From 1b8e1f074e4c7ac25e77b581ac734e17df0be2cc Mon Sep 17 00:00:00 2001 From: Robert Knight Date: Mon, 16 Dec 2024 15:28:18 +0000 Subject: [PATCH 1/2] Translation sync --- crowdin/translated/api.ca.json | 4 +- crowdin/translated/api.de.json | 182 ++-- crowdin/translated/api.es-es.json | 6 +- crowdin/translated/api.fr.json | 4 +- crowdin/translated/api.ja.json | 2 +- crowdin/translated/api.nl.json | 4 +- crowdin/translated/api.pl.json | 6 +- lang/ca/typeshed/stdlib/gc.pyi | 83 +- lang/ca/typeshed/stdlib/log.pyi | 111 ++- lang/ca/typeshed/stdlib/machine.pyi | 93 +- lang/ca/typeshed/stdlib/math.pyi | 257 ++--- lang/ca/typeshed/stdlib/microbit/__init__.pyi | 899 ++++++++++-------- .../stdlib/microbit/accelerometer.pyi | 110 ++- lang/ca/typeshed/stdlib/microbit/audio.pyi | 188 ++-- lang/ca/typeshed/stdlib/microbit/compass.pyi | 66 +- lang/ca/typeshed/stdlib/microbit/display.pyi | 123 ++- lang/ca/typeshed/stdlib/microbit/i2c.pyi | 66 +- .../typeshed/stdlib/microbit/microphone.pyi | 62 +- lang/ca/typeshed/stdlib/microbit/speaker.pyi | 17 +- lang/ca/typeshed/stdlib/microbit/spi.pyi | 71 +- lang/ca/typeshed/stdlib/microbit/uart.pyi | 115 ++- lang/ca/typeshed/stdlib/micropython.pyi | 157 +-- lang/ca/typeshed/stdlib/music.pyi | 173 ++-- lang/ca/typeshed/stdlib/neopixel.pyi | 93 +- lang/ca/typeshed/stdlib/os.pyi | 74 +- lang/ca/typeshed/stdlib/radio.pyi | 166 ++-- lang/ca/typeshed/stdlib/random.pyi | 86 +- lang/ca/typeshed/stdlib/speech.pyi | 157 +-- lang/ca/typeshed/stdlib/struct.pyi | 73 +- lang/ca/typeshed/stdlib/sys.pyi | 63 +- lang/ca/typeshed/stdlib/time.pyi | 172 ++-- lang/de/typeshed/stdlib/gc.pyi | 83 +- lang/de/typeshed/stdlib/log.pyi | 111 ++- lang/de/typeshed/stdlib/machine.pyi | 93 +- lang/de/typeshed/stdlib/math.pyi | 257 ++--- lang/de/typeshed/stdlib/microbit/__init__.pyi | 894 +++++++++-------- .../stdlib/microbit/accelerometer.pyi | 110 ++- lang/de/typeshed/stdlib/microbit/audio.pyi | 188 ++-- lang/de/typeshed/stdlib/microbit/compass.pyi | 66 +- lang/de/typeshed/stdlib/microbit/display.pyi | 123 ++- lang/de/typeshed/stdlib/microbit/i2c.pyi | 66 +- .../typeshed/stdlib/microbit/microphone.pyi | 62 +- lang/de/typeshed/stdlib/microbit/speaker.pyi | 17 +- lang/de/typeshed/stdlib/microbit/spi.pyi | 71 +- lang/de/typeshed/stdlib/microbit/uart.pyi | 115 ++- lang/de/typeshed/stdlib/micropython.pyi | 155 +-- lang/de/typeshed/stdlib/music.pyi | 173 ++-- lang/de/typeshed/stdlib/neopixel.pyi | 93 +- lang/de/typeshed/stdlib/os.pyi | 74 +- lang/de/typeshed/stdlib/radio.pyi | 162 ++-- lang/de/typeshed/stdlib/random.pyi | 85 +- lang/de/typeshed/stdlib/speech.pyi | 154 +-- lang/de/typeshed/stdlib/struct.pyi | 73 +- lang/de/typeshed/stdlib/sys.pyi | 60 +- lang/de/typeshed/stdlib/time.pyi | 167 ++-- lang/es-es/typeshed/stdlib/gc.pyi | 83 +- lang/es-es/typeshed/stdlib/log.pyi | 111 ++- lang/es-es/typeshed/stdlib/machine.pyi | 93 +- lang/es-es/typeshed/stdlib/math.pyi | 257 ++--- .../typeshed/stdlib/microbit/__init__.pyi | 897 +++++++++-------- .../stdlib/microbit/accelerometer.pyi | 110 ++- lang/es-es/typeshed/stdlib/microbit/audio.pyi | 188 ++-- .../typeshed/stdlib/microbit/compass.pyi | 66 +- .../typeshed/stdlib/microbit/display.pyi | 123 ++- lang/es-es/typeshed/stdlib/microbit/i2c.pyi | 66 +- .../typeshed/stdlib/microbit/microphone.pyi | 62 +- .../typeshed/stdlib/microbit/speaker.pyi | 17 +- lang/es-es/typeshed/stdlib/microbit/spi.pyi | 71 +- lang/es-es/typeshed/stdlib/microbit/uart.pyi | 115 ++- lang/es-es/typeshed/stdlib/micropython.pyi | 156 +-- lang/es-es/typeshed/stdlib/music.pyi | 173 ++-- lang/es-es/typeshed/stdlib/neopixel.pyi | 93 +- lang/es-es/typeshed/stdlib/os.pyi | 74 +- lang/es-es/typeshed/stdlib/radio.pyi | 166 ++-- lang/es-es/typeshed/stdlib/random.pyi | 85 +- lang/es-es/typeshed/stdlib/speech.pyi | 157 +-- lang/es-es/typeshed/stdlib/struct.pyi | 73 +- lang/es-es/typeshed/stdlib/sys.pyi | 63 +- lang/es-es/typeshed/stdlib/time.pyi | 168 ++-- lang/fr/typeshed/stdlib/gc.pyi | 83 +- lang/fr/typeshed/stdlib/log.pyi | 111 ++- lang/fr/typeshed/stdlib/machine.pyi | 93 +- lang/fr/typeshed/stdlib/math.pyi | 257 ++--- lang/fr/typeshed/stdlib/microbit/__init__.pyi | 898 +++++++++-------- .../stdlib/microbit/accelerometer.pyi | 110 ++- lang/fr/typeshed/stdlib/microbit/audio.pyi | 188 ++-- lang/fr/typeshed/stdlib/microbit/compass.pyi | 66 +- lang/fr/typeshed/stdlib/microbit/display.pyi | 123 ++- lang/fr/typeshed/stdlib/microbit/i2c.pyi | 66 +- .../typeshed/stdlib/microbit/microphone.pyi | 62 +- lang/fr/typeshed/stdlib/microbit/speaker.pyi | 17 +- lang/fr/typeshed/stdlib/microbit/spi.pyi | 71 +- lang/fr/typeshed/stdlib/microbit/uart.pyi | 115 ++- lang/fr/typeshed/stdlib/micropython.pyi | 156 +-- lang/fr/typeshed/stdlib/music.pyi | 173 ++-- lang/fr/typeshed/stdlib/neopixel.pyi | 93 +- lang/fr/typeshed/stdlib/os.pyi | 74 +- lang/fr/typeshed/stdlib/radio.pyi | 166 ++-- lang/fr/typeshed/stdlib/random.pyi | 85 +- lang/fr/typeshed/stdlib/speech.pyi | 157 +-- lang/fr/typeshed/stdlib/struct.pyi | 73 +- lang/fr/typeshed/stdlib/sys.pyi | 63 +- lang/fr/typeshed/stdlib/time.pyi | 171 ++-- lang/ja/typeshed/stdlib/gc.pyi | 83 +- lang/ja/typeshed/stdlib/log.pyi | 111 ++- lang/ja/typeshed/stdlib/machine.pyi | 93 +- lang/ja/typeshed/stdlib/math.pyi | 257 ++--- lang/ja/typeshed/stdlib/microbit/__init__.pyi | 894 +++++++++-------- .../stdlib/microbit/accelerometer.pyi | 110 ++- lang/ja/typeshed/stdlib/microbit/audio.pyi | 188 ++-- lang/ja/typeshed/stdlib/microbit/compass.pyi | 66 +- lang/ja/typeshed/stdlib/microbit/display.pyi | 123 ++- lang/ja/typeshed/stdlib/microbit/i2c.pyi | 66 +- .../typeshed/stdlib/microbit/microphone.pyi | 62 +- lang/ja/typeshed/stdlib/microbit/speaker.pyi | 17 +- lang/ja/typeshed/stdlib/microbit/spi.pyi | 71 +- lang/ja/typeshed/stdlib/microbit/uart.pyi | 115 ++- lang/ja/typeshed/stdlib/micropython.pyi | 155 +-- lang/ja/typeshed/stdlib/music.pyi | 173 ++-- lang/ja/typeshed/stdlib/neopixel.pyi | 93 +- lang/ja/typeshed/stdlib/os.pyi | 74 +- lang/ja/typeshed/stdlib/radio.pyi | 165 ++-- lang/ja/typeshed/stdlib/random.pyi | 85 +- lang/ja/typeshed/stdlib/speech.pyi | 157 +-- lang/ja/typeshed/stdlib/struct.pyi | 73 +- lang/ja/typeshed/stdlib/sys.pyi | 60 +- lang/ja/typeshed/stdlib/time.pyi | 167 ++-- lang/ko/typeshed/stdlib/gc.pyi | 83 +- lang/ko/typeshed/stdlib/log.pyi | 111 ++- lang/ko/typeshed/stdlib/machine.pyi | 93 +- lang/ko/typeshed/stdlib/math.pyi | 257 ++--- lang/ko/typeshed/stdlib/microbit/__init__.pyi | 888 +++++++++-------- .../stdlib/microbit/accelerometer.pyi | 106 ++- lang/ko/typeshed/stdlib/microbit/audio.pyi | 137 ++- lang/ko/typeshed/stdlib/microbit/compass.pyi | 66 +- lang/ko/typeshed/stdlib/microbit/display.pyi | 123 ++- lang/ko/typeshed/stdlib/microbit/i2c.pyi | 66 +- .../typeshed/stdlib/microbit/microphone.pyi | 62 +- lang/ko/typeshed/stdlib/microbit/speaker.pyi | 17 +- lang/ko/typeshed/stdlib/microbit/spi.pyi | 71 +- lang/ko/typeshed/stdlib/microbit/uart.pyi | 115 ++- lang/ko/typeshed/stdlib/micropython.pyi | 155 +-- lang/ko/typeshed/stdlib/music.pyi | 173 ++-- lang/ko/typeshed/stdlib/neopixel.pyi | 93 +- lang/ko/typeshed/stdlib/os.pyi | 74 +- lang/ko/typeshed/stdlib/radio.pyi | 161 ++-- lang/ko/typeshed/stdlib/random.pyi | 85 +- lang/ko/typeshed/stdlib/speech.pyi | 157 +-- lang/ko/typeshed/stdlib/struct.pyi | 73 +- lang/ko/typeshed/stdlib/sys.pyi | 60 +- lang/ko/typeshed/stdlib/time.pyi | 167 ++-- lang/lol/typeshed/stdlib/gc.pyi | 83 +- lang/lol/typeshed/stdlib/log.pyi | 111 ++- lang/lol/typeshed/stdlib/machine.pyi | 93 +- lang/lol/typeshed/stdlib/math.pyi | 257 ++--- .../lol/typeshed/stdlib/microbit/__init__.pyi | 894 +++++++++-------- .../stdlib/microbit/accelerometer.pyi | 110 ++- lang/lol/typeshed/stdlib/microbit/audio.pyi | 187 ++-- lang/lol/typeshed/stdlib/microbit/compass.pyi | 66 +- lang/lol/typeshed/stdlib/microbit/display.pyi | 123 ++- lang/lol/typeshed/stdlib/microbit/i2c.pyi | 66 +- .../typeshed/stdlib/microbit/microphone.pyi | 62 +- lang/lol/typeshed/stdlib/microbit/speaker.pyi | 17 +- lang/lol/typeshed/stdlib/microbit/spi.pyi | 71 +- lang/lol/typeshed/stdlib/microbit/uart.pyi | 115 ++- lang/lol/typeshed/stdlib/micropython.pyi | 155 +-- lang/lol/typeshed/stdlib/music.pyi | 173 ++-- lang/lol/typeshed/stdlib/neopixel.pyi | 93 +- lang/lol/typeshed/stdlib/os.pyi | 74 +- lang/lol/typeshed/stdlib/radio.pyi | 159 ++-- lang/lol/typeshed/stdlib/random.pyi | 85 +- lang/lol/typeshed/stdlib/speech.pyi | 154 +-- lang/lol/typeshed/stdlib/struct.pyi | 73 +- lang/lol/typeshed/stdlib/sys.pyi | 60 +- lang/lol/typeshed/stdlib/time.pyi | 166 ++-- lang/nl/typeshed/stdlib/gc.pyi | 83 +- lang/nl/typeshed/stdlib/log.pyi | 111 ++- lang/nl/typeshed/stdlib/machine.pyi | 93 +- lang/nl/typeshed/stdlib/math.pyi | 257 ++--- lang/nl/typeshed/stdlib/microbit/__init__.pyi | 899 ++++++++++-------- .../stdlib/microbit/accelerometer.pyi | 110 ++- lang/nl/typeshed/stdlib/microbit/audio.pyi | 188 ++-- lang/nl/typeshed/stdlib/microbit/compass.pyi | 66 +- lang/nl/typeshed/stdlib/microbit/display.pyi | 123 ++- lang/nl/typeshed/stdlib/microbit/i2c.pyi | 66 +- .../typeshed/stdlib/microbit/microphone.pyi | 62 +- lang/nl/typeshed/stdlib/microbit/speaker.pyi | 17 +- lang/nl/typeshed/stdlib/microbit/spi.pyi | 71 +- lang/nl/typeshed/stdlib/microbit/uart.pyi | 115 ++- lang/nl/typeshed/stdlib/micropython.pyi | 154 +-- lang/nl/typeshed/stdlib/music.pyi | 173 ++-- lang/nl/typeshed/stdlib/neopixel.pyi | 93 +- lang/nl/typeshed/stdlib/os.pyi | 74 +- lang/nl/typeshed/stdlib/radio.pyi | 166 ++-- lang/nl/typeshed/stdlib/random.pyi | 86 +- lang/nl/typeshed/stdlib/speech.pyi | 154 +-- lang/nl/typeshed/stdlib/struct.pyi | 73 +- lang/nl/typeshed/stdlib/sys.pyi | 61 +- lang/nl/typeshed/stdlib/time.pyi | 168 ++-- lang/pl/typeshed/stdlib/gc.pyi | 83 +- lang/pl/typeshed/stdlib/log.pyi | 111 ++- lang/pl/typeshed/stdlib/machine.pyi | 93 +- lang/pl/typeshed/stdlib/math.pyi | 257 ++--- lang/pl/typeshed/stdlib/microbit/__init__.pyi | 899 ++++++++++-------- .../stdlib/microbit/accelerometer.pyi | 110 ++- lang/pl/typeshed/stdlib/microbit/audio.pyi | 187 ++-- lang/pl/typeshed/stdlib/microbit/compass.pyi | 66 +- lang/pl/typeshed/stdlib/microbit/display.pyi | 123 ++- lang/pl/typeshed/stdlib/microbit/i2c.pyi | 66 +- .../typeshed/stdlib/microbit/microphone.pyi | 62 +- lang/pl/typeshed/stdlib/microbit/speaker.pyi | 17 +- lang/pl/typeshed/stdlib/microbit/spi.pyi | 71 +- lang/pl/typeshed/stdlib/microbit/uart.pyi | 115 ++- lang/pl/typeshed/stdlib/micropython.pyi | 156 +-- lang/pl/typeshed/stdlib/music.pyi | 173 ++-- lang/pl/typeshed/stdlib/neopixel.pyi | 93 +- lang/pl/typeshed/stdlib/os.pyi | 74 +- lang/pl/typeshed/stdlib/radio.pyi | 166 ++-- lang/pl/typeshed/stdlib/random.pyi | 86 +- lang/pl/typeshed/stdlib/speech.pyi | 157 +-- lang/pl/typeshed/stdlib/struct.pyi | 73 +- lang/pl/typeshed/stdlib/sys.pyi | 63 +- lang/pl/typeshed/stdlib/time.pyi | 173 ++-- lang/zh-cn/typeshed/stdlib/gc.pyi | 83 +- lang/zh-cn/typeshed/stdlib/log.pyi | 111 ++- lang/zh-cn/typeshed/stdlib/machine.pyi | 93 +- lang/zh-cn/typeshed/stdlib/math.pyi | 257 ++--- .../typeshed/stdlib/microbit/__init__.pyi | 894 +++++++++-------- .../stdlib/microbit/accelerometer.pyi | 110 ++- lang/zh-cn/typeshed/stdlib/microbit/audio.pyi | 188 ++-- .../typeshed/stdlib/microbit/compass.pyi | 66 +- .../typeshed/stdlib/microbit/display.pyi | 123 ++- lang/zh-cn/typeshed/stdlib/microbit/i2c.pyi | 66 +- .../typeshed/stdlib/microbit/microphone.pyi | 62 +- .../typeshed/stdlib/microbit/speaker.pyi | 17 +- lang/zh-cn/typeshed/stdlib/microbit/spi.pyi | 71 +- lang/zh-cn/typeshed/stdlib/microbit/uart.pyi | 115 ++- lang/zh-cn/typeshed/stdlib/micropython.pyi | 155 +-- lang/zh-cn/typeshed/stdlib/music.pyi | 173 ++-- lang/zh-cn/typeshed/stdlib/neopixel.pyi | 93 +- lang/zh-cn/typeshed/stdlib/os.pyi | 74 +- lang/zh-cn/typeshed/stdlib/radio.pyi | 165 ++-- lang/zh-cn/typeshed/stdlib/random.pyi | 85 +- lang/zh-cn/typeshed/stdlib/speech.pyi | 157 +-- lang/zh-cn/typeshed/stdlib/struct.pyi | 73 +- lang/zh-cn/typeshed/stdlib/sys.pyi | 62 +- lang/zh-cn/typeshed/stdlib/time.pyi | 167 ++-- lang/zh-tw/typeshed/stdlib/gc.pyi | 83 +- lang/zh-tw/typeshed/stdlib/log.pyi | 109 ++- lang/zh-tw/typeshed/stdlib/machine.pyi | 93 +- lang/zh-tw/typeshed/stdlib/math.pyi | 257 ++--- .../typeshed/stdlib/microbit/__init__.pyi | 886 +++++++++-------- .../stdlib/microbit/accelerometer.pyi | 106 ++- lang/zh-tw/typeshed/stdlib/microbit/audio.pyi | 133 ++- .../typeshed/stdlib/microbit/compass.pyi | 66 +- .../typeshed/stdlib/microbit/display.pyi | 123 ++- lang/zh-tw/typeshed/stdlib/microbit/i2c.pyi | 66 +- .../typeshed/stdlib/microbit/microphone.pyi | 62 +- .../typeshed/stdlib/microbit/speaker.pyi | 17 +- lang/zh-tw/typeshed/stdlib/microbit/spi.pyi | 71 +- lang/zh-tw/typeshed/stdlib/microbit/uart.pyi | 115 ++- lang/zh-tw/typeshed/stdlib/micropython.pyi | 155 +-- lang/zh-tw/typeshed/stdlib/music.pyi | 173 ++-- lang/zh-tw/typeshed/stdlib/neopixel.pyi | 93 +- lang/zh-tw/typeshed/stdlib/os.pyi | 74 +- lang/zh-tw/typeshed/stdlib/radio.pyi | 167 ++-- lang/zh-tw/typeshed/stdlib/random.pyi | 85 +- lang/zh-tw/typeshed/stdlib/speech.pyi | 157 +-- lang/zh-tw/typeshed/stdlib/struct.pyi | 73 +- lang/zh-tw/typeshed/stdlib/sys.pyi | 60 +- lang/zh-tw/typeshed/stdlib/time.pyi | 168 ++-- 271 files changed, 21808 insertions(+), 16352 deletions(-) diff --git a/crowdin/translated/api.ca.json b/crowdin/translated/api.ca.json index 6206889..079bb59 100644 --- a/crowdin/translated/api.ca.json +++ b/crowdin/translated/api.ca.json @@ -3460,7 +3460,7 @@ "description": "(function name) Read at most ``nbytes`` while continuously writing the single byte given by ``out``." }, "microbit.spi.read.summary": { - "message": "Llegeix bytes", + "message": "Llegeix com a màxim {{nbytes}} mentre escriu contínuament l'únic byte donat per {{out}}.", "description": "Read at most ``nbytes`` while continuously writing the single byte given by ``out``." }, "microbit.spi.read.param-name.nbytes": { @@ -3476,7 +3476,7 @@ "description": "(parameter name) The byte value to write (default 0)." }, "microbit.spi.read.param-doc.out": { - "message": "The byte value to write (default 0).", + "message": "El valor del byte a escriure (per defecte 0).", "description": "Parameter docs" }, "microbit.spi.write": { diff --git a/crowdin/translated/api.de.json b/crowdin/translated/api.de.json index 3050b28..cf9f751 100644 --- a/crowdin/translated/api.de.json +++ b/crowdin/translated/api.de.json @@ -84,7 +84,7 @@ "description": "(field name) Milliseconds timestamp format." }, "log.MILLISECONDS.summary": { - "message": "Millisekunden Zeitstempelformat.", + "message": "Zeitstempelformat: Millisekunden", "description": "Milliseconds timestamp format." }, "log.SECONDS": { @@ -92,7 +92,7 @@ "description": "(field name) Seconds timestamp format." }, "log.SECONDS.summary": { - "message": "Sekunden Zeitstempelformat.", + "message": "Zeitstempelformat: Sekunden", "description": "Seconds timestamp format." }, "log.MINUTES": { @@ -100,7 +100,7 @@ "description": "(field name) Minutes timestamp format." }, "log.MINUTES.summary": { - "message": "Minuten Zeitstempelformat.", + "message": "Zeitstempelformat: Minuten", "description": "Minutes timestamp format." }, "log.HOURS": { @@ -108,7 +108,7 @@ "description": "(field name) Hours timestamp format." }, "log.HOURS.summary": { - "message": "Stunden Zeitstempelformat.", + "message": "Zeitstempelformat: Stunden", "description": "Hours timestamp format." }, "log.DAYS": { @@ -460,7 +460,7 @@ "description": "(function name) Calculate ``x`` with the sign of ``y``." }, "math.copysign.summary": { - "message": "Berechne {{x}} mit dem Vorzeichen von {{y}}.", + "message": "Berechnet {{x}} mit dem Vorzeichen von {{y}}.", "description": "Calculate ``x`` with the sign of ``y``." }, "math.copysign.param-name.x": { @@ -564,7 +564,7 @@ "description": "(function name) Calculate the remainder of ``x/y``." }, "math.fmod.summary": { - "message": "Berechne den Rest von {{x/y}}.", + "message": "Berechnet den Rest von {{x/y}}.", "description": "Calculate the remainder of ``x/y``." }, "math.fmod.param-name.x": { @@ -636,7 +636,7 @@ "description": "(function name) Check if a value is not-a-number (NaN)." }, "math.isnan.summary": { - "message": "Prüft, ob ein Wert keine Zahl (NaN ... Not A Number) ist.", + "message": "Prüft, ob ein Wert keine Zahl (NaN bzw. Not A Number) ist.", "description": "Check if a value is not-a-number (NaN)." }, "math.isnan.param-name.x": { @@ -652,7 +652,7 @@ "description": "(function name) Calculate ``x * (2**exp)``." }, "math.ldexp.summary": { - "message": "Berechne {{x * (2**exp)}}.", + "message": "Berechnet {{x * (2**exp)}}.", "description": "Calculate ``x * (2**exp)``." }, "math.ldexp.param-name.exp": { @@ -700,7 +700,7 @@ "description": "(function name) Calculate the fractional and integral parts of ``x``." }, "math.modf.summary": { - "message": "Berechne die gebrochenen und ganzzahligen Teile von {{x}}.", + "message": "Berechnet die gebrochenen und ganzzahligen Teile von {{x}}.", "description": "Calculate the fractional and integral parts of ``x``." }, "math.modf.param-name.x": { @@ -820,7 +820,7 @@ "description": "(field name) Base of the natural logarithm" }, "math.e.summary": { - "message": "Basis des natürlichen Logarithmus", + "message": "Basis des natürlichen Logarithmus.", "description": "Base of the natural logarithm" }, "math.pi": { @@ -828,7 +828,7 @@ "description": "(field name) The ratio of a circle's circumference to its diameter" }, "math.pi.summary": { - "message": "Das Verhältnis des Umfangs eines Kreises zu seinem Durchmesser", + "message": "Das Verhältnis des Umfangs eines Kreises zu seinem Durchmesser.", "description": "The ratio of a circle's circumference to its diameter" }, "microbit": { @@ -844,7 +844,7 @@ "description": "(function name) Schedule to run a function at the interval specified by the time arguments **V2 only**." }, "microbit.run_every.summary": { - "message": "Plant die Ausführung einer Funktion in dem durch die Zeitargumente festgelegten Intervall **nur V2**.", + "message": "Plant die Ausführung einer Funktion in dem durch die Zeitargumente festgelegten Intervall. **Nur micro:bit V2**.", "description": "Schedule to run a function at the interval specified by the time arguments **V2 only**." }, "microbit.run_every.param-name.callback": { @@ -988,7 +988,7 @@ "description": "(function name) Wait for ``n`` milliseconds." }, "microbit.sleep.summary": { - "message": "Warte auf {{n}} Millisekunden.", + "message": "Wartet {{n}} Millisekunden.", "description": "Wait for ``n`` milliseconds." }, "microbit.sleep.param-name.n": { @@ -1068,7 +1068,7 @@ "description": "(field name) The left button ``Button`` object." }, "microbit.button_a.summary": { - "message": "Das {{Button}}-Objekt der linken Taste.", + "message": "Das Objekt {{Button}} der linken Taste.", "description": "The left button ``Button`` object." }, "microbit.button_b": { @@ -1076,7 +1076,7 @@ "description": "(field name) The right button ``Button`` object." }, "microbit.button_b.summary": { - "message": "Das {{Button}}-Objekt der rechten Taste.", + "message": "Das Objekt {{Button}} der rechten Taste.", "description": "The right button ``Button`` object." }, "microbit.MicroBitDigitalPin": { @@ -1148,7 +1148,7 @@ "description": "(function name) Output a PWM signal on the pin, with the duty cycle proportional to ``value``." }, "microbit.MicroBitDigitalPin.write_analog.summary": { - "message": "Erzeugt ein PWM-Signal am Pin mit der Einschaltdauer proportional zu {{value}}.", + "message": "Gib ein PWM-Signal am Pin aus, bei dem das Verhältnis von An- zu Auszeit proportional zu {{value}} ist.", "description": "Output a PWM signal on the pin, with the duty cycle proportional to ``value``." }, "microbit.MicroBitDigitalPin.write_analog.param-name.value": { @@ -1164,7 +1164,7 @@ "description": "(function name) Set the period of the PWM signal being output to ``period`` in milliseconds." }, "microbit.MicroBitDigitalPin.set_analog_period.summary": { - "message": "Setzt die Periodendauer des PWM-Signals, das ausgegeben wird, auf {{period}} in Millisekunden.", + "message": "Setze die Periodendauer für die Ausgabe des PWM-Signals auf {{period}} in Mikrosekunden.", "description": "Set the period of the PWM signal being output to ``period`` in milliseconds." }, "microbit.MicroBitDigitalPin.set_analog_period.param-name.period": { @@ -1180,7 +1180,7 @@ "description": "(function name) Set the period of the PWM signal being output to ``period`` in microseconds." }, "microbit.MicroBitDigitalPin.set_analog_period_microseconds.summary": { - "message": "Setze die Periodendauer für die Ausgabe des PWM-Signals auf {{period}} in Mikrosekunden.", + "message": "Setzt den Zeitraum des PWM-Signals, das ausgegeben wird, auf {{period}} in Mikrosekunden.", "description": "Set the period of the PWM signal being output to ``period`` in microseconds." }, "microbit.MicroBitDigitalPin.set_analog_period_microseconds.param-name.period": { @@ -1188,7 +1188,7 @@ "description": "(parameter name) The period in microseconds with a minimum valid value of 256µs." }, "microbit.MicroBitDigitalPin.set_analog_period_microseconds.param-doc.period": { - "message": "Die Periodendauer in Mikrosekunden mit einem Mindestwert von 256μs.", + "message": "Die Periodendauer in Mikrosekunden mit einem Mindestwert von 256 μs.", "description": "Parameter docs" }, "microbit.MicroBitAnalogDigitalPin": { @@ -1228,7 +1228,7 @@ "description": "(function name) Set the touch mode for the pin." }, "microbit.MicroBitTouchPin.set_touch_mode.summary": { - "message": "Legt den Touchmodus für den Pin fest.", + "message": "Legt den Berührungsmodus für den Pin fest.", "description": "Set the touch mode for the pin." }, "microbit.MicroBitTouchPin.set_touch_mode.param-name.value": { @@ -1396,7 +1396,7 @@ "description": "(field name) A touch sensitive logo pin on the front of the micro:bit, which by default is set to capacitive touch mode." }, "microbit.pin_logo.summary": { - "message": "Ein berührungsempfindlicher Logo-Pin auf der Vorderseite des micro:bit, der standardmäßig auf den kapazitiven Touch-Modus eingestellt ist.", + "message": "Ein berührungsempfindlicher Logo-Pin auf der Vorderseite des micro:bit, der standardmäßig auf den kapazitiven Berührungsmodus eingestellt ist.", "description": "A touch sensitive logo pin on the front of the micro:bit, which by default is set to capacitive touch mode." }, "microbit.pin_speaker": { @@ -1404,7 +1404,7 @@ "description": "(field name) A pin to address the micro:bit speaker." }, "microbit.pin_speaker.summary": { - "message": "Ein Pin zur Ansteuerung des micro:bit Lautsprechers.", + "message": "Ein Pin zur Ansteuerung des micro:bit-Lautsprechers.", "description": "A pin to address the micro:bit speaker." }, "microbit.Image": { @@ -1948,7 +1948,7 @@ "description": "(function name) Create an image from a string describing which LEDs are lit." }, "microbit.Image.__init__-1.summary": { - "message": "Erstellen Sie ein Bild aus einer Zeichenkette, die beschreibt, welche LEDs leuchten.", + "message": "Erstellt ein Bild aus einer Zeichenkette, die beschreibt, welche LEDs leuchten.", "description": "Create an image from a string describing which LEDs are lit." }, "microbit.Image.__init__-1.param-name.string": { @@ -2068,7 +2068,7 @@ "description": "(function name) Create a new image by shifting the picture left." }, "microbit.Image.shift_left.summary": { - "message": "Erstellen Sie ein neues Bild, indem Sie das Bild nach links verschieben.", + "message": "Erstellt ein neues Bild, indem das Bild nach links verschoben wird.", "description": "Create a new image by shifting the picture left." }, "microbit.Image.shift_left.param-name.n": { @@ -2084,7 +2084,7 @@ "description": "(function name) Create a new image by shifting the picture right." }, "microbit.Image.shift_right.summary": { - "message": "Erstellen Sie ein neues Bild, indem Sie das Bild nach rechts verschieben.", + "message": "Erstellt ein neues Bild, indem das Bild nach rechts verschoben wird.", "description": "Create a new image by shifting the picture right." }, "microbit.Image.shift_right.param-name.n": { @@ -2100,7 +2100,7 @@ "description": "(function name) Create a new image by shifting the picture up." }, "microbit.Image.shift_up.summary": { - "message": "Erstellen Sie ein neues Bild, indem Sie das Bild nach oben verschoben wird.", + "message": "Erstellt ein neues Bild, indem das Bild nach oben verschoben wird.", "description": "Create a new image by shifting the picture up." }, "microbit.Image.shift_up.param-name.n": { @@ -2116,7 +2116,7 @@ "description": "(function name) Create a new image by shifting the picture down." }, "microbit.Image.shift_down.summary": { - "message": "Erstellen Sie ein neues Bild, indem Sie das Bild nach unten verschoben wird.", + "message": "Erstellt ein neues Bild, indem das Bild nach unten verschoben wird.", "description": "Create a new image by shifting the picture down." }, "microbit.Image.shift_down.param-name.n": { @@ -2484,7 +2484,7 @@ "description": "(function name) Get the acceleration measurements in all axes at once as a tuple." }, "microbit.accelerometer.get_values.summary": { - "message": "Erhalten Sie die Beschleunigungsmessungen in allen Achsen auf einmal als Tupel.", + "message": "Erhalte die Beschleunigungsmessung in allen Achsen auf einmal als Tupel.", "description": "Get the acceleration measurements in all axes at once as a tuple." }, "microbit.accelerometer.get_strength": { @@ -2492,7 +2492,7 @@ "description": "(function name) Get the acceleration measurement of all axes combined, as a positive integer. This is the Pythagorean sum of the X, Y and Z axes." }, "microbit.accelerometer.get_strength.summary": { - "message": "Erhalte die Beschleunigungsmessung aller Achsen als positive Ganzzahl. Dies ist die euklidische Summe der X-, Y- und Z-Achsen.", + "message": "Erhalte die Beschleunigungsmessung aller Achsen als positive Ganzzahl. Dies ist die euklidische Summe der x-, y- und z-Achsen.", "description": "Get the acceleration measurement of all axes combined, as a positive integer. This is the Pythagorean sum of the X, Y and Z axes." }, "microbit.accelerometer.current_gesture": { @@ -2548,7 +2548,7 @@ "description": "(function name) Set the accelerometer sensitivity range, in g (standard gravity), to the closest values supported by the hardware, so it rounds to either ``2``, ``4``, or ``8`` g." }, "microbit.accelerometer.set_range.summary": { - "message": "Legen Sie den Bereich des Beschleunigungsmessers in g (Fallbeschleunigung) auf den nächstgelegenen Wert fest, welcher von der Hardware unterstützt wird. Diese sind {{2}}, {{4}}oder {{8}} g.", + "message": "Legt den Bereich des Beschleunigungsmessers in g (Fallbeschleunigung) auf den nächstgelegenen Wert fest, welcher von der Hardware unterstützt wird. Diese sind {{2}}, {{4}}oder {{8}} g.", "description": "Set the accelerometer sensitivity range, in g (standard gravity), to the closest values supported by the hardware, so it rounds to either ``2``, ``4``, or ``8`` g." }, "microbit.accelerometer.set_range.param-name.value": { @@ -2612,7 +2612,7 @@ "description": "(function name) Check whether a sound is playing." }, "microbit.audio.is_playing.summary": { - "message": "Überprüfen Sie, ob ein Ton abgespielt wird.", + "message": "Überprüft, ob ein Ton abgespielt wird.", "description": "Check whether a sound is playing." }, "microbit.audio.stop": { @@ -2620,7 +2620,7 @@ "description": "(function name) Stop all audio playback." }, "microbit.audio.stop.summary": { - "message": "Stoppe jede Audio-Wiedergabe.", + "message": "Stoppt jede Audio-Wiedergabe.", "description": "Stop all audio playback." }, "microbit.audio.SoundEffect": { @@ -2780,7 +2780,7 @@ "description": "(field name) Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``" }, "microbit.audio.SoundEffect.fx.summary": { - "message": "Effekt, der dem Sound hinzugefügt werden soll, in Frage kommende Werte: {{FX_TREMOLO}}, {{FX_VIBRATO}}, {{FX_WARBLE}}, oder {{FX_NONE}}", + "message": "Effekt, der dem Sound hinzugefügt werden soll. Mögliche Werte: {{FX_TREMOLO}}, {{FX_VIBRATO}}, {{FX_WARBLE}} oder {{FX_NONE}}", "description": "Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``" }, "microbit.audio.SoundEffect.shape": { @@ -2796,7 +2796,7 @@ "description": "(function name) Create a new sound effect." }, "microbit.audio.SoundEffect.__init__.summary": { - "message": "Erstelle einen neuen Soundeffekt. ", + "message": "Erstellt einen neuen Soundeffekt. ", "description": "Create a new sound effect." }, "microbit.audio.SoundEffect.__init__.param-name.duration": { @@ -2868,7 +2868,7 @@ "description": "(function name) Create a copy of this ``SoundEffect``." }, "microbit.audio.SoundEffect.copy.summary": { - "message": "Erstelle eine Kopie dieses {{SoundEffect}}. ", + "message": "Erstellt eine Kopie dieses {{SoundEffect}}. ", "description": "Create a copy of this ``SoundEffect``." }, "microbit.audio.AudioFrame": { @@ -2884,7 +2884,7 @@ "description": "(function name) Overwrite the data in this ``AudioFrame`` with the data from another ``AudioFrame`` instance." }, "microbit.audio.AudioFrame.copyfrom.summary": { - "message": "Überschreibe die Daten in diesem {{AudioFrame}} mit den Daten einer anderen {{AudioFrame}} Instanz. ", + "message": "Überschreibt die Daten in diesem {{AudioFrame}} mit den Daten einer anderen {{AudioFrame}}-Instanz. ", "description": "Overwrite the data in this ``AudioFrame`` with the data from another ``AudioFrame`` instance." }, "microbit.audio.AudioFrame.copyfrom.param-name.other": { @@ -2916,7 +2916,7 @@ "description": "(function name) Check is the compass is calibrated." }, "microbit.compass.is_calibrated.summary": { - "message": "Überprüfe, dass der Kompass kalibriert ist. ", + "message": "Überprüft, dass der Kompass kalibriert ist. ", "description": "Check is the compass is calibrated." }, "microbit.compass.clear_calibration": { @@ -2956,7 +2956,7 @@ "description": "(function name) Get the compass heading." }, "microbit.compass.heading.summary": { - "message": "Ermittle die Kompassrichtung. ", + "message": "Ermittelt die Kompassrichtung. ", "description": "Get the compass heading." }, "microbit.compass.get_field_strength": { @@ -2964,7 +2964,7 @@ "description": "(function name) Get the magnitude of the magnetic field around the device." }, "microbit.compass.get_field_strength.summary": { - "message": "Ermittle die Größe des Magnetfelds um das Gerät herum.", + "message": "Ermittelt die Größe des Magnetfelds um das Gerät herum.", "description": "Get the magnitude of the magnetic field around the device." }, "microbit.display": { @@ -3140,7 +3140,7 @@ "description": "(function name) Turn on the LED display." }, "microbit.display.on.summary": { - "message": "Das LED-Display einschalten.", + "message": "Schaltet das LED-Display ein.", "description": "Turn on the LED display." }, "microbit.display.off": { @@ -3148,7 +3148,7 @@ "description": "(function name) Turn off the LED display (disabling the display allows you to re-use the GPIO pins for other purposes)." }, "microbit.display.off.summary": { - "message": "Die LED-Anzeige ausschalten (Deaktivieren des Displays ermöglicht es dir, die GPIO-Pins für andere Zwecke zu verwenden).", + "message": "Schaltet das LED-Display aus (Deaktivieren des Displays ermöglicht es dir, die GPIO-Pins für andere Zwecke zu verwenden).", "description": "Turn off the LED display (disabling the display allows you to re-use the GPIO pins for other purposes)." }, "microbit.display.is_on": { @@ -3156,7 +3156,7 @@ "description": "(function name) Check whether the LED display is enabled." }, "microbit.display.is_on.summary": { - "message": "Überprüfung, ob die LED-Anzeige aktiviert ist.", + "message": "Überprüft, ob die LED-Anzeige aktiviert ist.", "description": "Check whether the LED display is enabled." }, "microbit.display.read_light_level": { @@ -3252,7 +3252,7 @@ "description": "(function name) Write bytes to a device." }, "microbit.i2c.write.summary": { - "message": "Schreibe Bytes auf ein Gerät.", + "message": "Schreibt Bytes auf ein Gerät.", "description": "Write bytes to a device." }, "microbit.i2c.write.param-name.addr": { @@ -3300,7 +3300,7 @@ "description": "(function name) Check if a sound was heard at least once since the last call." }, "microbit.microphone.was_event.summary": { - "message": "Überprüfung, ob seit dem letzten Anruf mindestens einmal ein Geräusch gehört wurde.", + "message": "Überprüft, ob seit dem letzten Anruf mindestens einmal ein Geräusch gehört wurde.", "description": "Check if a sound was heard at least once since the last call." }, "microbit.microphone.was_event.param-name.event": { @@ -3316,7 +3316,7 @@ "description": "(function name) Check the most recent sound event detected." }, "microbit.microphone.is_event.summary": { - "message": "Überprüfe das zuletzt erkannte Sound-Ereignis.", + "message": "Überprüft das zuletzt erkannte Sound-Ereignis.", "description": "Check the most recent sound event detected." }, "microbit.microphone.is_event.param-name.event": { @@ -3364,7 +3364,7 @@ "description": "(function name) Get the sound pressure level." }, "microbit.microphone.sound_level.summary": { - "message": "Ermittle den Schalldruckpegel. ", + "message": "Ermittelt den Schalldruckpegel. ", "description": "Get the sound pressure level." }, "microbit.speaker": { @@ -3380,7 +3380,7 @@ "description": "(function name) Turn the speaker off." }, "microbit.speaker.off.summary": { - "message": "Lautsprecher ausschalten. ", + "message": "Schaltet den Lautsprecher aus.", "description": "Turn the speaker off." }, "microbit.speaker.on": { @@ -3388,7 +3388,7 @@ "description": "(function name) Turn the speaker on." }, "microbit.speaker.on.summary": { - "message": "Lautsprecher einschalten. ", + "message": "Schaltet den Lautsprecher ein.", "description": "Turn the speaker on." }, "microbit.spi": { @@ -3484,7 +3484,7 @@ "description": "(function name) Write bytes to the bus." }, "microbit.spi.write.summary": { - "message": "Schreibe Bytes auf den Bus. ", + "message": "Schreibt Bytes auf den Bus. ", "description": "Write bytes to the bus." }, "microbit.spi.write.param-name.buffer": { @@ -3524,7 +3524,7 @@ "description": "(module name) Communicate with a device using a serial interface." }, "microbit.uart.summary": { - "message": "Verbindet mit einem Gerät über eine serielle Schnittstelle.", + "message": "Kommunikation mit einem Gerät über eine serielle Schnittstelle.", "description": "Communicate with a device using a serial interface." }, "microbit.uart.ODD": { @@ -3548,7 +3548,7 @@ "description": "(function name) Initialize serial communication." }, "microbit.uart.init.summary": { - "message": "Initialisiere die serielle Kommunikation.", + "message": "Initialisiert die serielle Kommunikation.", "description": "Initialize serial communication." }, "microbit.uart.init.param-name.baudrate": { @@ -3604,7 +3604,7 @@ "description": "(function name) Check if any data is waiting." }, "microbit.uart.any.summary": { - "message": "Überprüfen Sie, ob irgendwelche Daten warten.", + "message": "Überprüft, ob irgendwelche Daten warten.", "description": "Check if any data is waiting." }, "microbit.uart.read": { @@ -3628,7 +3628,7 @@ "description": "(function name) Read bytes into the ``buf``." }, "microbit.uart.readinto.summary": { - "message": "Lese Bytes in {{buf}}.", + "message": "Liest Bytes in {{buf}}.", "description": "Read bytes into the ``buf``." }, "microbit.uart.readinto.param-name.buf": { @@ -3652,7 +3652,7 @@ "description": "(function name) Read a line, ending in a newline character." }, "microbit.uart.readline.summary": { - "message": "Liest eine Zeile bis zum Zeilenumbruch.", + "message": "Liest eine Zeile bis zu einem Zeilenumbruch.", "description": "Read a line, ending in a newline character." }, "microbit.uart.write": { @@ -3764,7 +3764,7 @@ "description": "(function name) Lock the heap." }, "micropython.heap_lock.summary": { - "message": "Heap-Speicher sperren.", + "message": "Sperrt den Heap-Speicher.", "description": "Lock the heap." }, "micropython.heap_unlock": { @@ -3772,7 +3772,7 @@ "description": "(function name) Unlock the heap." }, "micropython.heap_unlock.summary": { - "message": "Heap-Speicher entsperren.", + "message": "Entsperrt den Heap-Speicher.", "description": "Unlock the heap." }, "micropython.kbd_intr": { @@ -3804,7 +3804,7 @@ "description": "(field name) Melody: the opening to Beethoven’s 5th Symphony in C minor." }, "music.DADADADUM.summary": { - "message": "Melodie: der Anfang von Beethovens 5. Symphonie in c-Moll.", + "message": "Melodie: Der Anfang von Beethovens 5. Symphonie in c-Moll.", "description": "Melody: the opening to Beethoven’s 5th Symphony in C minor." }, "music.ENTERTAINER": { @@ -3812,7 +3812,7 @@ "description": "(field name) Melody: the opening fragment of Scott Joplin’s Ragtime classic “The Entertainer”." }, "music.ENTERTAINER.summary": { - "message": "Melodie: die ersten Takte des Ragtime-Klassikers \"The Entertainer\" von Scott Joplin.", + "message": "Melodie: Die ersten Takte des Ragtime-Klassikers „The Entertainer“ von Scott Joplin.", "description": "Melody: the opening fragment of Scott Joplin’s Ragtime classic “The Entertainer”." }, "music.PRELUDE": { @@ -3836,7 +3836,7 @@ "description": "(field name) Melody: the Nyan Cat theme (http://www.nyan.cat/)." }, "music.NYAN.summary": { - "message": "Melodie: Die Nyan-Katze (http://www.nyan.cat/)", + "message": "Melodie: Nyan-Katze (http://www.nyan.cat/).", "description": "Melody: the Nyan Cat theme (http://www.nyan.cat/)." }, "music.RINGTONE": { @@ -3844,7 +3844,7 @@ "description": "(field name) Melody: something that sounds like a mobile phone ringtone." }, "music.RINGTONE.summary": { - "message": "Melodie: Etwas das wie ein Handy-Klingelton klingt.", + "message": "Melodie: Etwas, das wie ein Handy-Klingelton klingt.", "description": "Melody: something that sounds like a mobile phone ringtone." }, "music.FUNK": { @@ -3868,7 +3868,7 @@ "description": "(field name) Melody: “Happy Birthday to You…”" }, "music.BIRTHDAY.summary": { - "message": "Melodie: „Alles Gute zum Geburtstag…“", + "message": "Melodie: „Alles Gute zum Geburtstag …“", "description": "Melody: “Happy Birthday to You…”" }, "music.WEDDING": { @@ -3876,7 +3876,7 @@ "description": "(field name) Melody: the bridal chorus from Wagner’s opera “Lohengrin”." }, "music.WEDDING.summary": { - "message": "Melodie: der Hochzeitschor aus Wagners Oper \"Lohengrin\".", + "message": "Melodie: der Hochzeitschor aus Wagners Oper „Lohengrin“.", "description": "Melody: the bridal chorus from Wagner’s opera “Lohengrin”." }, "music.FUNERAL": { @@ -3884,7 +3884,7 @@ "description": "(field name) Melody: the “funeral march” otherwise known as Frédéric Chopin’s Piano Sonata No. 2 in B♭ minor, Op. 35." }, "music.FUNERAL.summary": { - "message": "Melodie: der \"Trauermarsch\", auch bekannt als Frédéric Chopins Klaviersonate Nr. 2 in b-Moll, op. 35.", + "message": "Melodie: Der „Trauermarsch“, auch bekannt als Frédéric Chopins Klaviersonate Nr. 2 in b-Moll, op. 35.", "description": "Melody: the “funeral march” otherwise known as Frédéric Chopin’s Piano Sonata No. 2 in B♭ minor, Op. 35." }, "music.PUNCHLINE": { @@ -3900,7 +3900,7 @@ "description": "(field name) Melody: John Philip Sousa’s march “Liberty Bell” aka, the theme for “Monty Python’s Flying Circus” (after which the Python programming language is named)." }, "music.PYTHON.summary": { - "message": "Melodie: John Philip Sousas Marsch \"Liberty Bell\", auch bekannt als das Thema von \"Monty Python's Flying Circus\" (nach dem die Programmiersprache Python benannt ist).", + "message": "Melodie: John Philip Sousas Marsch „Liberty Bell“, auch bekannt als die Titelmusik von „Monty Python's Flying Circus“ (nach dem die Programmiersprache Python benannt ist).", "description": "Melody: John Philip Sousa’s march “Liberty Bell” aka, the theme for “Monty Python’s Flying Circus” (after which the Python programming language is named)." }, "music.BADDY": { @@ -4116,7 +4116,7 @@ "description": "(function name) Initialise a new strip of neopixel LEDs controlled via a pin." }, "neopixel.NeoPixel.__init__.summary": { - "message": "Initialisierung eines neuen Streifens von Neopixel-LEDs, die über einen Pin gesteuert werden.", + "message": "Initialisiert einen neuen Streifen von Neopixel-LEDs, die über einen Pin gesteuert werden.", "description": "Initialise a new strip of neopixel LEDs controlled via a pin." }, "neopixel.NeoPixel.__init__.param-name.bpp": { @@ -4148,7 +4148,7 @@ "description": "(function name) Clear all the pixels." }, "neopixel.NeoPixel.clear.summary": { - "message": "Lösche alle Pixel.", + "message": "Löscht alle Pixel.", "description": "Clear all the pixels." }, "neopixel.NeoPixel.show": { @@ -4172,7 +4172,7 @@ "description": "(function name) Colour all pixels a given RGB/RGBW value (micro:bit V2 only)." }, "neopixel.NeoPixel.fill.summary": { - "message": "Alle Pixel mit einem bestimmten RGB/RGBW-Wert färben.", + "message": "Färbt alle Pixel mit einem bestimmten RGB/RGBW-Wert (nur micro:bit V2).", "description": "Colour all pixels a given RGB/RGBW value (micro:bit V2 only)." }, "neopixel.NeoPixel.fill.param-name.colour": { @@ -4252,7 +4252,7 @@ "description": "(function name) Remove (delete) a file." }, "os.remove.summary": { - "message": "Entferne (lösche) eine Datei.", + "message": "Entfernt / Löscht eine Datei.", "description": "Remove (delete) a file." }, "os.remove.param-name.filename": { @@ -4348,7 +4348,7 @@ "description": "(field name) Constant used to indicate a throughput of 1 MBit a second." }, "radio.RATE_1MBIT.summary": { - "message": "Konstante zur Angabe eines Durchsatzes von 1 MBit pro Sekunde.", + "message": "Konstante zur Angabe eines Durchsatzes von 1 MBit pro Sekunde.", "description": "Constant used to indicate a throughput of 1 MBit a second." }, "radio.RATE_2MBIT": { @@ -4356,7 +4356,7 @@ "description": "(field name) Constant used to indicate a throughput of 2 MBit a second." }, "radio.RATE_2MBIT.summary": { - "message": "Konstante zur Angabe eines Durchsatzes von 2 MBit pro Sekunde.", + "message": "Konstante zur Angabe eines Durchsatzes von 2 MBit pro Sekunde.", "description": "Constant used to indicate a throughput of 2 MBit a second." }, "radio.on": { @@ -4524,7 +4524,7 @@ "description": "(module name) Generate random numbers." }, "random.summary": { - "message": "Gibt eine Zufallszahl zurück.", + "message": "Zufallszahlen generieren.", "description": "Generate random numbers." }, "random.getrandbits": { @@ -4684,7 +4684,7 @@ "description": "(module name) Make the micro:bit talk, sing and make other speech like sounds." }, "speech.summary": { - "message": "Bringe den micro:bit dazu zu Sprechen, zu Singen und andere sprachähnliche Geräusche zu machen.", + "message": "Bringe den micro:bit zum Sprechen, singen und dazu, andere sprachähnliche Geräusche zu machen.", "description": "Make the micro:bit talk, sing and make other speech like sounds." }, "speech.translate": { @@ -4692,7 +4692,7 @@ "description": "(function name) Translate English words to phonemes." }, "speech.translate.summary": { - "message": "Übersetze englische Wörter in Sprache.", + "message": "Übersetzt englische Wörter in Sprache.", "description": "Translate English words to phonemes." }, "speech.translate.param-name.words": { @@ -4708,7 +4708,7 @@ "description": "(function name) Pronounce phonemes." }, "speech.pronounce.summary": { - "message": "Laute aussprechen.", + "message": "Spricht Laute aus.", "description": "Pronounce phonemes." }, "speech.pronounce.param-name.mouth": { @@ -4716,7 +4716,7 @@ "description": "(parameter name) A number representing the mouth of the voice" }, "speech.pronounce.param-doc.mouth": { - "message": "Eine Zahl, die den Mund der Stimme repräsentiert", + "message": "Eine Zahl, die den Mund der Stimme repräsentiert.", "description": "Parameter docs" }, "speech.pronounce.param-name.phonemes": { @@ -4724,7 +4724,7 @@ "description": "(parameter name) The string of phonemes to pronounce" }, "speech.pronounce.param-doc.phonemes": { - "message": "Die auszusprechenden Phoneme als Zeichenkette", + "message": "Die auszusprechende Laut als Zeichenkette.", "description": "Parameter docs" }, "speech.pronounce.param-name.pin": { @@ -4740,7 +4740,7 @@ "description": "(parameter name) A number representing the pitch of the voice" }, "speech.pronounce.param-doc.pitch": { - "message": "Eine Zahl, die die Tonhöhe der Stimme angibt", + "message": "Eine Zahl, die die Tonhöhe der Stimme angibt.", "description": "Parameter docs" }, "speech.pronounce.param-name.speed": { @@ -4748,7 +4748,7 @@ "description": "(parameter name) A number representing the speed of the voice" }, "speech.pronounce.param-doc.speed": { - "message": "Eine Zahl, die die Geschwindigkeit der Stimme angibt", + "message": "Eine Zahl, die die Geschwindigkeit der Stimme angibt.", "description": "Parameter docs" }, "speech.pronounce.param-name.throat": { @@ -4756,7 +4756,7 @@ "description": "(parameter name) A number representing the throat of the voice" }, "speech.pronounce.param-doc.throat": { - "message": "Eine Zahl, die den Klang der Stimme angibt", + "message": "Eine Zahl, die den Klang der Stimme angibt.", "description": "Parameter docs" }, "speech.say": { @@ -4772,7 +4772,7 @@ "description": "(parameter name) A number representing the mouth of the voice" }, "speech.say.param-doc.mouth": { - "message": "Eine Zahl, die den Mund der Stimme repräsentiert", + "message": "Eine Zahl, die den Mund der Stimme repräsentiert.", "description": "Parameter docs" }, "speech.say.param-name.pin": { @@ -4788,7 +4788,7 @@ "description": "(parameter name) A number representing the pitch of the voice" }, "speech.say.param-doc.pitch": { - "message": "Eine Zahl, die die Tonhöhe der Stimme angibt", + "message": "Eine Zahl, die die Tonhöhe der Stimme angibt.", "description": "Parameter docs" }, "speech.say.param-name.speed": { @@ -4796,7 +4796,7 @@ "description": "(parameter name) A number representing the speed of the voice" }, "speech.say.param-doc.speed": { - "message": "Eine Zahl, die die Geschwindigkeit der Stimme angibt", + "message": "Eine Zahl, die die Geschwindigkeit der Stimme angibt.", "description": "Parameter docs" }, "speech.say.param-name.throat": { @@ -4804,7 +4804,7 @@ "description": "(parameter name) A number representing the throat of the voice" }, "speech.say.param-doc.throat": { - "message": "Eine Zahl, die den Klang der Stimme angibt", + "message": "Eine Zahl, die den Klang der Stimme angibt.", "description": "Parameter docs" }, "speech.say.param-name.words": { @@ -4820,7 +4820,7 @@ "description": "(function name) Sing phonemes." }, "speech.sing.summary": { - "message": "Singe Phoneme", + "message": "Singt Laute.", "description": "Sing phonemes." }, "speech.sing.param-name.mouth": { @@ -4828,7 +4828,7 @@ "description": "(parameter name) A number representing the mouth of the voice" }, "speech.sing.param-doc.mouth": { - "message": "Eine Zahl, die den Mund der Stimme repräsentiert", + "message": "Eine Zahl, die den Mund der Stimme repräsentiert.", "description": "Parameter docs" }, "speech.sing.param-name.phonemes": { @@ -4836,7 +4836,7 @@ "description": "(parameter name) The string of words to sing." }, "speech.sing.param-doc.phonemes": { - "message": "Der zu singende String", + "message": "Der zu singende String.", "description": "Parameter docs" }, "speech.sing.param-name.pin": { @@ -4852,7 +4852,7 @@ "description": "(parameter name) A number representing the pitch of the voice" }, "speech.sing.param-doc.pitch": { - "message": "Eine Zahl, die die Tonhöhe der Stimme angibt", + "message": "Eine Zahl, die die Tonhöhe der Stimme angibt.", "description": "Parameter docs" }, "speech.sing.param-name.speed": { @@ -4860,7 +4860,7 @@ "description": "(parameter name) A number representing the speed of the voice" }, "speech.sing.param-doc.speed": { - "message": "Eine Zahl, die die Geschwindigkeit der Stimme angibt", + "message": "Eine Zahl, die die Geschwindigkeit der Stimme angibt.", "description": "Parameter docs" }, "speech.sing.param-name.throat": { @@ -4868,7 +4868,7 @@ "description": "(parameter name) A number representing the throat of the voice" }, "speech.sing.param-doc.throat": { - "message": "Eine Zahl, die den Klang der Stimme angibt", + "message": "Eine Zahl, die den Klang der Stimme angibt.", "description": "Parameter docs" }, "struct": { @@ -5044,7 +5044,7 @@ "description": "(function name) Terminate current program with a given exit code." }, "sys.exit.summary": { - "message": "Ein Programm mit dem gegebenen Exit-Code beenden.", + "message": "Beendet ein Programm mit dem gegeneben Exit-Code.", "description": "Terminate current program with a given exit code." }, "sys.exit.param-name.retval": { @@ -5148,7 +5148,7 @@ "description": "(module name) Measure time and add delays to programs." }, "time.summary": { - "message": "Messe Zeit und füge Verzögerung zu Programmen hinzu.", + "message": "Miss Zeit und füge Verzögerung zu Programmen hinzu.", "description": "Measure time and add delays to programs." }, "time.sleep": { diff --git a/crowdin/translated/api.es-es.json b/crowdin/translated/api.es-es.json index afb04f1..212e182 100644 --- a/crowdin/translated/api.es-es.json +++ b/crowdin/translated/api.es-es.json @@ -3460,7 +3460,7 @@ "description": "(function name) Read at most ``nbytes`` while continuously writing the single byte given by ``out``." }, "microbit.spi.read.summary": { - "message": "Lee bytes.", + "message": "Lee como máximo {{nbytes}} mientras está escribiendo continuamente el byte individual dado por {{out}}.", "description": "Read at most ``nbytes`` while continuously writing the single byte given by ``out``." }, "microbit.spi.read.param-name.nbytes": { @@ -3472,11 +3472,11 @@ "description": "Parameter docs" }, "microbit.spi.read.param-name.out": { - "message": "a", + "message": "salida", "description": "(parameter name) The byte value to write (default 0)." }, "microbit.spi.read.param-doc.out": { - "message": "The byte value to write (default 0).", + "message": "El valor del byte a escribir (por defecto 0).", "description": "Parameter docs" }, "microbit.spi.write": { diff --git a/crowdin/translated/api.fr.json b/crowdin/translated/api.fr.json index 14b6a92..cd4d7f1 100644 --- a/crowdin/translated/api.fr.json +++ b/crowdin/translated/api.fr.json @@ -3472,11 +3472,11 @@ "description": "Parameter docs" }, "microbit.spi.read.param-name.out": { - "message": "out", + "message": "Sortie", "description": "(parameter name) The byte value to write (default 0)." }, "microbit.spi.read.param-doc.out": { - "message": "The byte value to write (default 0).", + "message": "La valeur d'octet à écrire (0 par défaut).", "description": "Parameter docs" }, "microbit.spi.write": { diff --git a/crowdin/translated/api.ja.json b/crowdin/translated/api.ja.json index ea86681..eac225d 100644 --- a/crowdin/translated/api.ja.json +++ b/crowdin/translated/api.ja.json @@ -3476,7 +3476,7 @@ "description": "(parameter name) The byte value to write (default 0)." }, "microbit.spi.read.param-doc.out": { - "message": "The byte value to write (default 0).", + "message": "書き込むバイト値(初期値は'0')", "description": "Parameter docs" }, "microbit.spi.write": { diff --git a/crowdin/translated/api.nl.json b/crowdin/translated/api.nl.json index 84a0a03..b335d22 100644 --- a/crowdin/translated/api.nl.json +++ b/crowdin/translated/api.nl.json @@ -3460,7 +3460,7 @@ "description": "(function name) Read at most ``nbytes`` while continuously writing the single byte given by ``out``." }, "microbit.spi.read.summary": { - "message": "Lees bytes.", + "message": "Lees minstens {{nbytes}} terwijl het enkele byte gegeven in {{out}} continu geschreven wordt.", "description": "Read at most ``nbytes`` while continuously writing the single byte given by ``out``." }, "microbit.spi.read.param-name.nbytes": { @@ -3476,7 +3476,7 @@ "description": "(parameter name) The byte value to write (default 0)." }, "microbit.spi.read.param-doc.out": { - "message": "The byte value to write (default 0).", + "message": "De byte-waarde om te schrijven (standaard 0).", "description": "Parameter docs" }, "microbit.spi.write": { diff --git a/crowdin/translated/api.pl.json b/crowdin/translated/api.pl.json index 4738739..c746506 100644 --- a/crowdin/translated/api.pl.json +++ b/crowdin/translated/api.pl.json @@ -4,7 +4,7 @@ "description": "(module name) Control the garbage collector" }, "gc.summary": { - "message": "Steruj zbieraniem sieci", + "message": "Steruj zbieraniem śmieci", "description": "Control the garbage collector" }, "gc.enable": { @@ -3460,7 +3460,7 @@ "description": "(function name) Read at most ``nbytes`` while continuously writing the single byte given by ``out``." }, "microbit.spi.read.summary": { - "message": "Czytaj bajty.", + "message": "Przeczytaj co najwyżej {{nbytes}} podczas ciągłego pisania pojedynczego bajtu danego przez {{out}}.", "description": "Read at most ``nbytes`` while continuously writing the single byte given by ``out``." }, "microbit.spi.read.param-name.nbytes": { @@ -3476,7 +3476,7 @@ "description": "(parameter name) The byte value to write (default 0)." }, "microbit.spi.read.param-doc.out": { - "message": "The byte value to write (default 0).", + "message": "Wartość bajtu do zapisu (domyślnie 0).", "description": "Parameter docs" }, "microbit.spi.write": { diff --git a/lang/ca/typeshed/stdlib/gc.pyi b/lang/ca/typeshed/stdlib/gc.pyi index e12aaf9..1370abf 100644 --- a/lang/ca/typeshed/stdlib/gc.pyi +++ b/lang/ca/typeshed/stdlib/gc.pyi @@ -1,68 +1,73 @@ -"""Controla el recol·lector de memòria brossa""" +"""Control the garbage collector""" + from typing import overload def enable() -> None: - """Habilita la recol·lecció automàtica de la memòria brossa (habilita)""" + """Enable automatic garbage collection.""" ... def disable() -> None: - """Inhabilita la recol·lecció automàtica de la memòria brossa (desactiva) + """Disable automatic garbage collection. -Heap memory can still be allocated, -and garbage collection can still be initiated manually using ``gc.collect``.""" + Heap memory can still be allocated, + and garbage collection can still be initiated manually using ``gc.collect``.""" def collect() -> None: - """Executa la recol·lecció automàtica de la memòria brossa (Recull)""" + """Run a garbage collection.""" ... def mem_alloc() -> int: - """Obté el nombre de bytes assignats a la memòria dinàmica. (espai de memòria) + """Get the number of bytes of heap RAM that are allocated. -:return: The number of bytes allocated. + :return: The number of bytes allocated. -This function is MicroPython extension.""" + This function is MicroPython extension. + """ ... def mem_free() -> int: - """Obté el nombre disponible de bytes de la memòria dinàmica, o -1 si no es coneix la quantitat. (memòria lliure) + """Get the number of bytes of available heap RAM, or -1 if this amount is not known. -:return: The number of bytes free. + :return: The number of bytes free. -This function is MicroPython extension.""" + This function is MicroPython extension. + """ ... @overload def threshold() -> int: - """Consulta l'assignació del llindar del col·lector d'escombraries. (llindar) + """Query the additional GC allocation threshold. -:return: The GC allocation threshold. + :return: The GC allocation threshold. -This function is a MicroPython extension. CPython has a similar -function - ``set_threshold()``, but due to different GC -implementations, its signature and semantics are different.""" + This function is a MicroPython extension. CPython has a similar + function - ``set_threshold()``, but due to different GC + implementations, its signature and semantics are different. + """ ... @overload def threshold(amount: int) -> None: - """Assigna un espai adicional al llindar del col·lector d'escombraries. (llindar) - -Normally, a collection is triggered only when a new allocation -cannot be satisfied, i.e. on an out-of-memory (OOM) condition. -If this function is called, in addition to OOM, a collection -will be triggered each time after ``amount`` bytes have been -allocated (in total, since the previous time such an amount of bytes -have been allocated). ``amount`` is usually specified as less than the -full heap size, with the intention to trigger a collection earlier than when the -heap becomes exhausted, and in the hope that an early collection will prevent -excessive memory fragmentation. This is a heuristic measure, the effect -of which will vary from application to application, as well as -the optimal value of the ``amount`` parameter. - -A value of -1 means a disabled allocation threshold. - -This function is a MicroPython extension. CPython has a similar -function - ``set_threshold()``, but due to different GC -implementations, its signature and semantics are different. - -:param amount: (quantitat) El nombre de bytes després del qual s'activarà la recol·lecció de la memòria brossa.""" - ... \ No newline at end of file + """Set the additional GC allocation threshold. + + Normally, a collection is triggered only when a new allocation + cannot be satisfied, i.e. on an out-of-memory (OOM) condition. + If this function is called, in addition to OOM, a collection + will be triggered each time after ``amount`` bytes have been + allocated (in total, since the previous time such an amount of bytes + have been allocated). ``amount`` is usually specified as less than the + full heap size, with the intention to trigger a collection earlier than when the + heap becomes exhausted, and in the hope that an early collection will prevent + excessive memory fragmentation. This is a heuristic measure, the effect + of which will vary from application to application, as well as + the optimal value of the ``amount`` parameter. + + A value of -1 means a disabled allocation threshold. + + This function is a MicroPython extension. CPython has a similar + function - ``set_threshold()``, but due to different GC + implementations, its signature and semantics are different. + + :param amount: The number of bytes after which a garbage collection should be triggered. + """ + ... diff --git a/lang/ca/typeshed/stdlib/log.pyi b/lang/ca/typeshed/stdlib/log.pyi index 50e425d..c9870fa 100644 --- a/lang/ca/typeshed/stdlib/log.pyi +++ b/lang/ca/typeshed/stdlib/log.pyi @@ -1,89 +1,104 @@ -"""Registre dades en la micro:bit V2 (registre)""" +"""Log data to your micro:bit V2.""" + from typing import Literal, Mapping, Optional, Union, overload + MILLISECONDS = 1 -"""Format de marca de temps de mil·lisegons. (mil·lisegons)""" +"""Milliseconds timestamp format.""" + SECONDS = 10 -"""Format de marca de temps de segons. (segons)""" +"""Seconds timestamp format.""" + MINUTES = 600 -"""Format de marca de temps de minuts. (minuts)""" +"""Minutes timestamp format.""" + HOURS = 36000 -"""Format de marca de temps d'hores. (hores)""" +"""Hours timestamp format.""" + DAYS = 864000 -"""Format de marca de temps de dies. (dies)""" +"""Days timestamp format.""" -def set_labels(*labels: str, timestamp: Optional[Literal[1, 10, 36000, 864000]]=SECONDS) -> None: - """Defineix la capçalera del fitxer de registre. (Defineix l'etiqueta) +def set_labels( + *labels: str, timestamp: Optional[Literal[1, 10, 36000, 864000]] = SECONDS +) -> None: + """Set up the log file header. -Example: ``log.set_labels('X', 'Y', 'Z', timestamp=log.MINUTES)`` + Example: ``log.set_labels('X', 'Y', 'Z', timestamp=log.MINUTES)`` -Ideally this function should be called a single time, before any data is -logged, to configure the data table header once. + Ideally this function should be called a single time, before any data is + logged, to configure the data table header once. -If a log file already exists when the program starts, or if this function -is called multiple times, it will check the labels already defined in the -log file. If this function call contains any new labels not already -present, it will generate a new header row with the additional columns. + If a log file already exists when the program starts, or if this function + is called multiple times, it will check the labels already defined in the + log file. If this function call contains any new labels not already + present, it will generate a new header row with the additional columns. -By default the first column contains a timestamp for each row. The time -unit can be selected via the timestamp argument. + By default the first column contains a timestamp for each row. The time + unit can be selected via the timestamp argument. -:param *labels: Qualsevol nombre d'arguments posicionals, corresponent cadascun a una entrada en la capçalera del registre. -:param timestamp: (marca horària) Selecciona la unitat de la marca del temps que serà automaticament afegida com a primera columna de cada fila. Els valors de la marca del temps pot ser un de ``log.MILLISECONDS``, ``log.SECONDS``, ``log.MINUTES``, ``log.HOURS``, ``log.DAYS`` o ``None`` per desactivar la marca del temps. El valor per defecte es ``log.SECONDS``.""" + :param *labels: Any number of positional arguments, each corresponding to an entry in the log header. + :param timestamp: Select the timestamp unit that will be automatically added as the first column in every row. Timestamp values can be one of ``log.MILLISECONDS``, ``log.SECONDS``, ``log.MINUTES``, ``log.HOURS``, ``log.DAYS`` or ``None`` to disable the timestamp. The default value is ``log.SECONDS``. + """ ... @overload -def add(data_dictionary: Optional[Mapping[str, Union[str, int, float]]]) -> None: - """Afegeix una fila de dades al registre passant un diccionari de capçaleres i valors. (afegeix) +def add( + data_dictionary: Optional[Mapping[str, Union[str, int, float]]], +) -> None: + """Add a data row to the log by passing a dictionary of headers and values. -Example: ``log.add({ 'temp': temperature() })`` + Example: ``log.add({ 'temp': temperature() })`` -Each call to this function adds a row to the log. + Each call to this function adds a row to the log. -New labels not previously specified via the set_labels function, or by a -previous call to this function, will trigger a new header entry to be added -to the log with the extra labels. + New labels not previously specified via the set_labels function, or by a + previous call to this function, will trigger a new header entry to be added + to the log with the extra labels. -Labels previously specified and not present in a call to this function will -be skipped with an empty value in the log row. + Labels previously specified and not present in a call to this function will + be skipped with an empty value in the log row. -:param data_dictionary: (diccionari de dades) Les dades a ser registrades com un diccionari amb una clau per cada capçalera.""" + :param data_dictionary: The data to log as a dictionary with a key for each header. + """ ... @overload def add(**kwargs: Union[str, int, float]) -> None: - """Afegeix una fila de dades al registre fent servir arguments de paraula clau. (afegeix) + """Add a data row to the log using keyword arguments. -Example: ``log.add(temp=temperature())`` + Example: ``log.add(temp=temperature())`` -Each call to this function adds a row to the log. + Each call to this function adds a row to the log. -New labels not previously specified via the set_labels function, or by a -previous call to this function, will trigger a new header entry to be added -to the log with the extra labels. + New labels not previously specified via the set_labels function, or by a + previous call to this function, will trigger a new header entry to be added + to the log with the extra labels. -Labels previously specified and not present in a call to this function will -be skipped with an empty value in the log row.""" + Labels previously specified and not present in a call to this function will + be skipped with an empty value in the log row. + """ ... def delete(full=False): - """Suprimeix el contingut del registre, incloses les capçaleres. (suprimeix) + """Deletes the contents of the log, including headers. -Example: ``log.delete()`` + Example: ``log.delete()`` -To add the log headers again the ``set_labels`` function should to be called after this function. + To add the log headers again the ``set_labels`` function should to be called after this function. -There are two erase modes; “full” completely removes the data from the physical storage, -and “fast” invalidates the data without removing it. + There are two erase modes; “full” completely removes the data from the physical storage, + and “fast” invalidates the data without removing it. -:param full: (ple) ``True`` selecciona un esborrat "total" ``False`` selecciona un mètode d'esborrat "ràpid".""" + :param full: ``True`` selects a “full” erase and ``False`` selects the “fast” erase method. + """ ... def set_mirroring(serial: bool): - """Configura la duplicació de l'activitat de registre de dades a la sortida en sèrie. (estableix mirall) + """Configure mirroring of the data logging activity to the serial output. -Example: ``log.set_mirroring(True)`` + Example: ``log.set_mirroring(True)`` -Serial mirroring is disabled by default. When enabled, it will print to serial each row logged into the log file. + Serial mirroring is disabled by default. When enabled, it will print to serial each row logged into the log file. -:param serial: ``True`` permet la duplicació de les dades a la sortida sèrie.""" - ... \ No newline at end of file + :param serial: ``True`` enables mirroring data to the serial output. + """ + ... diff --git a/lang/ca/typeshed/stdlib/machine.pyi b/lang/ca/typeshed/stdlib/machine.pyi index d40f465..2e82f5b 100644 --- a/lang/ca/typeshed/stdlib/machine.pyi +++ b/lang/ca/typeshed/stdlib/machine.pyi @@ -1,84 +1,97 @@ -"""Utilitats de baix nivell. (màquina)""" +"""Low-level utilities. +""" from typing import Any from .microbit import MicroBitDigitalPin def unique_id() -> bytes: - """Obté una cadena de bytes amb un identificador únic d'una placa. + """Get a byte string with a unique identifier of a board. -Example: ``machine.unique_id()`` + Example: ``machine.unique_id()`` -:return: An identifier that varies from one board instance to another.""" + :return: An identifier that varies from one board instance to another. + """ ... def reset() -> None: - """Reinicia el dispositiu d'una manera semblant a la de prémer el botó extern de REINICI. (reiniciar) + """Reset the device in a manner similar to pushing the external RESET button. -Example: ``machine.reset()``""" + Example: ``machine.reset()`` + """ ... def freq() -> int: - """Obté la freqüència en Hertz de la CPU + """Get the CPU frequency in hertz. -Example: ``machine.freq()`` + Example: ``machine.freq()`` -:return: The CPU frequency.""" + :return: The CPU frequency. + """ ... def disable_irq() -> Any: - """Desactiva les sol·licituds d'interrupció. (desabilita irq) + """Disable interrupt requests. -Example: ``interrupt_state = machine.disable_irq()`` + Example: ``interrupt_state = machine.disable_irq()`` -:return: the previous IRQ state which should be considered an opaque value + :return: the previous IRQ state which should be considered an opaque value -The return value should be passed to the ``enable_irq`` function to restore -interrupts to their original state.""" + The return value should be passed to the ``enable_irq`` function to restore + interrupts to their original state. + """ ... def enable_irq(state: Any) -> None: - """Torna a habilitar les sol·licituds d'interrupció. (habilita irq) + """Re-enable interrupt requests. -Example: ``machine.enable_irq(interrupt_state)`` + Example: ``machine.enable_irq(interrupt_state)`` -:param state: (estat) El valor retornat per la crida més recent a la funció ``disable_irq``.""" + :param state: The value that was returned from the most recent call to the ``disable_irq`` function. + """ ... -def time_pulse_us(pin: MicroBitDigitalPin, pulse_level: int, timeout_us: int=1000000) -> int: - """Cronometra una pulsació en un pin. (mesura la durada d'una pulsació en un pin) +def time_pulse_us( + pin: MicroBitDigitalPin, pulse_level: int, timeout_us: int = 1000000 +) -> int: + """Time a pulse on a pin. -Example: ``time_pulse_us(pin0, 1)`` + Example: ``time_pulse_us(pin0, 1)`` -If the current input value of the pin is different to ``pulse_level``, the -function first waits until the pin input becomes equal to -``pulse_level``, then times the duration that the pin is equal to -``pulse_level``. If the pin is already equal to ``pulse_level`` then timing -starts straight away. + If the current input value of the pin is different to ``pulse_level``, the + function first waits until the pin input becomes equal to + ``pulse_level``, then times the duration that the pin is equal to + ``pulse_level``. If the pin is already equal to ``pulse_level`` then timing + starts straight away. -:param pin: El pin a utilitzar -:param pulse_level: (nivell de pulsació) 0 per cronometrar la durada de l'estat baix o 1 per cronometrar la durada de l'estat alt -:param timeout_us: (temps d'espera a la resposta excedit en microsegons) Temps d'espera d'un microsegon -:return: The duration of the pulse in microseconds, or -1 for a timeout waiting for the level to match ``pulse_level``, or -2 on timeout waiting for the pulse to end""" + :param pin: The pin to use + :param pulse_level: 0 to time a low pulse or 1 to time a high pulse + :param timeout_us: A microsecond timeout + :return: The duration of the pulse in microseconds, or -1 for a timeout waiting for the level to match ``pulse_level``, or -2 on timeout waiting for the pulse to end + """ ... class mem: - """La classe per a les vistes de la memòria ``mem8``, ``mem16`` i ``mem32``.""" + """The class for the ``mem8``, ``mem16`` and ``mem32`` memory views.""" def __getitem__(self, address: int) -> int: - """Accedeix a un valor de la memòria + """Access a value from memory. -:param address: (adreça) L'adreça de la memòria -:return: The value at that address as an integer.""" + :param address: The memory address. + :return: The value at that address as an integer. + """ ... - def __setitem__(self, address: int, value: int) -> None: - """Assigna un valor a l'adreça donada + """Set a value at the given address. -:param address: (adreça) L'adreça de la memòria -:param value: (valor) El valor enter que cal assignar.""" + :param address: The memory address. + :param value: The integer value to set. + """ ... + mem8: mem -"""vista de la memòria 8-bit (byte)""" +"""8-bit (byte) view of memory.""" + mem16: mem -"""vista de la memòria 16-bit""" +"""16-bit view of memory.""" + mem32: mem -"""vista de la memòria 32-bit""" \ No newline at end of file +"""32-bit view of memory.""" diff --git a/lang/ca/typeshed/stdlib/math.pyi b/lang/ca/typeshed/stdlib/math.pyi index 0ec2a6a..f82d4de 100644 --- a/lang/ca/typeshed/stdlib/math.pyi +++ b/lang/ca/typeshed/stdlib/math.pyi @@ -1,246 +1,273 @@ -"""Funcions matemàtiques (matemàtiques)""" +"""Mathematical functions. +""" + from typing import Tuple def acos(x: float) -> float: - """Calcula l'invers del cosinus (arc cosinus) + """Calculate the inverse cosine. -Example: ``math.acos(1)`` + Example: ``math.acos(1)`` -:param x: Un nombre -:return: The inverse cosine of ``x``""" + :param x: A number + :return: The inverse cosine of ``x`` + """ ... def asin(x: float) -> float: - """Calcula l'invers del sinus (arc sinus) + """Calculate the inverse sine. -Example: ``math.asin(0)`` + Example: ``math.asin(0)`` -:param x: Un nombre -:return: The inverse sine of ``x``""" + :param x: A number + :return: The inverse sine of ``x`` + """ ... def atan(x: float) -> float: - """Calcula l'invers de la tangent (arc tangent) + """Calculate the inverse tangent. -Example: ``math.atan(0)`` + Example: ``math.atan(0)`` -:param x: Un nombre -:return: The inverse tangent of ``x``""" + :param x: A number + :return: The inverse tangent of ``x`` + """ ... def atan2(y: float, x: float) -> float: - """Calcula el valor principal de l'invers de la tangent de ``y/x``. (arc tangent 2) + """Calculate the principal value of the inverse tangent of ``y/x``. -Example: ``math.atan2(0, -1)`` + Example: ``math.atan2(0, -1)`` -:param y: Un nombre -:param x: Un nombre -:return: The principal value of the inverse tangent of ``y/x``""" + :param y: A number + :param x: A number + :return: The principal value of the inverse tangent of ``y/x`` + """ ... def ceil(x: float) -> float: - """Arrodoneix un nombre cap a l'infinit positiu. (arrodoniment per excés) + """Round a number towards positive infinity. -Example: ``math.ceil(0.1)`` + Example: ``math.ceil(0.1)`` -:param x: Un nombre -:return: ``x`` rounded towards positive infinity.""" + :param x: A number + :return: ``x`` rounded towards positive infinity. + """ ... def copysign(x: float, y: float) -> float: - """Calcula ``x`` amb el signe de ``y``. + """Calculate ``x`` with the sign of ``y``. -Example: ``math.copysign(1, -1)`` + Example: ``math.copysign(1, -1)`` -:param x: Un nombre -:param y: L'origen del signe pel valor retornat. -:return: ``x`` with the sign of ``y``""" + :param x: A number + :param y: The source of the sign for the return value + :return: ``x`` with the sign of ``y`` + """ ... def cos(x: float) -> float: - """Calcula el cosinus de ``x``. (cosinus) + """Calculate the cosine of ``x``. -Example: ``math.cos(0)`` + Example: ``math.cos(0)`` -:param x: Un nombre -:return: The cosine of ``x``""" + :param x: A number + :return: The cosine of ``x`` + """ ... def degrees(x: float) -> float: - """Convertir radiants a graus (graus) + """Convert radians to degrees. -Example: ``math.degrees(2 * math.pi)`` + Example: ``math.degrees(2 * math.pi)`` -:param x: Un valor en radians -:return: The value converted to degrees""" + :param x: A value in radians + :return: The value converted to degrees""" ... def exp(x: float) -> float: - """Calcula l'exponencial de ``x``. + """Calculate the exponential of ``x``. -Example: ``math.exp(1)`` + Example: ``math.exp(1)`` -:param x: Un nombre -:return: The exponential of ``x``.""" + :param x: A number + :return: The exponential of ``x``. + """ ... def fabs(x: float) -> float: - """Retorna el valor absolut de ``x``. + """Return the absolute value of ``x``. -Example: ``math.fabs(-0.1)`` + Example: ``math.fabs(-0.1)`` -:param x: Un nombre -:return: The absolute value of ``x``""" + :param x: A number + :return: The absolute value of ``x`` + """ ... def floor(x: float) -> int: - """Arrodoneix un nombre cap a l'infinit negatiu. (arrodoniment per defecte) + """Round a number towards negative infinity. -Example: ``math.floor(0.9)`` + Example: ``math.floor(0.9)`` -:param x: Un nombre -:return: ``x`` rounded towards negative infinity.""" + :param x: A number + :return: ``x`` rounded towards negative infinity. + """ ... def fmod(x: float, y: float) -> float: - """Calcula el residu de ``x/y``. + """Calculate the remainder of ``x/y``. -Example: ``math.fmod(10, 3)`` + Example: ``math.fmod(10, 3)`` -:param x: El numerador -:param y: El denominador""" + :param x: The numerator + :param y: The denominator + """ ... def frexp(x: float) -> Tuple[float, int]: - """Descompon un nombre de coma flotant en la seva mantissa i el seu exponent. + """Decomposes a floating-point number into its mantissa and exponent. -Example: ``mantissa, exponent = math.frexp(2)`` + Example: ``mantissa, exponent = math.frexp(2)`` -The returned value is the tuple ``(m, e)`` such that ``x == m * 2**e`` -exactly. If ``x == 0`` then the function returns ``(0.0, 0)``, otherwise -the relation ``0.5 <= abs(m) < 1`` holds. + The returned value is the tuple ``(m, e)`` such that ``x == m * 2**e`` + exactly. If ``x == 0`` then the function returns ``(0.0, 0)``, otherwise + the relation ``0.5 <= abs(m) < 1`` holds. -:param x: Un nombre de coma flotant -:return: A tuple of length two containing its mantissa then exponent""" + :param x: A floating-point number + :return: A tuple of length two containing its mantissa then exponent + """ ... def isfinite(x: float) -> bool: - """Verifica si un valor és finit. + """Check if a value is finite. -Example: ``math.isfinite(float('inf'))`` + Example: ``math.isfinite(float('inf'))`` -:param x: Un nombre. -:return: ``True`` if ``x`` is finite, ``False`` otherwise.""" + :param x: A number. + :return: ``True`` if ``x`` is finite, ``False`` otherwise. + """ ... def isinf(x: float) -> bool: - """Verifica si un valor és infinit. + """Check if a value is infinite. -Example: ``math.isinf(float('-inf'))`` + Example: ``math.isinf(float('-inf'))`` -:param x: Un nombre. -:return: ``True`` if ``x`` is infinite, ``False`` otherwise.""" + :param x: A number. + :return: ``True`` if ``x`` is infinite, ``False`` otherwise. + """ ... def isnan(x: float) -> bool: - """Verifica si un valor és un "no nombre" (NaN) + """Check if a value is not-a-number (NaN). -Example: ``math.isnan(float('nan'))`` + Example: ``math.isnan(float('nan'))`` -:param x: Un nombre -:return: ``True`` if ``x`` is not-a-number (NaN), ``False`` otherwise.""" + :param x: A number + :return: ``True`` if ``x`` is not-a-number (NaN), ``False`` otherwise.""" ... def ldexp(x: float, exp: int) -> float: - """Calcula ``x * (2**exp)``. (ldexp (Calcula ``x * (2**exp)``)) + """Calculate ``x * (2**exp)``. -Example: ``math.ldexp(0.5, 2)`` + Example: ``math.ldexp(0.5, 2)`` -:param x: Un nombre -:param exp: Exponent enter -:return: ``x * (2**exp)``""" + :param x: A number + :param exp: Integer exponent + :return: ``x * (2**exp)`` + """ ... -def log(x: float, base: float=e) -> float: - """Calcula el logaritme ``x`` d'una base donada (per defecte al logaritme natural). (registre) +def log(x: float, base: float = e) -> float: + """Calculate the logarithm of ``x`` to the given base (defaults to natural logorithm). -Example: ``math.log(math.e)`` + Example: ``math.log(math.e)`` -With one argument, return the natural logarithm of x (to base e). + With one argument, return the natural logarithm of x (to base e). -With two arguments, return the logarithm of x to the given base, calculated as ``log(x)/log(base)``. + With two arguments, return the logarithm of x to the given base, calculated as ``log(x)/log(base)``. -:param x: Un nombre -:param base: La base a utilitzar -:return: The natural logarithm of ``x``""" + :param x: A number + :param base: The base to use + :return: The natural logarithm of ``x`` + """ ... def modf(x: float) -> Tuple[float, float]: - """Calcula les parts fraccionàries i integrals de ``x``. + """Calculate the fractional and integral parts of ``x``. -Example: ``fractional, integral = math.modf(1.5)`` + Example: ``fractional, integral = math.modf(1.5)`` -:param x: Un nombre -:return: A tuple of two floats representing the fractional then integral parts of ``x``. + :param x: A number + :return: A tuple of two floats representing the fractional then integral parts of ``x``. -Both the fractional and integral values have the same sign as ``x``.""" + Both the fractional and integral values have the same sign as ``x``. + """ ... def pow(x: float, y: float) -> float: - """Retorna ``x`` a la potència de ``y``. + """Returns ``x`` to the power of ``y``. -Example: ``math.pow(4, 0.5)`` + Example: ``math.pow(4, 0.5)`` -:param x: Un nombre -:param y: L'exponent -:return: ``x`` to the power of ``y``""" + :param x: A number + :param y: The exponent + :return: ``x`` to the power of ``y`` + """ ... def radians(x: float) -> float: - """Converteix graus a radians + """Convert a degrees to radians. -Example: ``math.radians(360)`` + Example: ``math.radians(360)`` -:param x: Un valor en graus -:return: The value converted to radians""" + :param x: A value in degrees + :return: The value converted to radians + """ ... def sin(x: float) -> float: - """Calcula el sinus de ``x``. (sinus) + """Calculate the sine of ``x``. -Example: ``math.sin(math.pi/2)`` + Example: ``math.sin(math.pi/2)`` -:param x: Un nombre -:return: The sine of ``x``""" + :param x: A number + :return: The sine of ``x`` + """ ... def sqrt(x: float) -> float: - """Calcula l'arrel quadrada de ``x``. + """Calculate the square root of ``x``. -Example: ``math.sqrt(4)`` + Example: ``math.sqrt(4)`` -:param x: Un nombre -:return: The square root of ``x``""" + :param x: A number + :return: The square root of ``x`` + """ ... def tan(x: float) -> float: - """Calcula la tangent de ``x``. + """Calculate the tangent of ``x``. -Example: ``math.tan(0)`` + Example: ``math.tan(0)`` -:param x: Un nombre -:return: The tangent of ``x``.""" + :param x: A number + :return: The tangent of ``x``. + """ ... def trunc(x: float) -> int: - """Arrodoneix un nombre cap al 0. (trunca) + """Round a number towards 0. -Example: ``math.trunc(-0.9)`` + Example: ``math.trunc(-0.9)`` -:param x: Un nombre -:return: ``x`` rounded towards zero.""" + :param x: A number + :return: ``x`` rounded towards zero. + """ ... + e: float -"""Base del logaritme natural""" +"""Base of the natural logarithm""" + pi: float -"""La relació entre la circumferència d'un cercle i el seu diàmetre""" \ No newline at end of file +"""The ratio of a circle's circumference to its diameter""" diff --git a/lang/ca/typeshed/stdlib/microbit/__init__.pyi b/lang/ca/typeshed/stdlib/microbit/__init__.pyi index cff2992..f12158f 100644 --- a/lang/ca/typeshed/stdlib/microbit/__init__.pyi +++ b/lang/ca/typeshed/stdlib/microbit/__init__.pyi @@ -1,6 +1,11 @@ -"""Pins, imatges, sons, temperatura i volum.""" +"""Pins, images, sounds, temperature and volume. +""" + from typing import Any, Callable, List, Optional, Tuple, Union, overload + from _typeshed import ReadableBuffer + +# V2 only from . import accelerometer as accelerometer from . import audio as audio from . import compass as compass @@ -11,701 +16,831 @@ from . import speaker as speaker from . import spi as spi from . import uart as uart -def run_every(callback: Optional[Callable[[], None]]=None, days: int=0, h: int=0, min: int=0, s: int=0, ms: int=0) -> Callable[[Callable[[], None]], Callable[[], None]]: - """Programa l'execució d'una funció a cada interval especificat pels arguments de temps **només V2**. +def run_every( + callback: Optional[Callable[[], None]] = None, + days: int = 0, + h: int = 0, + min: int = 0, + s: int = 0, + ms: int = 0, +) -> Callable[[Callable[[], None]], Callable[[], None]]: + """Schedule to run a function at the interval specified by the time arguments **V2 only**. -Example: ``run_every(my_logging, min=5)`` + Example: ``run_every(my_logging, min=5)`` -``run_every`` can be used in two ways: + ``run_every`` can be used in two ways: -As a Decorator - placed on top of the function to schedule. For example:: + As a Decorator - placed on top of the function to schedule. For example:: - @run_every(h=1, min=20, s=30, ms=50) - def my_function(): - # Do something here + @run_every(h=1, min=20, s=30, ms=50) + def my_function(): + # Do something here -As a Function - passing the callback as a positional argument. For example:: + As a Function - passing the callback as a positional argument. For example:: - def my_function(): - # Do something here - run_every(my_function, s=30) + def my_function(): + # Do something here + run_every(my_function, s=30) -Each argument corresponds to a different time unit and they are additive. -So ``run_every(min=1, s=30)`` schedules the callback every minute and a half. + Each argument corresponds to a different time unit and they are additive. + So ``run_every(min=1, s=30)`` schedules the callback every minute and a half. -When an exception is thrown inside the callback function it deschedules the -function. To avoid this you can catch exceptions with ``try/except``. + When an exception is thrown inside the callback function it deschedules the + function. To avoid this you can catch exceptions with ``try/except``. -:param callback: Funció a cridar a l'interval previst. Omet quan el fas servir com decorador. -:param days: (dies) Estableix la marca del dia per la programació -:param h: Estableix la marca de l'hora per la programació -:param min: Estableix la marca del minut per la programació -:param s: Estableix la marca del segon per la programació -:param ms: Estableix la marca del mil·lisegon per la programació""" + :param callback: Function to call at the provided interval. Omit when using as a decorator. + :param days: Sets the day mark for the scheduling. + :param h: Sets the hour mark for the scheduling. + :param min: Sets the minute mark for the scheduling. + :param s: Sets the second mark for the scheduling. + :param ms: Sets the millisecond mark for the scheduling. + """ def panic(n: int) -> None: - """Entrar en mode pànic. (pànic) + """Enter a panic mode. -Example: ``panic(127)`` + Example: ``panic(127)`` -:param n: Un nombre enter arbitrari <= 255 per indicar un estat. + :param n: An arbitrary integer <= 255 to indicate a status. -Requires restart.""" + Requires restart. + """ def reset() -> None: - """Reinicialitza la placa. (reiniciar)""" + """Restart the board.""" + @overload def scale(value: float, from_: Tuple[float, float], to: Tuple[int, int]) -> int: - """Converteix un valor d'un interval a un interval de nombre enter. (escala) + """Converts a value from a range to an integer range. -Example: ``volume = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255))`` + Example: ``volume = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255))`` -For example, to convert an accelerometer X value to a speaker volume. + For example, to convert an accelerometer X value to a speaker volume. -If one of the numbers in the ``to`` parameter is a floating point -(i.e a decimal number like ``10.0``), this function will return a -floating point number. + If one of the numbers in the ``to`` parameter is a floating point + (i.e a decimal number like ``10.0``), this function will return a + floating point number. - temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0)) + temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0)) -:param value: (valor) Un nombre a convertir. -:param from_: (des de) Una tupla des d'on definir l'interval a convertir -:param to: (a) Una tupla que defineix l'interval d'arribada -:return: The ``value`` converted to the ``to`` range.""" + :param value: A number to convert. + :param from_: A tuple to define the range to convert from. + :param to: A tuple to define the range to convert to. + :return: The ``value`` converted to the ``to`` range. + """ @overload def scale(value: float, from_: Tuple[float, float], to: Tuple[float, float]) -> float: - """Converteix un valor d'un interval a un altre interval de coma flotant. (escala) + """Converts a value from a range to a floating point range. -Example: ``temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0))`` + Example: ``temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0))`` -For example, to convert temperature from a Celsius scale to Fahrenheit. + For example, to convert temperature from a Celsius scale to Fahrenheit. -If one of the numbers in the ``to`` parameter is a floating point -(i.e a decimal number like ``10.0``), this function will return a -floating point number. -If they are both integers (i.e ``10``), it will return an integer:: + If one of the numbers in the ``to`` parameter is a floating point + (i.e a decimal number like ``10.0``), this function will return a + floating point number. + If they are both integers (i.e ``10``), it will return an integer:: - returns_int = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255)) + returns_int = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255)) -:param value: (valor) Un nombre a convertir. -:param from_: (des de) Una tupla des d'on definir l'interval a convertir -:param to: (a) Una tupla que defineix l'interval d'arribada de la conversió. -:return: The ``value`` converted to the ``to`` range.""" + :param value: A number to convert. + :param from_: A tuple to define the range to convert from. + :param to: A tuple to define the range to convert to. + :return: The ``value`` converted to the ``to`` range. + """ def sleep(n: float) -> None: - """Espera per ``n`` mil·lisegons. (dormir) + """Wait for ``n`` milliseconds. -Example: ``sleep(1000)`` + Example: ``sleep(1000)`` -:param n: El nombre de mil·lisegons a esperar + :param n: The number of milliseconds to wait -One second is 1000 milliseconds, so:: + One second is 1000 milliseconds, so:: - microbit.sleep(1000) + microbit.sleep(1000) -will pause the execution for one second.""" + will pause the execution for one second. + """ def running_time() -> int: - """Obté el temps d'execució de la placa. (temps d'execució) + """Get the running time of the board. -:return: The number of milliseconds since the board was switched on or restarted.""" + :return: The number of milliseconds since the board was switched on or restarted. + """ def temperature() -> int: - """Obté la temperatura de la micro:bit en graus Celsius. (temperatura)""" + """Get the temperature of the micro:bit in degrees Celsius.""" def set_volume(v: int) -> None: - """Configura el volum (assigna volum) + """Sets the volume. -Example: ``set_volume(127)`` + Example: ``set_volume(127)`` -:param v: un valor entre 0 (baix) i 255 (alt). + :param v: a value between 0 (low) and 255 (high). -Out of range values will be clamped to 0 or 255. + Out of range values will be clamped to 0 or 255. -**V2** only.""" + **V2** only. + """ ... class Button: - """La classe dels botons ``button_a`` i ``button_b``. (botó)""" + """The class for the buttons ``button_a`` and ``button_b``.""" def is_pressed(self) -> bool: - """Verifica si el botó està premut. (és premut) + """Check if the button is pressed. -:return: ``True`` if the specified button ``button`` is pressed, and ``False`` otherwise.""" + :return: ``True`` if the specified button ``button`` is pressed, and ``False`` otherwise. + """ ... - def was_pressed(self) -> bool: - """Verifica si el botó ha estat premut d'ençà que el dispositiu va arrancar o l'última vegada que aquest mètode va ser cridat. (ha estat premut) + """Check if the button was pressed since the device started or the last time this method was called. -Calling this method will clear the press state so -that the button must be pressed again before this method will return -``True`` again. + Calling this method will clear the press state so + that the button must be pressed again before this method will return + ``True`` again. -:return: ``True`` if the specified button ``button`` was pressed, and ``False`` otherwise""" + :return: ``True`` if the specified button ``button`` was pressed, and ``False`` otherwise + """ ... - def get_presses(self) -> int: - """Obté el total acumulat de pressions dels botons i restableix aquest total -a zero abans de tornar. (obté pitjades) + """Get the running total of button presses, and resets this total + to zero before returning. -:return: The number of presses since the device started or the last time this method was called""" + :return: The number of presses since the device started or the last time this method was called + """ ... + button_a: Button -"""L'objecte botó esquerre ``Button`` . (botó a)""" +"""The left button ``Button`` object.""" + button_b: Button -"""L'objecte el botó dret ``Button``. (botó b)""" +"""The right button ``Button`` object.""" class MicroBitDigitalPin: - """Un pin digital. + """A digital pin. + + Some pins support analog and touch features using the ``MicroBitAnalogDigitalPin`` and ``MicroBitTouchPin`` subclasses. + """ -Some pins support analog and touch features using the ``MicroBitAnalogDigitalPin`` and ``MicroBitTouchPin`` subclasses.""" NO_PULL: int PULL_UP: int PULL_DOWN: int - def read_digital(self) -> int: - """Obté el valor digital del pin. (llegeix digital) + """Get the digital value of the pin. -Example: ``value = pin0.read_digital()`` + Example: ``value = pin0.read_digital()`` -:return: 1 if the pin is high, and 0 if it's low.""" + :return: 1 if the pin is high, and 0 if it's low. + """ ... - def write_digital(self, value: int) -> None: - """Assigna el valor digital del pin. (escriu digital) + """Set the digital value of the pin. -Example: ``pin0.write_digital(1)`` + Example: ``pin0.write_digital(1)`` -:param value: (valor) 1 per posar el pin alt o 0 per posar el pin baix""" + :param value: 1 to set the pin high or 0 to set the pin low""" ... - def set_pull(self, value: int) -> None: - """Configura les resistències de pull-up/pull-down un dels tres valors possibles: ``PULL_UP``, ``PULL_DOWN`` o ``NO_PULL``. (configuració de les resistències de pull up/down) + """Set the pull state to one of three possible values: ``PULL_UP``, ``PULL_DOWN`` or ``NO_PULL``. -Example: ``pin0.set_pull(pin0.PULL_UP)`` + Example: ``pin0.set_pull(pin0.PULL_UP)`` -:param value: (valor) L'estat del pull-up/pull-down del pin corresponent, per ex. ``pin0.PULL_UP``.""" + :param value: The pull state from the relevant pin, e.g. ``pin0.PULL_UP``. + """ ... - def get_pull(self) -> int: - """Obté l'estat de pull-up/pull-down d'un pin. + """Get the pull state on a pin. -Example: ``pin0.get_pull()`` + Example: ``pin0.get_pull()`` -:return: ``NO_PULL``, ``PULL_DOWN``, or ``PULL_UP`` + :return: ``NO_PULL``, ``PULL_DOWN``, or ``PULL_UP`` -These are set using the ``set_pull()`` method or automatically configured -when a pin mode requires it.""" + These are set using the ``set_pull()`` method or automatically configured + when a pin mode requires it. + """ ... - def get_mode(self) -> str: - """Retorna el mode del pin (obté el mode) + """Returns the pin mode. -Example: ``pin0.get_mode()`` + Example: ``pin0.get_mode()`` -When a pin is used for a specific function, like -writing a digital value, or reading an analog value, the pin mode -changes. + When a pin is used for a specific function, like + writing a digital value, or reading an analog value, the pin mode + changes. -:return: ``"unused"``, ``"analog"``, ``"read_digital"``, ``"write_digital"``, ``"display"``, ``"button"``, ``"music"``, ``"audio"``, ``"touch"``, ``"i2c"``, or ``"spi"``""" + :return: ``"unused"``, ``"analog"``, ``"read_digital"``, ``"write_digital"``, ``"display"``, ``"button"``, ``"music"``, ``"audio"``, ``"touch"``, ``"i2c"``, or ``"spi"`` + """ ... - def write_analog(self, value: int) -> None: - """Genera un senyal PWM al pin, amb el cicle de treball proporcional a ``value``. (escriu analògic) - -Example: ``pin0.write_analog(254)`` + """Output a PWM signal on the pin, with the duty cycle proportional to ``value``. -:param value: (valor) Un nombre enter o de coma flotant entre 0 (cicle de treball del 0%) i 1023 (cicle de treball del 100%).""" + Example: ``pin0.write_analog(254)`` + :param value: An integer or a floating point number between 0 (0% duty cycle) and 1023 (100% duty). + """ def set_analog_period(self, period: int) -> None: - """Estableix el període del senyal PWM a ``period`` en mil·lisegons. (configura el període amb un valor analògic) + """Set the period of the PWM signal being output to ``period`` in milliseconds. -Example: ``pin0.set_analog_period(10)`` - -:param period: (període) El període en mil·lisegons amb un valor mínim vàlid d'1\u202fms""" + Example: ``pin0.set_analog_period(10)`` + :param period: The period in milliseconds with a minimum valid value of 1ms. + """ def set_analog_period_microseconds(self, period: int) -> None: - """Estableix el període del senyal PWM a ``period`` microsegons. (configura el període amb un valor analògic en microsegons) + """Set the period of the PWM signal being output to ``period`` in microseconds. -Example: ``pin0.set_analog_period_microseconds(512)`` + Example: ``pin0.set_analog_period_microseconds(512)`` -:param period: (període) El període en microsegons amb un valor vàlid mínim de 256\u202fµs.""" + :param period: The period in microseconds with a minimum valid value of 256µs. + """ class MicroBitAnalogDigitalPin(MicroBitDigitalPin): - """Un pin amb funcions analògiques i digitals.""" + """A pin with analog and digital features.""" def read_analog(self) -> int: - """Llegeix el voltatge aplicat al pin. (llegeix analògic) + """Read the voltage applied to the pin. -Example: ``pin0.read_analog()`` + Example: ``pin0.read_analog()`` -:return: An integer between 0 (meaning 0V) and 1023 (meaning 3.3V).""" + :return: An integer between 0 (meaning 0V) and 1023 (meaning 3.3V). + """ class MicroBitTouchPin(MicroBitAnalogDigitalPin): - """Un pin amb característiques analògiques, digitals i tàctils.""" + """A pin with analog, digital and touch features.""" + CAPACITIVE: int RESISTIVE: int - def is_touched(self) -> bool: - """Comprova si el pin està sent tocat. (està tocat) + """Check if the pin is being touched. -Example: ``pin0.is_touched()`` + Example: ``pin0.is_touched()`` -The default touch mode for the pins on the edge connector is ``resistive``. -The default for the logo pin **V2** is ``capacitive``. + The default touch mode for the pins on the edge connector is ``resistive``. + The default for the logo pin **V2** is ``capacitive``. -**Resistive touch** -This test is done by measuring how much resistance there is between the -pin and ground. A low resistance gives a reading of ``True``. To get -a reliable reading using a finger you may need to touch the ground pin -with another part of your body, for example your other hand. + **Resistive touch** + This test is done by measuring how much resistance there is between the + pin and ground. A low resistance gives a reading of ``True``. To get + a reliable reading using a finger you may need to touch the ground pin + with another part of your body, for example your other hand. -**Capacitive touch** -This test is done by interacting with the electric field of a capacitor -using a finger as a conductor. `Capacitive touch -`_ -does not require you to make a ground connection as part of a circuit. + **Capacitive touch** + This test is done by interacting with the electric field of a capacitor + using a finger as a conductor. `Capacitive touch + `_ + does not require you to make a ground connection as part of a circuit. -:return: ``True`` if the pin is being touched with a finger, otherwise return ``False``.""" + :return: ``True`` if the pin is being touched with a finger, otherwise return ``False``. + """ ... - def set_touch_mode(self, value: int) -> None: - """Estableix el mode tàctil per al pin. (estableix el mode tàctil) + """Set the touch mode for the pin. -Example: ``pin0.set_touch_mode(pin0.CAPACITIVE)`` + Example: ``pin0.set_touch_mode(pin0.CAPACITIVE)`` -The default touch mode for the pins on the edge connector is -``resistive``. The default for the logo pin **V2** is ``capacitive``. + The default touch mode for the pins on the edge connector is + ``resistive``. The default for the logo pin **V2** is ``capacitive``. -:param value: (valor) ``CAPACITIVE`` o ``RESISTIVE`` del pin corresponent.""" + :param value: ``CAPACITIVE`` or ``RESISTIVE`` from the relevant pin. + """ ... + pin0: MicroBitTouchPin -"""Pin amb característiques digitals, analògiques i tàctils.""" +"""Pin with digital, analog and touch features.""" + pin1: MicroBitTouchPin -"""Pin amb característiques digitals, analògiques i tàctils.""" +"""Pin with digital, analog and touch features.""" + pin2: MicroBitTouchPin -"""Pin amb característiques digitals, analògiques i tàctils.""" +"""Pin with digital, analog and touch features.""" + pin3: MicroBitAnalogDigitalPin -"""Pin amb característiques digitals i analògiques.""" +"""Pin with digital and analog features.""" + pin4: MicroBitAnalogDigitalPin -"""Pin amb característiques digitals i analògiques.""" +"""Pin with digital and analog features.""" + pin5: MicroBitDigitalPin -"""Pin amb característiques digitals.""" +"""Pin with digital features.""" + pin6: MicroBitDigitalPin -"""Pin amb característiques digitals.""" +"""Pin with digital features.""" + pin7: MicroBitDigitalPin -"""Pin amb característiques digitals.""" +"""Pin with digital features.""" + pin8: MicroBitDigitalPin -"""Pin amb característiques digitals.""" +"""Pin with digital features.""" + pin9: MicroBitDigitalPin -"""Pin amb característiques digitals.""" +"""Pin with digital features.""" + pin10: MicroBitAnalogDigitalPin -"""Pin amb característiques digitals i analògiques.""" +"""Pin with digital and analog features.""" + pin11: MicroBitDigitalPin -"""Pin amb característiques digitals.""" +"""Pin with digital features.""" + pin12: MicroBitDigitalPin -"""Pin amb característiques digitals.""" +"""Pin with digital features.""" + pin13: MicroBitDigitalPin -"""Pin amb característiques digitals.""" +"""Pin with digital features.""" + pin14: MicroBitDigitalPin -"""Pin amb característiques digitals.""" +"""Pin with digital features.""" + pin15: MicroBitDigitalPin -"""Pin amb característiques digitals.""" +"""Pin with digital features.""" + pin16: MicroBitDigitalPin -"""Pin amb característiques digitals.""" +"""Pin with digital features.""" + pin19: MicroBitDigitalPin -"""Pin amb característiques digitals.""" +"""Pin with digital features.""" + pin20: MicroBitDigitalPin -"""Pin amb característiques digitals.""" +"""Pin with digital features.""" + pin_logo: MicroBitTouchPin -"""Un logotip tàctil a la part frontal de la micro:bit, que per defecte està establert al mode tàctil capacitiu. (pin logotip)""" +"""A touch sensitive logo pin on the front of the micro:bit, which by default is set to capacitive touch mode.""" + pin_speaker: MicroBitAnalogDigitalPin -"""Un pin per adreçar-se a l'altaveu micro:bit. (pin altaveu) +"""A pin to address the micro:bit speaker. This API is intended only for use in Pulse-Width Modulation pin operations e.g. pin_speaker.write_analog(128). """ class Image: - """Una imatge per mostrar a la pantalla LED de micro:bit. (imatge) + """An image to show on the micro:bit LED display. -Given an image object it's possible to display it via the ``display`` API:: + Given an image object it's possible to display it via the ``display`` API:: + + display.show(Image.HAPPY) + """ - display.show(Image.HAPPY)""" HEART: Image - """Imatge d'un cor. (cor)""" + """Heart image.""" + HEART_SMALL: Image - """Imatge d'un cor petit (cor petit)""" + """Small heart image.""" + HAPPY: Image - """Imatge d'una cara feliç (feliç)""" + """Happy face image.""" + SMILE: Image - """Imatge d'una cara somrient (somriure)""" + """Smiling mouth image.""" + SAD: Image - """Imatge d'una cara trista (tristesa)""" + """Sad face image.""" + CONFUSED: Image - """Imatge de cara confusa. (confusa)""" + """Confused face image.""" + ANGRY: Image - """Imatge d'una cara enfadada. (enfadat)""" + """Angry face image.""" + ASLEEP: Image - """Imatge d'una cara dormint. (despert)""" + """Sleeping face image.""" + SURPRISED: Image - """Imatge d'una cara de sorpresa (sorprès)""" + """Surprised face image.""" + SILLY: Image - """Imatge d'una cara ximple. (ximple)""" + """Silly face image.""" + FABULOUS: Image - """Imatge d'una cara amb ulleres de sol. (fabulós)""" + """Sunglasses face image.""" + MEH: Image - """Imatge d'una cara inexpressiva. (BAH avorrit)""" + """Unimpressed face image.""" + YES: Image - """Imatge d'una marca tic. (sí)""" + """Tick image.""" + NO: Image - """Imatge d'una creu.""" + """Cross image.""" + CLOCK12: Image - """Imatge d'una línia apuntant les dotze. (les dotze)""" + """Image with line pointing to 12 o'clock.""" + CLOCK11: Image - """Imatge d'una línia apuntant les onze. (les onze)""" + """Image with line pointing to 11 o'clock.""" + CLOCK10: Image - """Imatge d'una línia apuntant les deu. (les deu)""" + """Image with line pointing to 10 o'clock.""" + CLOCK9: Image - """Imatge d'una línia apuntant les nou. (les nou)""" + """Image with line pointing to 9 o'clock.""" + CLOCK8: Image - """Imatge d'una línia apuntant les vuit. (les vuit)""" + """Image with line pointing to 8 o'clock.""" + CLOCK7: Image - """Imatge d'una línia apuntant les set. (les set)""" + """Image with line pointing to 7 o'clock.""" + CLOCK6: Image - """Imatge amb una línia apuntant a les 6 en punt. (les sis)""" + """Image with line pointing to 6 o'clock.""" + CLOCK5: Image - """Imatge amb una línia apuntant a les 5 en punt. (les cinc)""" + """Image with line pointing to 5 o'clock.""" + CLOCK4: Image - """Imatge amb una línia apuntant a les 4 en punt. (les quatre)""" + """Image with line pointing to 4 o'clock.""" + CLOCK3: Image - """Imatge amb una línia apuntant a les 3 en punt. (les tres)""" + """Image with line pointing to 3 o'clock.""" + CLOCK2: Image - """Imatge amb una línia apuntant a les 2 en punt. (les dues)""" + """Image with line pointing to 2 o'clock.""" + CLOCK1: Image - """Imatge amb una línia apuntant a la 1 en punt. (la una)""" + """Image with line pointing to 1 o'clock.""" + ARROW_N: Image - """Imatge de fletxa apuntant al nord. (fletxa n)""" + """Image of arrow pointing north.""" + ARROW_NE: Image - """Imatge de fletxa apuntant al nord-est. (fletxa ne)""" + """Image of arrow pointing north east.""" + ARROW_E: Image - """Imatge de fletxa apuntant a l'est. (fletxa e)""" + """Image of arrow pointing east.""" + ARROW_SE: Image - """Imatge de fletxa apuntant al sud-est. (fletxa se)""" + """Image of arrow pointing south east.""" + ARROW_S: Image - """Imatge de fletxa apuntant al sud. (fletxa s)""" + """Image of arrow pointing south.""" + ARROW_SW: Image - """Imatge de fletxa apuntant al sud-oest. (fletxa so)""" + """Image of arrow pointing south west.""" + ARROW_W: Image - """Imatge de fletxa apuntant a l'oest. (fletxa o)""" + """Image of arrow pointing west.""" + ARROW_NW: Image - """Imatge de fletxa apuntant al nord-oest. (fletxa no)""" + """Image of arrow pointing north west.""" + TRIANGLE: Image - """Imatge d'un triangle apuntant amunt.""" + """Image of a triangle pointing up.""" + TRIANGLE_LEFT: Image - """Imatge d'un triangle en la cantonada esquerra. (triangle a l'esquerra)""" + """Image of a triangle in the left corner.""" + CHESSBOARD: Image - """Leds alternatius il·luminats en un patró d'escacs. (Tauler d'escacs)""" + """Alternate LEDs lit in a chessboard pattern.""" + DIAMOND: Image - """Imatge d'un diamant (diamant)""" + """Diamond image.""" + DIAMOND_SMALL: Image - """Imatge d'un diamant petit (diamant petit)""" + """Small diamond image.""" + SQUARE: Image - """Imatge d'un quadrat (quadrat)""" + """Square image.""" + SQUARE_SMALL: Image - """Imatge d'un quadrat petit (quadrat petit)""" + """Small square image.""" + RABBIT: Image - """Imatge d'un conill. (conill)""" + """Rabbit image.""" + COW: Image - """Imatge d'una vaca. (vaca)""" + """Cow image.""" + MUSIC_CROTCHET: Image - """Imatge de la nota musical negra (nota musical negra)""" + """Crotchet note image.""" + MUSIC_QUAVER: Image - """Imatge de la nota musical corxera (nota musical corxera)""" + """Quaver note image.""" + MUSIC_QUAVERS: Image - """Imatge d'un parell de notes musicals corxeres (nota musical corxera)""" + """Pair of quavers note image.""" + PITCHFORK: Image - """Imatge d'una forca. (forca)""" + """Pitchfork image.""" + XMAS: Image - """Imatge d'un arbre de Nadal (nadal)""" + """Christmas tree image.""" + PACMAN: Image - """Imatge del personatge de Pac-man a arcade""" + """Pac-Man arcade character image.""" + TARGET: Image - """Imatge d'objectiu. (diana)""" + """Target image.""" + TSHIRT: Image - """Imatge de samarreta. (Imatge d'una samarreta T-shirt)""" + """T-shirt image.""" + ROLLERSKATE: Image - """Imatge d'un patinet. (patinet)""" + """Rollerskate image.""" + DUCK: Image - """Imatge d'un ànec. (ànec)""" + """Duck image.""" + HOUSE: Image - """Imatge d'una casa. (casa)""" + """House image.""" + TORTOISE: Image - """Imatge d'una tortuga. (tortuga)""" + """Tortoise image.""" + BUTTERFLY: Image - """Imatge d'una papallona. (papallona)""" + """Butterfly image.""" + STICKFIGURE: Image - """Imatge de figura d'un pal. (imatge d'un pal)""" + """Stick figure image.""" + GHOST: Image - """Imatge d'un fantasma. (fantasma)""" + """Ghost image.""" + SWORD: Image - """Imatge d'una espasa (espasa)""" + """Sword image.""" + GIRAFFE: Image - """Imatge d'una girafa. (girafa)""" + """Giraffe image.""" + SKULL: Image - """Imatge d'un crani. (crani)""" + """Skull image.""" + UMBRELLA: Image - """Imatge d'un paraigua, (paraigua)""" + """Umbrella image.""" + SNAKE: Image - """Imatge d'una serp. (serp)""" + """Snake image.""" + SCISSORS: Image - """Imatge d'unes tisores. (tisores)""" + """Scissors image.""" + ALL_CLOCKS: List[Image] - """Una llista que conté totes les imatges CLOCK_ en seqüència. (tots els rellotges)""" - ALL_ARROWS: List[Image] - """Una llista que conté totes les ARROW_images en seqüència. (totes les fletxes)""" + """A list containing all the CLOCK_ images in sequence.""" + ALL_ARROWS: List[Image] + """A list containing all the ARROW_ images in sequence.""" @overload def __init__(self, string: str) -> None: - """Crea una imatge a partir d'una cadena que descrigui quins leds estan encesos. + """Create an image from a string describing which LEDs are lit. -``string`` has to consist of digits 0-9 arranged into lines, -describing the image, for example:: + ``string`` has to consist of digits 0-9 arranged into lines, + describing the image, for example:: - image = Image("90009:" - "09090:" - "00900:" - "09090:" - "90009") + 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 newlines (\\n) insead of the colons. + 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 newlines (\\n) insead of the colons. -:param string: (cadena) La cadena descrivint la imatge.""" + :param string: The string describing the image. + """ ... - @overload - def __init__(self, width: int=5, height: int=5, buffer: ReadableBuffer=None) -> None: - """Crea una imatge buida amb ``width`` columnes i ``height`` files. + def __init__( + self, width: int = 5, height: int = 5, buffer: ReadableBuffer = None + ) -> None: + """Create an empty image with ``width`` columns and ``height`` rows. -:param width: (amplada) Amplada opcional de la imatge -:param height: (alçària) Alçària opcional de la imatge -:param buffer: (memòria intermèdia) Llistes o bytes opcionals d'enters de ``width``×``height`` dins l'interval de 0 a 9 per inicialitzar la imatge + :param width: Optional width of the image + :param height: Optional height of the image + :param buffer: Optional array or bytes of ``width``×``height`` integers in range 0-9 to initialize the image -Examples:: + Examples:: - Image(2, 2, b'\x08\x08\x08\x08') - Image(2, 2, bytearray([9,9,9,9])) + Image(2, 2, b'\x08\x08\x08\x08') + Image(2, 2, bytearray([9,9,9,9])) -These create 2 x 2 pixel images at full brightness.""" + These create 2 x 2 pixel images at full brightness. + """ ... - def width(self) -> int: - """Obté el nombre de columnes (amplada) + """Get the number of columns. -:return: The number of columns in the image""" + :return: The number of columns in the image + """ ... - def height(self) -> int: - """Obté el nombre de files. (alçària) + """Get the number of rows. -:return: The number of rows in the image""" + :return: The number of rows in the image + """ ... - def set_pixel(self, x: int, y: int, value: int) -> None: - """Estableix la brillantor d'un píxel. (estableix píxel) + """Set the brightness of a pixel. -Example: ``my_image.set_pixel(0, 0, 9)`` + Example: ``my_image.set_pixel(0, 0, 9)`` -:param x: El nombre de la columna -:param y: El nombre de la fila -:param value: (valor) La brillantor com a nombre enter entre 0 (fosc) i 9 (brillant) + :param x: The column number + :param y: The row number + :param value: The brightness as an integer 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``.""" + 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: - """Obté la brillantor d'un píxel. (obté píxel) + """Get the brightness of a pixel. -Example: ``my_image.get_pixel(0, 0)`` + Example: ``my_image.get_pixel(0, 0)`` -:param x: El nombre de la columna -:param y: El nombre de la fila -:return: The brightness as an integer between 0 and 9.""" + :param x: The column number + :param y: The row number + :return: The brightness as an integer between 0 and 9. + """ ... - def shift_left(self, n: int) -> Image: - """Crea una imatge nova movent-la cap a l'esquerra. (desplaça a l'esquerra) + """Create a new image by shifting the picture left. -Example: ``Image.HEART_SMALL.shift_left(1)`` + Example: ``Image.HEART_SMALL.shift_left(1)`` -:param n: El nombre de columnes per desplaçar-se -:return: The shifted image""" + :param n: The number of columns to shift by + :return: The shifted image + """ ... - def shift_right(self, n: int) -> Image: - """Crea una imatge nova movent-la cap a la dreta. (desplaça a la dreta) + """Create a new image by shifting the picture right. -Example: ``Image.HEART_SMALL.shift_right(1)`` + Example: ``Image.HEART_SMALL.shift_right(1)`` -:param n: El nombre de columnes per desplaçar-se -:return: The shifted image""" + :param n: The number of columns to shift by + :return: The shifted image + """ ... - def shift_up(self, n: int) -> Image: - """Crea una imatge nova desplaçant la imatge cap amunt. (desplaça cap amunt) + """Create a new image by shifting the picture up. -Example: ``Image.HEART_SMALL.shift_up(1)`` + Example: ``Image.HEART_SMALL.shift_up(1)`` -:param n: El nombre de files per desplaçar-se -:return: The shifted image""" + :param n: The number of rows to shift by + :return: The shifted image + """ ... - def shift_down(self, n: int) -> Image: - """Crea una imatge nova desplaçant-la cap avall. (desplaça cap avall) + """Create a new image by shifting the picture down. -Example: ``Image.HEART_SMALL.shift_down(1)`` + Example: ``Image.HEART_SMALL.shift_down(1)`` -:param n: El nombre de files per desplaçar-se -:return: The shifted image""" + :param n: The number of rows to shift by + :return: The shifted image + """ ... - def crop(self, x: int, y: int, w: int, h: int) -> Image: - """Crea una imatge nova retallant la imatge. (retalla) + """Create a new image by cropping the picture. -Example: ``Image.HEART.crop(1, 1, 3, 3)`` + Example: ``Image.HEART.crop(1, 1, 3, 3)`` -:param x: La columna de desplaçament del retall -:param y: La fila de desplaçament del retall -:param w: L'amplada del retall -:param h: L'alçària del retall -:return: The new image""" + :param x: The crop offset column + :param y: The crop offset row + :param w: The crop width + :param h: The crop height + :return: The new image + """ ... - def copy(self) -> Image: - """Crea una còpia exacta de la imatge (còpia) + """Create an exact copy of the image. -Example: ``Image.HEART.copy()`` + Example: ``Image.HEART.copy()`` -:return: The new image""" + :return: The new image + """ ... - def invert(self) -> Image: - """Crea una imatge nova invertint la brillantor dels píxels de la imatge -font. (inverteix) + """Create a new image by inverting the brightness of the pixels in the + source image. -Example: ``Image.SMALL_HEART.invert()`` + Example: ``Image.SMALL_HEART.invert()`` -:return: The new image.""" + :return: The new image. + """ ... - def fill(self, value: int) -> None: - """Assigna la brillantor de tots els píxels de la imatge (omple) + """Set the brightness of all the pixels in the image. -Example: ``my_image.fill(5)`` + Example: ``my_image.fill(5)`` -:param value: (valor) La nova brillantor com a nombre entre 0 (fosc) i 9 (brillant). + :param value: The new brightness as a number 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``.""" + 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: - """Copia una àrea d'una altra imatge a aquesta imatge. - -Example: ``my_image.blit(Image.HEART, 1, 1, 3, 3, 1, 1)`` - -:param src: (font) La imatge font -:param x: Desplaçament de la columna inicial a la imatge d'origen -:param y: Desplaçament de la fila inicial a la imatge d'origen -:param w: El nombre de columnes a copiar -:param h: El nombre de files a copiar -:param xdest: El desplaçament de columna a modificar en aquesta imatge -:param ydest: El desplaçament de fila que cal modificar en aquesta imatge - -Pixels outside the source image are treated as having a brightness 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 blit( + self, + src: Image, + x: int, + y: int, + w: int, + h: int, + xdest: int = 0, + ydest: int = 0, + ) -> None: + """Copy an area from another image into this image. + + Example: ``my_image.blit(Image.HEART, 1, 1, 3, 3, 1, 1)`` + + :param src: The source image + :param x: The starting column offset in the source image + :param y: The starting row offset in the source image + :param w: The number of columns to copy + :param h: The number of rows to copy + :param xdest: The column offset to modify in this image + :param ydest: The row offset to modify in this image + + Pixels outside the source image are treated as having a brightness 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: - """Obté una representació de cadena compacta de la imatge. (repr - Obté una representació de cadena compacta de la imatge.)""" + """Get a compact string representation of the image.""" ... - def __str__(self) -> str: - """Obté una representació de cadena llegible de la imatge.""" + """Get a readable string representation of the image.""" ... - def __add__(self, other: Image) -> Image: - """Crea una imatge nova afegint els valors de brillantor de les dues -imatges per a cada píxel. (afegeix) + """Create a new image by adding the brightness values from the two + images for each pixel. -Example: ``Image.HEART + Image.HAPPY`` + Example: ``Image.HEART + Image.HAPPY`` -:param other: (altre) La imatge a afegir.""" + :param other: The image to add. + """ ... - def __sub__(self, other: Image) -> Image: - """Crea una imatge nova restant els valors de brillantor d'una altra imatge d'aquesta imatge. + """Create a new image by subtracting the brightness values of the + other image from this image. -Example: ``Image.HEART - Image.HEART_SMALL`` + Example: ``Image.HEART - Image.HEART_SMALL`` -:param other: (altre) La imatge a restar.""" + :param other: The image to subtract. + """ ... - def __mul__(self, n: float) -> Image: - """Crea una imatge nova multiplicant la brillantor de cada píxel per -``n``. + """Create a new image by multiplying the brightness of each pixel by + ``n``. -Example: ``Image.HEART * 0.5`` + Example: ``Image.HEART * 0.5`` -:param n: El valor per multiplicar.""" + :param n: The value to multiply by. + """ ... - def __truediv__(self, n: float) -> Image: - """Crea una imatge nova dividint la brillantor de cada píxel per -``n``. + """Create a new image by dividing the brightness of each pixel by + ``n``. -Example: ``Image.HEART / 2`` + Example: ``Image.HEART / 2`` -:param n: El valor del divisor.""" + :param n: The value to divide by. + """ ... class SoundEvent: LOUD: SoundEvent - """Representa la transició dels esdeveniments de so, des de ``quiet`` a ``loud`` com picant de mans o cridant. (so fort)""" + """Represents the transition of sound events, from ``quiet`` to ``loud`` like clapping or shouting.""" + QUIET: SoundEvent - """Representa la transició dels esdeveniments de so, des de ``loud`` a ``quiet`` com parlant o música de fons. (so fluix)""" + """Represents the transition of sound events, from ``loud`` to ``quiet`` like speaking or background music.""" class Sound: - """Els sons integrats es poden reproduir mitjançant ``audio.play(Sound.NAME)``. (so)""" + """The built-in sounds can be called using ``audio.play(Sound.NAME)``.""" + GIGGLE: Sound - """So de riure (riure)""" + """Giggling sound.""" + HAPPY: Sound - """So feliç. (feliç)""" + """Happy sound.""" + HELLO: Sound - """So de salutació. (hola)""" + """Greeting sound.""" + MYSTERIOUS: Sound - """So misteriós. (misteriós)""" + """Mysterious sound.""" + SAD: Sound - """So trist. (tristesa)""" + """Sad sound.""" + SLIDE: Sound - """So lliscant (so lliscant)""" + """Sliding sound.""" + SOARING: Sound - """So creixent. (creixent)""" + """Soaring sound.""" + SPRING: Sound - """So primaveral. (primaveral)""" + """Spring sound.""" + TWINKLE: Sound - """So de centelleig. (centelleig)""" + """Twinkling sound.""" + YAWN: Sound - """So de badall. (badall)""" \ No newline at end of file + """Yawning sound.""" diff --git a/lang/ca/typeshed/stdlib/microbit/accelerometer.pyi b/lang/ca/typeshed/stdlib/microbit/accelerometer.pyi index c52b9d7..bac82c0 100644 --- a/lang/ca/typeshed/stdlib/microbit/accelerometer.pyi +++ b/lang/ca/typeshed/stdlib/microbit/accelerometer.pyi @@ -1,103 +1,115 @@ -"""Mesura l'acceleració de la micro:bit i reconeix els gestos. (acceleròmetre)""" +"""Measure the acceleration of the micro:bit and recognise gestures. +""" + from typing import Tuple def get_x() -> int: - """Obté la mesura de l'acceleració a l'eix ``x`` en mili-g. (obté x) + """Get the acceleration measurement in the ``x`` axis in milli-g. -Example: ``accelerometer.get_x()`` + Example: ``accelerometer.get_x()`` -:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" + :return: A positive or negative integer depending on direction in the range +/- 2000mg. + """ ... def get_y() -> int: - """Obté la mesura de l'acceleració a l'eix ``y`` en mili-g. (obté y) + """Get the acceleration measurement in the ``y`` axis in milli-g. -Example: ``accelerometer.get_y()`` + Example: ``accelerometer.get_y()`` -:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" + :return: A positive or negative integer depending on direction in the range +/- 2000mg. + """ ... def get_z() -> int: - """Obté la mesura de l'acceleració a l'eix ``z`` en mili-g. (obté z) + """Get the acceleration measurement in the ``z`` axis in milli-g. -Example: ``accelerometer.get_z()`` + Example: ``accelerometer.get_z()`` -:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" + :return: A positive or negative integer depending on direction in the range +/- 2000mg. + """ ... def get_values() -> Tuple[int, int, int]: - """Obté les mesures d'acceleració en tots els eixos alhora com una tupla. (obté valors) + """Get the acceleration measurements in all axes at once as a tuple. -Example: ``x, y, z = accelerometer.get_values()`` + Example: ``x, y, z = accelerometer.get_values()`` -:return: a three-element tuple of integers ordered as X, Y, Z, each value a positive or negative integer depending on direction in the range +/- 2000mg""" + :return: a three-element tuple of integers ordered as X, Y, Z, each value a positive or negative integer depending on direction in the range +/- 2000mg + """ ... def get_strength() -> int: - """Obté la mesura de l'acceleració de tots els eixos combinats, com un nombre enter positiu. Aquest serà la suma Pitagòrica dels eixos X, Y i Z. (obté la força) + """Get the acceleration measurement of all axes combined, as a positive integer. This is the Pythagorean sum of the X, Y and Z axes. -Example: ``accelerometer.get_strength()`` + Example: ``accelerometer.get_strength()`` -:return: The combined acceleration strength of all the axes, in milli-g.""" + :return: The combined acceleration strength of all the axes, in milli-g. + """ ... def current_gesture() -> str: - """Obté el nom del gest actual. (El gest actual) + """Get the name of the current gesture. -Example: ``accelerometer.current_gesture()`` + Example: ``accelerometer.current_gesture()`` -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. + 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. -:return: The current gesture""" + :return: The current gesture + """ ... def is_gesture(name: str) -> bool: - """Comprova si el gest nomenat està actiu actualment. + """Check if the named gesture is currently active. -Example: ``accelerometer.is_gesture('shake')`` + Example: ``accelerometer.is_gesture('shake')`` -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. + 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. -:param name: (nom) El nom del gest -:return: ``True`` if the gesture is active, ``False`` otherwise.""" + :param name: The gesture name. + :return: ``True`` if the gesture is active, ``False`` otherwise. + """ ... def was_gesture(name: str) -> bool: - """Comprova si el gest nomenat ha estat actiu des de l'última crida. + """Check if the named gesture was active since the last call. -Example: ``accelerometer.was_gesture('shake')`` + Example: ``accelerometer.was_gesture('shake')`` -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. + 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. -:param name: (nom) El nom del gest -:return: ``True`` if the gesture was active since the last call, ``False`` otherwise.""" + :param name: The gesture name. + :return: ``True`` if the gesture was active since the last call, ``False`` otherwise. + """ def get_gestures() -> Tuple[str, ...]: - """Retorna una tupla de l'historial de gestos. (obté gestos) + """Return a tuple of the gesture history. -Example: ``accelerometer.get_gestures()`` + Example: ``accelerometer.get_gestures()`` -Clears the gesture history before returning. + Clears the gesture history before returning. -Gestures are not updated in the background so there needs to be constant -calls to some accelerometer method to do the gesture detection. Usually -gestures can be detected using a loop with a small :func:`microbit.sleep` delay. + Gestures are not updated in the background so there needs to be constant + calls to some accelerometer method to do the gesture detection. Usually + gestures can be detected using a loop with a small :func:`microbit.sleep` delay. -:return: The history as a tuple, most recent last.""" + :return: The history as a tuple, most recent last. + """ ... def set_range(value: int) -> None: - """Estableix l'interval de la sensibilitat de l'acceleròmetre, en g (gravetat estàndard), al valor més proper acceptat pel maquinari, arrodonit a ``2``, ``4``, o ``8`` + """Set the accelerometer sensitivity range, in g (standard gravity), to the closest values supported by the hardware, so it rounds to either ``2``, ``4``, or ``8`` g. -Example: ``accelerometer.set_range(8)`` + Example: ``accelerometer.set_range(8)`` -:param value: (valor) Nou interval per a l'acceleròmetre, un nombre enter a ``g``.""" \ No newline at end of file + :param value: New range for the accelerometer, an integer in ``g``. + """ diff --git a/lang/ca/typeshed/stdlib/microbit/audio.pyi b/lang/ca/typeshed/stdlib/microbit/audio.pyi index 8c8c6bd..3b1e327 100644 --- a/lang/ca/typeshed/stdlib/microbit/audio.pyi +++ b/lang/ca/typeshed/stdlib/microbit/audio.pyi @@ -1,124 +1,160 @@ -"""Reprodueix sons amb la micro:bit (importa ``audio`` per a la compatibilitat amb V1). (àudio)""" +"""Play sounds using the micro:bit (import ``audio`` for V1 compatibility). +""" + from ..microbit import MicroBitDigitalPin, Sound, pin0 from typing import ClassVar, Iterable, Union -def play(source: Union[Iterable[AudioFrame], Sound, SoundEffect], wait: bool=True, pin: MicroBitDigitalPin=pin0, return_pin: Union[MicroBitDigitalPin, None]=None) -> None: - """Reprodueix un so incorporat, un efecte de só o marcs d'àudio personalitzats. +def play( + source: Union[Iterable[AudioFrame], Sound, SoundEffect], + wait: bool = True, + pin: MicroBitDigitalPin = pin0, + return_pin: Union[MicroBitDigitalPin, None] = None, +) -> None: + """Play a built-in sound, sound effect or custom audio frames. -Example: ``audio.play(Sound.GIGGLE)`` + Example: ``audio.play(Sound.GIGGLE)`` -:param source: (origen) Un objecte de ``Sound`` incorporat com ``Sound.GIGGLE``, un ``SoundEffect`` o una data de mostra com un iterable de ``AudioFrame`` . -:param wait: (espera) Si ``wait`` és ``True``, aquesta funció es bloquejarà fins que s'acabi el so. -:param pin: Es pot utilitzar un argument opcional per especificar el pin de sortida per anul·lar el valor predeterminat de ``pin0``. Si no vols que es reprodueixi cap so, pots utilitzar ``pin=None``. -:param return_pin: (retorna el pin) Especifica un pin diferent del connector d'expansió per connectar-lo a un altaveu extern en lloc de posar a terra. Això s'ignora per a la revisió **V2**.""" + :param source: A built-in ``Sound`` such as ``Sound.GIGGLE``, a ``SoundEffect`` or sample data as an iterable of ``AudioFrame`` objects. + :param wait: If ``wait`` is ``True``, this function will block until the sound is complete. + :param pin: An optional argument to specify the output pin can be used to override the default of ``pin0``. If we do not want any sound to play we can use ``pin=None``. + :param return_pin: Specifies a differential edge connector pin to connect to an external speaker instead of ground. This is ignored for the **V2** revision. + """ def is_playing() -> bool: - """Verifica si s'està reproduint un so. (està reproduint) + """Check whether a sound is playing. -Example: ``audio.is_playing()`` + Example: ``audio.is_playing()`` -:return: ``True`` if audio is playing, otherwise ``False``.""" + :return: ``True`` if audio is playing, otherwise ``False``.""" ... def stop() -> None: - """Atura tota la reproducció d'àudio. (atura) + """Stop all audio playback. -Example: ``audio.stop()``""" + Example: ``audio.stop()`` + """ ... class SoundEffect: - """Un efecte sonor, compost per un conjunt de paràmetres configurats via el constructor o atributs.""" + """A sound effect, composed by a set of parameters configured via the constructor or attributes.""" + WAVEFORM_SINE: ClassVar[int] - """Opció d'ona sinusoidal pel paràmetre ``waveform``. (forma d'ona sinusoidal)""" + """Sine wave option used for the ``waveform`` parameter.""" + WAVEFORM_SAWTOOTH: ClassVar[int] - """Opció d'ona de dent de serra pel paràmetre ``waveform``. (forma d'ona de dent de serra)""" + """Sawtooth wave option used for the ``waveform`` parameter.""" + WAVEFORM_TRIANGLE: ClassVar[int] - """Opció d'ona triangular pel paràmetre ``waveform``. (forma d'ona triangular)""" + """Triangle wave option used for the ``waveform`` parameter.""" + WAVEFORM_SQUARE: ClassVar[int] - """Opció d'ona quadrada pel paràmetre ``waveform``. (forma d'ona quadrada)""" + """Square wave option used for the ``waveform`` parameter.""" + WAVEFORM_NOISE: ClassVar[int] - """Opció d'ona de soroll pel paràmetre ``waveform``. (forma d'ona de soroll)""" + """Noise option used for the ``waveform`` parameter.""" + SHAPE_LINEAR: ClassVar[int] - """Opció d'ona lineal pel paràmetre ``shape``. (forma lineal)""" + """Linear interpolation option used for the ``shape`` parameter.""" + SHAPE_CURVE: ClassVar[int] - """Opció d'interpolació de corba usada pel paràmetre ``shape``. (forma de corba)""" + """Curve interpolation option used for the ``shape`` parameter.""" + SHAPE_LOG: ClassVar[int] - """Opció d'interpolació logarítmica utilitzada pel paràmetre ``shape``. (forma logarítmica)""" + """Logarithmic interpolation option used for the ``shape`` parameter.""" + FX_NONE: ClassVar[int] - """Opció de cap efecte utilitzat pel paràmetre ``fx``. (fx cap)""" + """No effect option used for the ``fx`` parameter.""" + FX_TREMOLO: ClassVar[int] - """Opció d'efecte trèmolo utilitzat pel paràmetre ``fx``. (fx trémolo)""" + """Tremolo effect option used for the ``fx`` parameter.""" + FX_VIBRATO: ClassVar[int] - """Opció d'efecte vibrato utilitzat pel paràmetre ``fx``.""" + """Vibrato effect option used for the ``fx`` parameter.""" + FX_WARBLE: ClassVar[int] - """Opció d'efecte gorjeu utilitzat pel paràmetre ``fx``. (Efecte gorjeu)""" + """Warble effect option used for the ``fx`` parameter.""" + freq_start: int - """Freqüència inicial en Hertz (Hz), un nombre entre ``0`` i ``9999`` (freqüència inicial)""" + """Start frequency in Hertz (Hz), a number between ``0`` and ``9999``""" + freq_end: int - """Freqüència final en Hertz (Hz), un nombre entre ``0`` i ``9999`` (frequència final)""" + """End frequency in Hertz (Hz), a number between ``0`` and ``9999``""" + duration: int - """Durada del so en mil·lisegons, un nombre entre ``0`` and ``9999`` (Durada - duració)""" - vol_start: int - """Volum inicial, un nombre entre ``0`` and ``255`` (volum inicial)""" - vol_end: int - """Valor del volum final, un nombre entre ``0`` and ``255`` (volum final)""" - waveform: int - """Tipus de forma d'ona, un d'aquest valors: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise) (forma d'ona)""" - fx: int - """Efecte a afegir al so, un dels següents valors: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE`` (efecte)""" - shape: int - """El tipus de corba d'interpolació entre les freqüències inicial i final, diferents formes d'ona tenen diferents ràtios de canvi en la freqüència. Un dels següents valors: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG`` (forma)""" + """Duration of the sound in milliseconds, a number between ``0`` and ``9999``""" - def __init__(self, freq_start: int=500, freq_end: int=2500, duration: int=500, vol_start: int=255, vol_end: int=0, waveform: int=WAVEFORM_SQUARE, fx: int=FX_NONE, shape: int=SHAPE_LOG): - """Crea un efecte de so nou. (inicial) + vol_start: int + """Start volume value, a number between ``0`` and ``255``""" -Example: ``my_effect = SoundEffect(duration=1000)`` + vol_end: int + """End volume value, a number between ``0`` and ``255``""" -All the parameters are optional, with default values as shown above, and -they can all be modified via attributes of the same name. For example, we -can first create an effect ``my_effect = SoundEffect(duration=1000)``, -and then change its attributes ``my_effect.duration = 500``. + waveform: int + """Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise)""" -:param freq_start: (freqüència inicial) Freqüència inicial en Hertz (Hz), un nombre entre ``0`` i ``9999``. -:param freq_end: (frequència final) Freqüència final en Hertz (Hz), un nombre entre ``0`` i ``9999``. -:param duration: (Durada - duració) Duració del so en mil·lisegons, un nombre entre ``0`` i ``9999``. -:param vol_start: (volum inicial) Valor del volum inicial, un nombre entre ``0`` i ``255``. -:param vol_end: (volum final) Valor del volum final, un nombre entre ``0`` i ``255``. -:param waveform: (forma d'ona) Tipus de forma d'ona, un d'aquests valors: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (soroll generat aleatòriament). -:param fx: (efecte) Efecte a afegir al so, un del següents valors: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``. -:param shape: (forma) El tipus de corba d'interpolació entre les freqüències inicial i final, diferents formes d'ona tenen diferents ràtios de canvi en la freqüència. Un dels següents valors: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``""" + fx: int + """Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``""" + shape: int + """The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``""" + + def __init__( + self, + freq_start: int = 500, + freq_end: int = 2500, + duration: int = 500, + vol_start: int = 255, + vol_end: int = 0, + waveform: int = WAVEFORM_SQUARE, + fx: int = FX_NONE, + shape: int = SHAPE_LOG, + ): + """Create a new sound effect. + + Example: ``my_effect = SoundEffect(duration=1000)`` + + All the parameters are optional, with default values as shown above, and + they can all be modified via attributes of the same name. For example, we + can first create an effect ``my_effect = SoundEffect(duration=1000)``, + and then change its attributes ``my_effect.duration = 500``. + + :param freq_start: Start frequency in Hertz (Hz), a number between ``0`` and ``9999``. + :param freq_end: End frequency in Hertz (Hz), a number between ``0`` and ``9999``. + :param duration: Duration of the sound in milliseconds, a number between ``0`` and ``9999``. + :param vol_start: Start volume value, a number between ``0`` and ``255``. + :param vol_end: End volume value, a number between ``0`` and ``255``. + :param waveform: Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise). + :param fx: Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``. + :param shape: The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``. + """ def copy(self) -> SoundEffect: - """Crea una còpia d'aquest ``SoundEffect``. (còpia) + """Create a copy of this ``SoundEffect``. -Example: ``sound_2 = sound_1.copy()`` + Example: ``sound_2 = sound_1.copy()`` -:return: A copy of the SoundEffect.""" + :return: A copy of the SoundEffect. + """ class AudioFrame: - """Un objecte ``AudioFrame`` és una llista de 32 mostres cadascuna de les quals és un byte sense signar -(nombre enter entre 0 i 255). + """An ``AudioFrame`` object is a list of 32 samples each of which is a unsigned byte + (whole number between 0 and 255). -It takes just over 4 ms to play a single frame. + It takes just over 4 ms to play a single frame. -Example:: + Example:: - frame = AudioFrame() - for i in range(len(frame)): - frame[i] = 252 - i * 8""" + frame = AudioFrame() + for i in range(len(frame)): + frame[i] = 252 - i * 8 + """ def copyfrom(self, other: AudioFrame) -> None: - """Sobreposa les dades d'aquest ``AudioFrame`` amb les dades d'una altra instància ``AudioFrame`` . (copia desde) - -Example: ``my_frame.copyfrom(source_frame)`` - -:param other: (altre) ``AudioFrame`` instància de la qual copiar les dades.""" - - def __len__(self) -> int: - ... + """Overwrite the data in this ``AudioFrame`` with the data from another ``AudioFrame`` instance. - def __setitem__(self, key: int, value: int) -> None: - ... + Example: ``my_frame.copyfrom(source_frame)`` - def __getitem__(self, key: int) -> int: - ... \ No newline at end of file + :param other: ``AudioFrame`` instance from which to copy the data. + """ + def __len__(self) -> int: ... + def __setitem__(self, key: int, value: int) -> None: ... + def __getitem__(self, key: int) -> int: ... diff --git a/lang/ca/typeshed/stdlib/microbit/compass.pyi b/lang/ca/typeshed/stdlib/microbit/compass.pyi index 9d7bc37..c74a47b 100644 --- a/lang/ca/typeshed/stdlib/microbit/compass.pyi +++ b/lang/ca/typeshed/stdlib/microbit/compass.pyi @@ -1,70 +1,78 @@ -"""Utilitza la brúixola integrada. (brúixola)""" +"""Use the built-in compass. +""" def calibrate() -> None: - """Comença el procés de calibració (calibrar) + """Starts the calibration process. -Example: ``compass.calibrate()`` + Example: ``compass.calibrate()`` -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.""" + 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: - """Verifica si la brúixola està calibrada. (s'ha calibrat) + """Check is the compass is calibrated. -Example: ``compass.is_calibrated()`` + Example: ``compass.is_calibrated()`` -:return: ``True`` if the compass has been successfully calibrated, ``False`` otherwise.""" + :return: ``True`` if the compass has been successfully calibrated, ``False`` otherwise. + """ ... def clear_calibration() -> None: - """Desfà el calibratge, fent que la brúixola torni a estar sense calibració. (esborra la calibració) + """Undoes the calibration, making the compass uncalibrated again. -Example: ``compass.clear_calibration()``""" + Example: ``compass.clear_calibration()`` + """ ... def get_x() -> int: - """Obté la intensitat del camp magnètic de l'eix ``x`` . (obté x) + """Get the magnetic field strength on the ``x`` axis. -Example: ``compass.get_x()`` + Example: ``compass.get_x()`` -Call ``calibrate`` first or the results will be inaccurate. + Call ``calibrate`` first or the results will be inaccurate. -:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" + :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. + """ ... def get_y() -> int: - """Obté la intensitat del camp magnètic de l'eix ``y`` . (obté y) + """Get the magnetic field strength on the ``y`` axis. -Example: ``compass.get_y()`` + Example: ``compass.get_y()`` -Call ``calibrate`` first or the results will be inaccurate. + Call ``calibrate`` first or the results will be inaccurate. -:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" + :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. + """ ... def get_z() -> int: - """Obté la intensitat del camp magnètic a l'eix ``z``. (obté z) + """Get the magnetic field strength on the ``z`` axis. -Example: ``compass.get_z()`` + Example: ``compass.get_z()`` -Call ``calibrate`` first or the results will be inaccurate. + Call ``calibrate`` first or the results will be inaccurate. -:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" + :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. + """ ... def heading() -> int: - """Obté l'orientació de la brúixola. + """Get the compass heading. -Example: ``compass.heading()`` + Example: ``compass.heading()`` -:return: An integer in the range from 0 to 360, representing the angle in degrees, clockwise, with north as 0.""" + :return: An integer in the range from 0 to 360, representing the angle in degrees, clockwise, with north as 0. + """ ... def get_field_strength() -> int: - """Obté la magnitud del camp magnètic al voltant del dispositiu. (obté la intensitat del camp) + """Get the magnitude of the magnetic field around the device. -Example: ``compass.get_field_strength()`` + Example: ``compass.get_field_strength()`` -:return: An integer indication of the magnitude of the magnetic field in nano tesla.""" - ... \ No newline at end of file + :return: An integer indication of the magnitude of the magnetic field in nano tesla.""" + ... diff --git a/lang/ca/typeshed/stdlib/microbit/display.pyi b/lang/ca/typeshed/stdlib/microbit/display.pyi index e302f86..aa4013e 100644 --- a/lang/ca/typeshed/stdlib/microbit/display.pyi +++ b/lang/ca/typeshed/stdlib/microbit/display.pyi @@ -1,92 +1,115 @@ -"""Mostra text, imatges i animacions a la pantalla LED 5×5. (pantalla)""" +"""Show text, images and animations on the 5×5 LED display. +""" + from ..microbit import Image from typing import Union, overload, Iterable def get_pixel(x: int, y: int) -> int: - """Obté la brillantor del LED a la columna ``x`` i la fila ``y``. (obté píxel) + """Get the brightness of the LED at column ``x`` and row ``y``. -Example: ``display.get_pixel(0, 0)`` + Example: ``display.get_pixel(0, 0)`` -:param x: La columna de la pantalla (0...4) -:param y: La fila de la pantalla (0...4) -:return: A number between 0 (off) and 9 (bright)""" + :param x: The display column (0..4) + :param y: The display row (0..4) + :return: A number between 0 (off) and 9 (bright) + """ ... def set_pixel(x: int, y: int, value: int) -> None: - """Estableix la brillantor del LED a la columna ``x`` i la fila ``y``. (estableix píxel) + """Set the brightness of the LED at column ``x`` and row ``y``. -Example: ``display.set_pixel(0, 0, 9)`` + Example: ``display.set_pixel(0, 0, 9)`` -:param x: La columna de la pantalla (0...4) -:param y: La fila de la pantalla (0...4) -:param value: (valor) La brillantor entre 0 (apagat) i 9 (brillant)""" + :param x: The display column (0..4) + :param y: The display row (0..4) + :param value: The brightness between 0 (off) and 9 (bright) + """ ... def clear() -> None: - """Estableix la brillantor de tots els leds a 0 (apagat). + """Set the brightness of all LEDs to 0 (off). -Example: ``display.clear()``""" + Example: ``display.clear()`` + """ ... -def show(image: Union[str, float, int, Image, Iterable[Image]], delay: int=400, wait: bool=True, loop: bool=False, clear: bool=False) -> None: - """Mostra imatges, lletres o dígits en la pantalla LED. (mostra) +def show( + image: Union[str, float, int, Image, Iterable[Image]], + delay: int = 400, + wait: bool = True, + loop: bool = False, + clear: bool = False, +) -> None: + """Shows images, letters or digits on the LED display. -Example: ``display.show(Image.HEART)`` + Example: ``display.show(Image.HEART)`` -When ``image`` is an image or a list of images then each image is displayed in turn. -If ``image`` is a string or number, each letter or digit is displayed in turn. + When ``image`` is an image or a list of images then each image is displayed in turn. + If ``image`` is a string or number, each letter or digit is displayed in turn. -:param image: (imatge) Una cadena, un nombre, una imatge o una llista d'imatges per mostrar. -:param delay: (retard) Cada lletra, dígit o imatge es mostra amb un ``delay`` mil·lisegons entre ells. -:param wait: (espera) Si ``wait`` és ``True``, aquesta funció es bloquejarà fins que s'acabi l'animació, en cas contrari, l'animació passarà en segon pla. -:param loop: (bucle) Si el ``loop`` és ``True``, l'animació es repetirà per sempre. -:param clear: Si ``clear`` és ``True``, la pantalla s'esborrarà un cop finalitzada la seqüència. + :param image: A string, number, image or list of images to show. + :param delay: Each letter, digit or image is shown with ``delay`` milliseconds between them. + :param wait: If ``wait`` is ``True``, this function will block until the animation is finished, otherwise the animation will happen in the background. + :param loop: If ``loop`` is ``True``, the animation will repeat forever. + :param clear: If ``clear`` is ``True``, the display will be cleared after the sequence has finished. -The ``wait``, ``loop`` and ``clear`` arguments must be specified using their keyword.""" + The ``wait``, ``loop`` and ``clear`` arguments must be specified using their keyword. + """ ... -def scroll(text: Union[str, float, int], delay: int=150, wait: bool=True, loop: bool=False, monospace: bool=False) -> None: - """Desplaça un número o text per la pantalla LED. - -Example: ``display.scroll('micro:bit')`` - -:param text: La cadena per a desplaçar. Si ``text`` és un nombre enter o flotant, primer es converteix en una cadena mitjançant ``str()``. -:param delay: (retard) El paràmetre ``delay`` controla la rapidesa amb què es desplaça el text. -:param wait: (espera) Si ``wait`` és ``True``, aquesta funció es bloquejarà fins que s'acabi l'animació, en cas contrari, l'animació passarà en segon pla. -:param loop: (bucle) Si el ``loop`` és ``True``, l'animació es repetirà per sempre. -:param monospace: Si ``monospace`` és ``True``, tots els caràcters ocuparan 5 columnes de píxels d'amplada, en cas contrari, hi haurà exactament 1 columna de píxels en blanc entre cada caràcter mentre es desplacen. - -The ``wait``, ``loop`` and ``monospace`` arguments must be specified -using their keyword.""" +def scroll( + text: Union[str, float, int], + delay: int = 150, + wait: bool = True, + loop: bool = False, + monospace: bool = False, +) -> None: + """Scrolls a number or text on the LED display. + + Example: ``display.scroll('micro:bit')`` + + :param text: The string to scroll. If ``text`` is an integer or float it is first converted to a string using ``str()``. + :param delay: The ``delay`` parameter controls how fast the text is scrolling. + :param wait: If ``wait`` is ``True``, this function will block until the animation is finished, otherwise the animation will happen in the background. + :param loop: If ``loop`` is ``True``, the animation will repeat forever. + :param monospace: 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. + + The ``wait``, ``loop`` and ``monospace`` arguments must be specified + using their keyword. + """ ... def on() -> None: - """Encén la pantalla LED. + """Turn on the LED display. -Example: ``display.on()``""" + Example: ``display.on()`` + """ ... def off() -> None: - """Apaga la pantalla LED (desactivar la pantalla et permet reutilitzar els pins GPIO per a altres finalitats). + """Turn off the LED display (disabling the display allows you to re-use the GPIO pins for other purposes). -Example: ``display.off()``""" + Example: ``display.off()`` + """ ... def is_on() -> bool: - """Comprova si la pantalla LED està habilitada. + """Check whether the LED display is enabled. -Example: ``display.is_on()`` + Example: ``display.is_on()`` -:return: ``True`` if the display is on, otherwise returns ``False``.""" + :return: ``True`` if the display is on, otherwise returns ``False``. + """ ... def read_light_level() -> int: - """Llegeix el nivell de llum. (llegir el nivell de llum) + """Read the light level. -Example: ``display.read_light_level()`` + Example: ``display.read_light_level()`` -Uses the display's LEDs in reverse-bias mode to sense the amount of light -falling on the display. + Uses the display's LEDs in reverse-bias mode to sense the amount of light + falling on the display. -:return: An integer between 0 and 255 representing the light level, with larger meaning more light.""" - ... \ No newline at end of file + :return: An integer between 0 and 255 representing the light level, with larger meaning more light. + """ + ... diff --git a/lang/ca/typeshed/stdlib/microbit/i2c.pyi b/lang/ca/typeshed/stdlib/microbit/i2c.pyi index 6f4ca40..df26efa 100644 --- a/lang/ca/typeshed/stdlib/microbit/i2c.pyi +++ b/lang/ca/typeshed/stdlib/microbit/i2c.pyi @@ -1,49 +1,57 @@ -"""Comunicar-se amb dispositius mitjançant el protocol de bus I²C.""" +"""Communicate with devices using the I²C bus protocol. +""" + from _typeshed import ReadableBuffer from ..microbit import MicroBitDigitalPin, pin19, pin20 from typing import List -def init(freq: int=100000, sda: MicroBitDigitalPin=pin20, scl: MicroBitDigitalPin=pin19) -> None: - """Reinicialitzar un perifèric. +def init( + freq: int = 100000, sda: MicroBitDigitalPin = pin20, scl: MicroBitDigitalPin = pin19 +) -> None: + """Re-initialize a peripheral. -Example: ``i2c.init()`` + Example: ``i2c.init()`` -:param freq: freqüència del rellotge -:param sda: Pin ``sda`` (per defecte 20) -:param scl: pin ``scl`` (per defecte 19) + :param freq: clock frequency + :param sda: ``sda`` pin (default 20) + :param scl: ``scl`` pin (default 19) -On a micro:bit V1 board, changing the I²C pins from defaults will make -the accelerometer and compass stop working, as they are connected -internally to those pins. This warning does not apply to the **V2** -revision of the micro:bit as this has `separate I²C lines `_ -for the motion sensors and the edge connector.""" + On a micro:bit V1 board, changing the I²C pins from defaults will make + the accelerometer and compass stop working, as they are connected + internally to those pins. This warning does not apply to the **V2** + revision of the micro:bit as this has `separate I²C lines `_ + for the motion sensors and the edge connector. + """ ... def scan() -> List[int]: - """Escaneja el bus dels dispositius + """Scan the bus for devices. -Example: ``i2c.scan()`` + Example: ``i2c.scan()`` -:return: A list of 7-bit addresses corresponding to those devices that responded to the scan.""" + :return: A list of 7-bit addresses corresponding to those devices that responded to the scan. + """ ... -def read(addr: int, n: int, repeat: bool=False) -> bytes: - """Llegeix bytes des d'un dispositiu. (llegeix) +def read(addr: int, n: int, repeat: bool = False) -> bytes: + """Read bytes from a device. -Example: ``i2c.read(0x50, 64)`` + Example: ``i2c.read(0x50, 64)`` -:param addr: L'adreça de 7-bit del dispositiu -:param n: El nombre de bytes a llegir -:param repeat: (repeteix) Si ``True``, no s'enviarà cap bit d'aturada -:return: The bytes read""" + :param addr: The 7-bit address of the device + :param n: The number of bytes to read + :param repeat: If ``True``, no stop bit will be sent + :return: The bytes read + """ ... -def write(addr: int, buf: ReadableBuffer, repeat: bool=False) -> None: - """Escriu bytes en un dispositiu (escriu) +def write(addr: int, buf: ReadableBuffer, repeat: bool = False) -> None: + """Write bytes to a device. -Example: ``i2c.write(0x50, bytes([1, 2, 3]))`` + Example: ``i2c.write(0x50, bytes([1, 2, 3]))`` -:param addr: L'adreça de 7-bit del dispositiu -:param buf: Una memòria intermèdia que conté els bytes per escriure -:param repeat: (repeteix) Si ``True``, no s'enviarà cap bit d'aturada""" - ... \ No newline at end of file + :param addr: The 7-bit address of the device + :param buf: A buffer containing the bytes to write + :param repeat: If ``True``, no stop bit will be sent + """ + ... diff --git a/lang/ca/typeshed/stdlib/microbit/microphone.pyi b/lang/ca/typeshed/stdlib/microbit/microphone.pyi index b36703c..68e8f3a 100644 --- a/lang/ca/typeshed/stdlib/microbit/microphone.pyi +++ b/lang/ca/typeshed/stdlib/microbit/microphone.pyi @@ -1,62 +1,70 @@ -"""Respon al so fent servir el micròfon integrat (només V2). (micròfon)""" +"""Respond to sound using the built-in microphone (V2 only). +""" + from typing import Optional, Tuple from ..microbit import SoundEvent def current_event() -> Optional[SoundEvent]: - """Obté l'últim esdeveniment de sonor gravat (esdeveniment actual) + """Get the last recorded sound event -Example: ``microphone.current_event()`` + Example: ``microphone.current_event()`` -:return: The event, ``SoundEvent('loud')`` or ``SoundEvent('quiet')``.""" + :return: The event, ``SoundEvent('loud')`` or ``SoundEvent('quiet')``. + """ ... def was_event(event: SoundEvent) -> bool: - """Comprova si s'ha sentit un so almenys una vegada des de l'última crida. (va ser un esdeveniment) + """Check if a sound was heard at least once since the last call. -Example: ``microphone.was_event(SoundEvent.LOUD)`` + Example: ``microphone.was_event(SoundEvent.LOUD)`` -This call clears the sound history before returning. + This call clears the sound history before returning. -:param event: (esdeveniment) L'esdeveniment per comprovar, com ara ``SoundEvent.LOUD`` o ``SoundEvent.QUIET`` -:return: ``True`` if sound was heard at least once since the last call, otherwise ``False``.""" + :param event: The event to check for, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET`` + :return: ``True`` if sound was heard at least once since the last call, otherwise ``False``. + """ ... def is_event(event: SoundEvent) -> bool: - """Comprova l'esdeveniment sonor més recent detectat. (és un esdeveniment) + """Check the most recent sound event detected. -Example: ``microphone.is_event(SoundEvent.LOUD)`` + Example: ``microphone.is_event(SoundEvent.LOUD)`` -This call does not clear the sound event history. + This call does not clear the sound event history. -:param event: (esdeveniment) L'esdeveniment per comprovar, com ara ``SoundEvent.LOUD`` o ``SoundEvent.QUIET`` -:return: ``True`` if sound was the most recent heard, ``False`` otherwise.""" + :param event: The event to check for, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET`` + :return: ``True`` if sound was the most recent heard, ``False`` otherwise. + """ ... def get_events() -> Tuple[SoundEvent, ...]: - """Obté l'historial d'esdeveniments sonors com una tupla. (obté esdeveniments) + """Get the sound event history as a tuple. -Example: ``microphone.get_events()`` + Example: ``microphone.get_events()`` -This call clears the sound history before returning. + This call clears the sound history before returning. -:return: A tuple of the event history with the most recent event last.""" + :return: A tuple of the event history with the most recent event last. + """ ... def set_threshold(event: SoundEvent, value: int) -> None: - """Assigna el llinar per un esdeveniment sonor (estableix llindar) + """Set the threshold for a sound event. -Example: ``microphone.set_threshold(SoundEvent.LOUD, 250)`` + Example: ``microphone.set_threshold(SoundEvent.LOUD, 250)`` -A high threshold means the event will only trigger if the sound is very loud (>= 250 in the example). + A high threshold means the event will only trigger if the sound is very loud (>= 250 in the example). -:param event: (esdeveniment) Un esdeveniment sonor, com ara ``SoundEvent.LOUD`` o ``SoundEvent.QUIET``. -:param value: (valor) El llindar en l'interval 0-255.""" + :param event: A sound event, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET``. + :param value: The threshold level in the range 0-255. + """ ... def sound_level() -> int: - """Obté el nivell de pressió sonora. (nivell de so) + """Get the sound pressure level. -Example: ``microphone.sound_level()`` + Example: ``microphone.sound_level()`` -:return: A representation of the sound pressure level in the range 0 to 255.""" - ... \ No newline at end of file + :return: A representation of the sound pressure level in the range 0 to 255. + """ + ... diff --git a/lang/ca/typeshed/stdlib/microbit/speaker.pyi b/lang/ca/typeshed/stdlib/microbit/speaker.pyi index dbce9de..5a74a4d 100644 --- a/lang/ca/typeshed/stdlib/microbit/speaker.pyi +++ b/lang/ca/typeshed/stdlib/microbit/speaker.pyi @@ -1,15 +1,18 @@ -"""Controla l'altaveu integrat (només V2). (altaveu)""" +"""Control the built-in speaker (V2 only). +""" def off() -> None: - """Apaga l'altaveu. + """Turn the speaker off. -Example: ``speaker.off()`` + Example: ``speaker.off()`` -This does not disable sound output to an edge connector pin.""" + This does not disable sound output to an edge connector pin. + """ ... def on() -> None: - """Encén l'altaveu. + """Turn the speaker on. -Example: ``speaker.on()``""" - ... \ No newline at end of file + Example: ``speaker.on()`` + """ + ... diff --git a/lang/ca/typeshed/stdlib/microbit/spi.pyi b/lang/ca/typeshed/stdlib/microbit/spi.pyi index d905f08..09c4046 100644 --- a/lang/ca/typeshed/stdlib/microbit/spi.pyi +++ b/lang/ca/typeshed/stdlib/microbit/spi.pyi @@ -1,47 +1,60 @@ -"""Comunica amb dispositius mitjançant el bus d'interfície perifèrica sèrie (SPI).""" +"""Communicate with devices using the serial peripheral interface (SPI) bus. +""" + from _typeshed import ReadableBuffer, WriteableBuffer from ..microbit import pin13, pin14, pin15, MicroBitDigitalPin -def init(baudrate: int=1000000, bits: int=8, mode: int=0, sclk: MicroBitDigitalPin=pin13, mosi: MicroBitDigitalPin=pin15, miso: MicroBitDigitalPin=pin14) -> None: - """Inicialitzar la comunicació SPI. - -Example: ``spi.init()`` - -For correct communication, the parameters have to be the same on both communicating devices. - -:param baudrate: (Velocitat de bauds) La velocitat de comunicació. -:param bits: L'amplada en bits de cada transferència. Actualment només ``bits=8`` és acceptada . Tot i que això pot canviar en el futur -:param mode: Determina la combinació de polaritat i fase del rellotge: `consulta la taula en línia `_. -:param sclk: pin sclk (per defecte 13) -:param mosi: mosi pin (per defecte 15) -:param miso: miso pin (per defecte 14)""" +def init( + baudrate: int = 1000000, + bits: int = 8, + mode: int = 0, + sclk: MicroBitDigitalPin = pin13, + mosi: MicroBitDigitalPin = pin15, + miso: MicroBitDigitalPin = pin14, +) -> None: + """Initialize SPI communication. + + Example: ``spi.init()`` + + For correct communication, the parameters have to be the same on both communicating devices. + + :param baudrate: The speed of communication. + :param bits: The width in bits of each transfer. Currently only ``bits=8`` is supported. However, this may change in the future. + :param mode: Determines the combination of clock polarity and phase - `see online table `_. + :param sclk: sclk pin (default 13) + :param mosi: mosi pin (default 15) + :param miso: miso pin (default 14) + """ ... -def read(nbytes: int, out: int=0) -> bytes: - """Llegeix bytes (llegeix) +def read(nbytes: int, out: int = 0) -> bytes: + """Read at most ``nbytes`` while continuously writing the single byte given by ``out``. -Example: ``spi.read(64)`` + Example: ``spi.read(64)`` -:param nbytes: Nombre màxim de bytes per llegir. -:param out: The byte value to write (default 0). -:return: The bytes read.""" + :param nbytes: Maximum number of bytes to read. + :param out: The byte value to write (default 0). + :return: The bytes read. + """ ... def write(buffer: ReadableBuffer) -> None: - """Escriu bytes al bus. (escriu) + """Write bytes to the bus. -Example: ``spi.write(bytes([1, 2, 3]))`` + Example: ``spi.write(bytes([1, 2, 3]))`` -:param buffer: (memòria intermèdia) Una memòria intermèdia per a llegir dades.""" + :param buffer: A buffer to read data from. + """ ... def write_readinto(out: WriteableBuffer, in_: ReadableBuffer) -> None: - """Escriu la memòria intermèdia ``out`` al bus i llegeix qualsevol resposta a la memòria intermèdia ``in_``. + """Write the ``out`` buffer to the bus and read any response into the ``in_`` buffer. -Example: ``spi.write_readinto(out_buffer, in_buffer)`` + Example: ``spi.write_readinto(out_buffer, in_buffer)`` -The length of the buffers should be the same. The buffers can be the same object. + The length of the buffers should be the same. The buffers can be the same object. -:param out: La memòria intermèdia per a escriure qualsevol resposta. -:param in_: La memòria intermèdia per a llegir dades.""" - ... \ No newline at end of file + :param out: The buffer to write any response to. + :param in_: The buffer to read data from. + """ + ... diff --git a/lang/ca/typeshed/stdlib/microbit/uart.pyi b/lang/ca/typeshed/stdlib/microbit/uart.pyi index 7ff8baa..2ab650f 100644 --- a/lang/ca/typeshed/stdlib/microbit/uart.pyi +++ b/lang/ca/typeshed/stdlib/microbit/uart.pyi @@ -1,79 +1,96 @@ -"""Comunica amb un dispositiu mitjançant una interfície sèrie.""" +"""Communicate with a device using a serial interface. +""" + from _typeshed import WriteableBuffer from ..microbit import MicroBitDigitalPin from typing import Optional, Union -ODD: int -"""Paritat senar (senar)""" -EVEN: int -"""Paritat parella (parell)""" - -def init(baudrate: int=9600, bits: int=8, parity: Optional[int]=None, stop: int=1, tx: Optional[MicroBitDigitalPin]=None, rx: Optional[MicroBitDigitalPin]=None) -> None: - """Inicialitzar la comunicació en sèrie. - -Example: ``uart.init(115200, tx=pin0, rx=pin1)`` -:param baudrate: (Velocitat de bauds) La velocitat de comunicació. -:param bits: La mida dels bytes que es transmeten. micro:bit només n'admet 8. -:param parity: (paritat) Com es verifica la paritat, ``None``, ``uart.ODD`` o ``uart.EVEN``. -:param stop: (atura) El nombre de bits de parada ha de ser 1 per micro:bit. -:param tx: Pin transmissor. -:param rx: Receiving pin. - -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. +ODD: int +"""Odd parity""" -For more details see `the online documentation `_.""" +EVEN: int +"""Even parity""" + +def init( + baudrate: int = 9600, + bits: int = 8, + parity: Optional[int] = None, + stop: int = 1, + tx: Optional[MicroBitDigitalPin] = None, + rx: Optional[MicroBitDigitalPin] = None, +) -> None: + """Initialize serial communication. + + Example: ``uart.init(115200, tx=pin0, rx=pin1)`` + + :param baudrate: The speed of communication. + :param bits: The size of bytes being transmitted. micro:bit only supports 8. + :param parity: How parity is checked, ``None``, ``uart.ODD`` or ``uart.EVEN``. + :param stop: The number of stop bits, has to be 1 for micro:bit. + :param tx: Transmitting pin. + :param rx: Receiving pin. + + 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. + + For more details see `the online documentation `_. + """ ... def any() -> bool: - """Verifica si hi ha alguna data esperant. + """Check if any data is waiting. -Example: ``uart.any()`` + Example: ``uart.any()`` -:return: ``True`` if any data is waiting, else ``False``.""" + :return: ``True`` if any data is waiting, else ``False``. + """ ... -def read(nbytes: Optional[int]=None) -> Optional[bytes]: - """Llegeix bytes (llegeix) +def read(nbytes: Optional[int] = None) -> Optional[bytes]: + """Read bytes. -Example: ``uart.read()`` + Example: ``uart.read()`` -:param nbytes: Si s'especifica ``nbytes``, llegeix com a màxim tants bytes, en cas contrari llegeix tants bytes com sigui possible -:return: A bytes object or ``None`` on timeout""" + :param nbytes: If ``nbytes`` is specified then read at most that many bytes, otherwise read as many bytes as possible + :return: A bytes object or ``None`` on timeout + """ ... -def readinto(buf: WriteableBuffer, nbytes: Optional[int]=None) -> Optional[int]: - """Llegeix bytes al ``buf``. +def readinto(buf: WriteableBuffer, nbytes: Optional[int] = None) -> Optional[int]: + """Read bytes into the ``buf``. -Example: ``uart.readinto(input_buffer)`` + Example: ``uart.readinto(input_buffer)`` -:param buf: La memòria intermèdia a on escriure. -:param nbytes: Si s'especifica ``nbytes``, llegeix com a màxim aquests bytes, en cas contrari llegeix ``len(buf)`` bytes. -:return: number of bytes read and stored into ``buf`` or ``None`` on timeout.""" + :param buf: The buffer to write to. + :param nbytes: If ``nbytes`` is specified then read at most that many bytes, otherwise read ``len(buf)`` bytes. + :return: number of bytes read and stored into ``buf`` or ``None`` on timeout. + """ ... def readline() -> Optional[bytes]: - """Llegir una línia que acaba en un caràcter de nova línia. + """Read a line, ending in a newline character. -Example: ``uart.readline()`` + Example: ``uart.readline()`` -:return: The line read or ``None`` on timeout. The newline character is included in the returned bytes.""" + :return: The line read or ``None`` on timeout. The newline character is included in the returned bytes. + """ ... def write(buf: Union[bytes, str]) -> Optional[int]: - """Escriu una memòria intermèdia al bus (escriu) + """Write a buffer to the bus. -Example: ``uart.write('hello world')`` + Example: ``uart.write('hello world')`` -:param buf: Un objecte bytes o una cadena. -:return: The number of bytes written, or ``None`` on timeout. + :param buf: A bytes object or a string. + :return: The number of bytes written, or ``None`` on timeout. -Examples:: + Examples:: - uart.write('hello world') - uart.write(b'hello world') - uart.write(bytes([1, 2, 3]))""" - ... \ No newline at end of file + uart.write('hello world') + uart.write(b'hello world') + uart.write(bytes([1, 2, 3])) + """ + ... diff --git a/lang/ca/typeshed/stdlib/micropython.pyi b/lang/ca/typeshed/stdlib/micropython.pyi index 2b2ca4a..7a6079f 100644 --- a/lang/ca/typeshed/stdlib/micropython.pyi +++ b/lang/ca/typeshed/stdlib/micropython.pyi @@ -1,133 +1,144 @@ -"""Components interns de MicroPython.""" +"""MicroPython internals.""" + from typing import Any, TypeVar, overload -_T = TypeVar('_T') + +_T = TypeVar("_T") def const(expr: _T) -> _T: - """S'utilitza per declarar que l'expressió és una constant perquè el compilador pugui -optimitzar-la. + """Used to declare that the expression is a constant so that the compiler can + optimise it. -The use of this function should be as follows:: + The use of this function should be as follows:: - from micropython import const - CONST_X = const(123) - CONST_Y = const(2 * CONST_X + 1) + from micropython import const + CONST_X = const(123) + CONST_Y = const(2 * CONST_X + 1) -Constants declared this way are still accessible as global variables from -outside the module they are declared in. On the other hand, if a constant -begins with an underscore then it is hidden, it is not available as a -global variable, and does not take up any memory during execution. + Constants declared this way are still accessible as global variables from + outside the module they are declared in. On the other hand, if a constant + begins with an underscore then it is hidden, it is not available as a + global variable, and does not take up any memory during execution. -:param expr: Una expressió constant""" + :param expr: A constant expression. + """ ... @overload def opt_level() -> int: - """Obté el nivell d'optimització actual per a la compilació d'scripts. + """Get the current optimisation level for the compilation of scripts. -Example: ``micropython.opt_level()`` + Example: ``micropython.opt_level()`` -The optimisation level controls the following compilation features: + The optimisation level controls the following compilation features: -- Assertions: at level 0 assertion statements are enabled and compiled - into the bytecode; at levels 1 and higher assertions are not compiled. + - Assertions: at level 0 assertion statements are enabled and compiled + into the bytecode; at levels 1 and higher assertions are not compiled. -- Built-in ``__debug__`` variable: at level 0 this variable expands to - True; at levels 1 and higher it expands to False. + - Built-in ``__debug__`` variable: at level 0 this variable expands to + True; at levels 1 and higher it expands to False. -- Source-code line numbers: at levels 0, 1 and 2 source-code line number - are stored along with the bytecode so that exceptions can report the - line number they occurred at; at levels 3 and higher line numbers are - not stored. + - Source-code line numbers: at levels 0, 1 and 2 source-code line number + are stored along with the bytecode so that exceptions can report the + line number they occurred at; at levels 3 and higher line numbers are + not stored. -:return: An integer representing the current level.""" + :return: An integer representing the current level. + """ ... @overload def opt_level(level: int) -> None: - """Estableix el nivell d'optimització per a la compilació posterior dels scripts. + """Sets the optimisation level for subsequent compilation of scripts. -Example: ``micropython.opt_level(1)`` + Example: ``micropython.opt_level(1)`` -The optimisation level controls the following compilation features: + The optimisation level controls the following compilation features: -- Assertions: at level 0 assertion statements are enabled and compiled - into the bytecode; at levels 1 and higher assertions are not compiled. + - Assertions: at level 0 assertion statements are enabled and compiled + into the bytecode; at levels 1 and higher assertions are not compiled. -- Built-in ``__debug__`` variable: at level 0 this variable expands to - True; at levels 1 and higher it expands to False. + - Built-in ``__debug__`` variable: at level 0 this variable expands to + True; at levels 1 and higher it expands to False. -- Source-code line numbers: at levels 0, 1 and 2 source-code line number - are stored along with the bytecode so that exceptions can report the - line number they occurred at; at levels 3 and higher line numbers are - not stored. + - Source-code line numbers: at levels 0, 1 and 2 source-code line number + are stored along with the bytecode so that exceptions can report the + line number they occurred at; at levels 3 and higher line numbers are + not stored. -The default optimisation level is usually level 0. + The default optimisation level is usually level 0. -:param level: Un nivell d'optimització enter.""" + :param level: An integer optimisation level. + """ ... -def mem_info(verbose: Any=None) -> None: - """Imprimeix informació sobre la memòria utilitzada actualment. (informació de la memòria) +def mem_info(verbose: Any = None) -> None: + """Print information about currently used memory. -Example: ``micropython.mem_info()`` + Example: ``micropython.mem_info()`` -:param verbose: Si es dona l'argument ``verbose``, s'imprimeix informació addicional.""" + :param verbose: If the ``verbose`` argument is given then extra information is printed. + """ ... -def qstr_info(verbose: Any=None) -> None: - """Imprimeix informació sobre les cadenes internades actualment. +def qstr_info(verbose: Any = None) -> None: + """Print information about currently interned strings. -Example: ``micropython.qstr_info()`` + Example: ``micropython.qstr_info()`` -:param verbose: Si es dona l'argument ``verbose``, s'imprimeix informació addicional. + :param verbose: If the ``verbose`` argument is given then extra information is printed. -The information that is printed is implementation dependent, but currently -includes the number of interned strings and the amount of RAM they use. In -verbose mode it prints out the names of all RAM-interned strings.""" + The information that is printed is implementation dependent, but currently + includes the number of interned strings and the amount of RAM they use. In + verbose mode it prints out the names of all RAM-interned strings. + """ ... def stack_use() -> int: - """Retorna un nombre enter que representa la quantitat actual de pila que està sent -utilitzada. + """Return an integer representing the current amount of stack that is being + used. -Example: ``micropython.stack_use()`` + Example: ``micropython.stack_use()`` -The absolute value of this is not particularly useful, rather it -should be used to compute differences in stack usage at different points. + The absolute value of this is not particularly useful, rather it + should be used to compute differences in stack usage at different points. -:return: An integer representing current stack use.""" + :return: An integer representing current stack use. + """ ... def heap_lock() -> None: - """Bloqueja el munt. + """Lock the heap. -Example: ``micropython.heap_lock()`` + Example: ``micropython.heap_lock()`` -When locked no memory allocation can occur and a ``MemoryError`` will be -raised if any heap allocation is attempted.""" + When locked no memory allocation can occur and a ``MemoryError`` will be + raised if any heap allocation is attempted. + """ ... def heap_unlock() -> None: - """Desbloqueja el munt. + """Unlock the heap. -Example: ``micropython.heap_unlock()`` + Example: ``micropython.heap_unlock()`` -When locked no memory allocation can occur and a ``MemoryError`` will be -raised if any heap allocation is attempted.""" + When locked no memory allocation can occur and a ``MemoryError`` will be + raised if any heap allocation is attempted. + """ ... def kbd_intr(chr: int) -> None: - """Estableix el caràcter que generarà una excepció ``KeyboardInterrupt``. + """Set the character that will raise a ``KeyboardInterrupt`` exception. -Example: ``micropython.kbd_intr(-1)`` + Example: ``micropython.kbd_intr(-1)`` -:param chr: Codi de caràcter per augmentar la interrupció o -1 per desactivar la captura de Ctrl-C. + :param chr: Character code to raise the interrupt or -1 to disable capture of Ctrl-C. -By default this is set to 3 during script execution, corresponding to Ctrl-C. -Passing -1 to this function will disable capture of Ctrl-C, and passing 3 -will restore it. + By default this is set to 3 during script execution, corresponding to Ctrl-C. + Passing -1 to this function will disable capture of Ctrl-C, and passing 3 + will restore it. -This function can be used to prevent the capturing of Ctrl-C on the -incoming stream of characters that is usually used for the REPL, in case -that stream is used for other purposes.""" - ... \ No newline at end of file + This function can be used to prevent the capturing of Ctrl-C on the + incoming stream of characters that is usually used for the REPL, in case + that stream is used for other purposes. + """ + ... diff --git a/lang/ca/typeshed/stdlib/music.pyi b/lang/ca/typeshed/stdlib/music.pyi index b748d9f..5f4778b 100644 --- a/lang/ca/typeshed/stdlib/music.pyi +++ b/lang/ca/typeshed/stdlib/music.pyi @@ -1,128 +1,167 @@ -"""Crea i toca melodies. (música)""" +"""Create and play melodies. +""" from typing import Optional, Tuple, Union, List + from .microbit import MicroBitDigitalPin, pin0 + DADADADUM: Tuple[str, ...] -"""Melodia: l'obertura de la cinquena simfonia de Beethoven en Do menor.""" +"""Melody: the opening to Beethoven’s 5th Symphony in C minor.""" + ENTERTAINER: Tuple[str, ...] -"""Melodia: el fragment inicial del clàssic Ragtime de Scott Joplin "The Entertainer".""" +"""Melody: the opening fragment of Scott Joplin’s Ragtime classic “The Entertainer”.""" + PRELUDE: Tuple[str, ...] -"""Melodia: obertura del primer Preludi en Do Major dels 48 Preludis i Fugues de J.S. Bach. (preludi)""" +"""Melody: the opening of the first Prelude in C Major of J.S.Bach’s 48 Preludes and Fugues.""" + ODE: Tuple[str, ...] -"""Melodia: el tema "Oda a l'alegria" de la 9a simfonia en Re menor de Beethoven. (oda)""" +"""Melody: the “Ode to Joy” theme from Beethoven’s 9th Symphony in D minor.""" + NYAN: Tuple[str, ...] -"""Melodia: el tema Nyan Cat (http://www.nyan.cat/). +"""Melody: the Nyan Cat theme (http://www.nyan.cat/). The composer is unknown. This is fair use for educational porpoises (as they say in New York).""" + RINGTONE: Tuple[str, ...] -"""Melodia: quelcom que sona com un to de trucada de telèfon mòbil. (to de trucada) +"""Melody: something that sounds like a mobile phone ringtone. To be used to indicate an incoming message. """ + FUNK: Tuple[str, ...] -"""Melodia: una línia de baix funky per a agents secrets i cervells criminals.""" +"""Melody: a funky bass line for secret agents and criminal masterminds.""" + BLUES: Tuple[str, ...] -"""Melodia: un blues walking bass boogie-woogie de dotze compassos.""" +"""Melody: a boogie-woogie 12-bar blues walking bass.""" + BIRTHDAY: Tuple[str, ...] -"""Melodia: “Feliç aniversari…” (aniversari) +"""Melody: “Happy Birthday to You…” For copyright status see: http://www.bbc.co.uk/news/world-us-canada-34332853 """ + WEDDING: Tuple[str, ...] -"""Melodia: el cor nupcial de l'òpera Lohengrin de Wagner. (casament)""" +"""Melody: the bridal chorus from Wagner’s opera “Lohengrin”.""" + FUNERAL: Tuple[str, ...] -"""Melodia: la “marxa fúnebre” com es coneix la Sonata per a piano No 2. en Si bemoll menor Op. 35 de Frédéric Chopin .""" +"""Melody: the “funeral march” otherwise known as Frédéric Chopin’s Piano Sonata No. 2 in B♭ minor, Op. 35.""" + PUNCHLINE: Tuple[str, ...] -"""Melodia: un fragment divertit que significa que s'ha fet una broma.""" +"""Melody: a fun fragment that signifies a joke has been made.""" + PYTHON: Tuple[str, ...] -"""Melodia: la marxa de John Philip Sousa "Liberty Bell", també conegut com, el tema de "Monty Python's Flying Circus" (a partir de la qual s'anomena el llenguatge de programació Python).""" +"""Melody: John Philip Sousa’s march “Liberty Bell” aka, the theme for “Monty Python’s Flying Circus” (after which the Python programming language is named).""" + BADDY: Tuple[str, ...] -"""Melodia: entrada d'un dolent a l'era del cinema mut. (dolent)""" +"""Melody: silent movie era entrance of a baddy.""" + CHASE: Tuple[str, ...] -"""Melodia: escena de persecució de l'era del cinema mut. (persecució)""" +"""Melody: silent movie era chase scene.""" + BA_DING: Tuple[str, ...] -"""Melodia: senyal breu per indicar que alguna cosa ha passat.""" +"""Melody: a short signal to indicate something has happened.""" + WAWAWAWAA: Tuple[str, ...] -"""Melodia: un trombó molt trist.""" +"""Melody: a very sad trombone.""" + JUMP_UP: Tuple[str, ...] -"""Melodia: per utilitzar-se en un joc, indicant moviment cap amunt. (saltar cap amunt)""" +"""Melody: for use in a game, indicating upward movement.""" + JUMP_DOWN: Tuple[str, ...] -"""Melodia: per utilitzar en un joc, que indica moviment cap avall. (saltar cap avall)""" +"""Melody: for use in a game, indicating downward movement.""" + POWER_UP: Tuple[str, ...] -"""Melodia: una fanfàrria per indicar un assoliment desbloquejat. (engegar)""" +"""Melody: a fanfare to indicate an achievement unlocked.""" + POWER_DOWN: Tuple[str, ...] -"""Melodia: una trista fanfàrria per indicar un assoliment perdut. (apagar)""" +"""Melody: a sad fanfare to indicate an achievement lost.""" -def set_tempo(ticks: int=4, bpm: int=120) -> None: - """Estableix el tempo aproximat per la reproducció. +def set_tempo(ticks: int = 4, bpm: int = 120) -> None: + """Sets the approximate tempo for playback. -Example: ``music.set_tempo(bpm=120)`` + Example: ``music.set_tempo(bpm=120)`` -:param ticks: El nombre de tics que constitueixen un ritme. -:param bpm: Un nombre enter determinant quantes pulsacions per minut. + :param ticks: The number of ticks constituting a beat. + :param bpm: An integer determining how many beats per minute. -Suggested default values allow the following useful behaviour: + Suggested default values allow the following useful behaviour: -- music.set_tempo() – reset the tempo to default of ticks = 4, bpm = 120 -- music.set_tempo(ticks=8) – change the “definition” of a beat -- music.set_tempo(bpm=180) – just change the tempo + - music.set_tempo() – reset the tempo to default of ticks = 4, bpm = 120 + - music.set_tempo(ticks=8) – change the “definition” of a beat + - music.set_tempo(bpm=180) – just change the tempo -To work out the length of a tick in milliseconds is very simple arithmetic: -60000/bpm/ticks_per_beat. For the default values that’s -60000/120/4 = 125 milliseconds or 1 beat = 500 milliseconds.""" + To work out the length of a tick in milliseconds is very simple arithmetic: + 60000/bpm/ticks_per_beat. For the default values that’s + 60000/120/4 = 125 milliseconds or 1 beat = 500 milliseconds. + """ ... def get_tempo() -> Tuple[int, int]: - """Obté el tempo actual com una tupla d'enters:``(ticks, bpm)``. (obté el tempo) + """Gets the current tempo as a tuple of integers: ``(ticks, bpm)``. -Example: ``ticks, beats = music.get_tempo()`` + Example: ``ticks, beats = music.get_tempo()`` -:return: The temp as a tuple with two integer values, the ticks then the beats per minute.""" + :return: The temp as a tuple with two integer values, the ticks then the beats per minute. + """ ... -def play(music: Union[str, List[str], Tuple[str, ...]], pin: Optional[MicroBitDigitalPin]=pin0, wait: bool=True, loop: bool=False) -> None: - """Tocar música +def play( + music: Union[str, List[str], Tuple[str, ...]], + pin: Optional[MicroBitDigitalPin] = pin0, + wait: bool = True, + loop: bool = False, +) -> None: + """Plays music. -Example: ``music.play(music.NYAN)`` + Example: ``music.play(music.NYAN)`` -:param music: (música) música especificada en `una notació especial `_ -:param pin: el pin de sortida per utilitzar-lo amb un altaveu extern (``pin0`` per defecte), ``None`` per no fer so. -:param wait: (espera) Si ``wait`` s'estableix en ``True``, aquesta funció està bloquejant. -:param loop: (bucle) Si el ``loop`` s'estableix en ``True``, la melodia es repeteix fins que es crida ``stop`` o s'interromp la trucada de bloqueig. + :param music: music specified in `a special notation `_ + :param pin: the output pin for use with an external speaker (default ``pin0``), ``None`` for no sound. + :param wait: If ``wait`` is set to ``True``, this function is blocking. + :param loop: If ``loop`` is set to ``True``, the tune repeats until ``stop`` is called or the blocking call is interrupted. -Many built-in melodies are defined in this module.""" + Many built-in melodies are defined in this module. + """ ... -def pitch(frequency: int, duration: int=-1, pin: Optional[MicroBitDigitalPin]=pin0, wait: bool=True) -> None: - """Toca una nota. (altura del to) +def pitch( + frequency: int, + duration: int = -1, + pin: Optional[MicroBitDigitalPin] = pin0, + wait: bool = True, +) -> None: + """Play a note. -Example: ``music.pitch(185, 1000)`` + Example: ``music.pitch(185, 1000)`` -:param frequency: (freqüència) Una freqüència de nombre enter -:param duration: (Durada - duració) Una duració d'un mil·lisegon. Si és negativa, el so és continu fins a la nova crida o una crida a ``stop``. -:param pin: Pin de sortida opcional (``pin0`` per defecte). -:param wait: (espera) Si ``wait`` s'estableix en ``True``, aquesta funció està bloquejant. + :param frequency: An integer frequency + :param duration: A millisecond duration. If negative then sound is continuous until the next call or a call to ``stop``. + :param pin: Optional output pin (default ``pin0``). + :param wait: If ``wait`` is set to ``True``, this function is blocking. -For example, if the frequency is set to 440 and the length to -1000 then we hear a standard concert A for one second. + For example, if the frequency is set to 440 and the length to + 1000 then we hear a standard concert A for one second. -You can only play one pitch on one pin at any one time.""" + You can only play one pitch on one pin at any one time. + """ ... -def stop(pin: Optional[MicroBitDigitalPin]=pin0) -> None: - """Atura tota la reproducció de música a l'altaveu integrat i qualsevol so de sortida de pin. (atura) +def stop(pin: Optional[MicroBitDigitalPin] = pin0) -> None: + """Stops all music playback on the built-in speaker and any pin outputting sound. -Example: ``music.stop()`` + Example: ``music.stop()`` -:param pin: Es pot proporcionar un argument opcional per especificar un pin, per exemple ``music.stop(pin1)``.""" + :param pin: An optional argument can be provided to specify a pin, e.g. ``music.stop(pin1)``. + """ def reset() -> None: - """Restableix els tics, ppm, duració i octava al seu valor per defecte. (reiniciar) + """Resets ticks, bpm, duration and octave to their default values. -Example: ``music.reset()`` + Example: ``music.reset()`` -Values: -- ``ticks = 4`` -- ``bpm = 120`` -- ``duration = 4`` -- ``octave = 4``""" - ... \ No newline at end of file + Values: + - ``ticks = 4`` + - ``bpm = 120`` + - ``duration = 4`` + - ``octave = 4`` + """ + ... diff --git a/lang/ca/typeshed/stdlib/neopixel.pyi b/lang/ca/typeshed/stdlib/neopixel.pyi index ec85e74..2d5a749 100644 --- a/lang/ca/typeshed/stdlib/neopixel.pyi +++ b/lang/ca/typeshed/stdlib/neopixel.pyi @@ -1,81 +1,82 @@ -"""Cintes LED RGB i RGBW adreçables individualment.""" +"""Individually addressable RGB and RGBW LED strips. +""" from .microbit import MicroBitDigitalPin from typing import Tuple class NeoPixel: + def __init__(self, pin: MicroBitDigitalPin, n: int, bpp: int = 3) -> None: + """Initialise a new strip of neopixel LEDs controlled via a pin. - def __init__(self, pin: MicroBitDigitalPin, n: int, bpp: int=3) -> None: - """Inicialitza una nova tira de LED de neopixel controlada mitjançant un pin. + Example: ``np = neopixel.NeoPixel(pin0, 8)`` -Example: ``np = neopixel.NeoPixel(pin0, 8)`` + To support RGBW neopixels, a third argument can be passed to + ``NeoPixel`` to indicate the number of bytes per pixel (``bpp``). + For RGBW, this is is 4 rather than the default of 3 for RGB and GRB. -To support RGBW neopixels, a third argument can be passed to -``NeoPixel`` to indicate the number of bytes per pixel (``bpp``). -For RGBW, this is is 4 rather than the default of 3 for RGB and GRB. + Each pixel is addressed by a position (starting from 0). Neopixels are + given RGB (red, green, blue) / RGBW (red, green, blue, white) values + between 0-255 as a tuple. For example, in RGB, ``(255,255,255)`` is + white. In RGBW, ``(255,255,255,0)`` or ``(0,0,0,255)`` is white. -Each pixel is addressed by a position (starting from 0). Neopixels are -given RGB (red, green, blue) / RGBW (red, green, blue, white) values -between 0-255 as a tuple. For example, in RGB, ``(255,255,255)`` is -white. In RGBW, ``(255,255,255,0)`` or ``(0,0,0,255)`` is white. + See `the online docs `_ for warnings and other advice. -See `the online docs `_ for warnings and other advice. - -:param pin: El pin que controla la tira de neopíxels. -:param n: El nombre de neopíxels de la tira. -:param bpp: Bytes per píxel. Per al suport del neopixel RGBW , passa 4 en lloc dels 3 per defecte per a RGB i GRB.""" + :param pin: The pin controlling the neopixel strip. + :param n: The number of neopixels in the strip. + :param bpp: Bytes per pixel. For RGBW neopixel support, pass 4 rather than the default of 3 for RGB and GRB. + """ ... - def clear(self) -> None: - """Esborra tots els píxels. + """Clear all the pixels. -Example: ``np.clear()``""" + Example: ``np.clear()`` + """ ... - def show(self) -> None: - """mostra els píxels. + """Show the pixels. -Example: ``np.show()`` + Example: ``np.show()`` -Must be called for any updates to become visible.""" + Must be called for any updates to become visible. + """ ... - def write(self) -> None: - """Mostra els píxels (només micro:bit V2) (escriu) + """Show the pixels (micro:bit V2 only). -Example: ``np.write()`` + Example: ``np.write()`` -Must be called for any updates to become visible. + Must be called for any updates to become visible. -Equivalent to ``show``.""" + Equivalent to ``show``. + """ ... - def fill(self, colour: Tuple[int, ...]) -> None: - """Acoloreix tots els píxels amb un valor RGB/RGBW determinat (només micro:bit V2). (omple) + """Colour all pixels a given RGB/RGBW value (micro:bit V2 only). -Example: ``np.fill((0, 0, 255))`` + Example: ``np.fill((0, 0, 255))`` -:param colour: (color) Una tupla de la mateixa longitud que el nombre de bytes per píxel (bpp). + :param colour: A tuple of the same length as the number of bytes per pixel (bpp). -Use in conjunction with ``show()`` to update the neopixels.""" + Use in conjunction with ``show()`` to update the neopixels. + """ ... - def __setitem__(self, key: int, value: Tuple[int, ...]) -> None: - """Estableix un color de píxel. + """Set a pixel colour. -Example: ``np[0] = (255, 0, 0)`` - -:param key: El nombre de píxels. -:param value: (valor) El color.""" + Example: ``np[0] = (255, 0, 0)`` + :param key: The pixel number. + :param value: The colour. + """ def __getitem__(self, key: int) -> Tuple[int, ...]: - """Obté un color de píxel. - -Example: ``r, g, b = np[0]`` + """Get a pixel colour. -:param key: El nombre de píxels. -:return: The colour tuple.""" + Example: ``r, g, b = np[0]`` + :param key: The pixel number. + :return: The colour tuple. + """ def __len__(self) -> int: - """Obté la longitud d'aquesta cinta de píxels. + """Get length of this pixel strip. -Example: ``len(np)``""" \ No newline at end of file + Example: ``len(np)`` + """ diff --git a/lang/ca/typeshed/stdlib/os.pyi b/lang/ca/typeshed/stdlib/os.pyi index 53b62c0..2f2db77 100644 --- a/lang/ca/typeshed/stdlib/os.pyi +++ b/lang/ca/typeshed/stdlib/os.pyi @@ -1,63 +1,73 @@ -"""Accedeix al sistema de fitxers.""" +"""Access the file system. +""" + from typing import Tuple from typing import List def listdir() -> List[str]: - """Llista dels fitxers. + """List files. -Example: ``os.listdir()`` + Example: ``os.listdir()`` -:return: A list of the names of all the files contained within the local -persistent on-device file system.""" + :return: A list of the names of all the files contained within the local + persistent on-device file system. + """ ... def remove(filename: str) -> None: - """Eliminar (suprimir) un fitxer. (eliminar) + """Remove (delete) a file. -Example: ``os.remove('data.txt')`` + Example: ``os.remove('data.txt')`` -:param filename: (nom del fitxer) El fitxer a suprimir. + :param filename: The file to delete. -If the file does not exist an ``OSError`` exception will occur.""" + If the file does not exist an ``OSError`` exception will occur. + """ ... def size(filename: str) -> int: - """Retorna la mida d'un fitxer (mida) + """Returns the size of a file. -Example: ``os.size('data.txt')`` + Example: ``os.size('data.txt')`` -:param filename: (nom del fitxer) El fitxer -:return: The size in bytes. + :param filename: The file + :return: The size in bytes. -If the file does not exist an ``OSError`` exception will occur.""" + If the file does not exist an ``OSError`` exception will occur. + """ class uname_result(Tuple[str, str, str, str, str]): - """Resultat de ``os.uname()``""" + """Result of ``os.uname()``""" sysname: str - """Nom del sistema operatiu.""" + """Operating system name.""" + nodename: str - """Nom de la màquina a la xarxa (definida per la implementació).""" + """Name of machine on network (implementation-defined).""" + release: str - """Versió del sistema operatiu. (versió)""" + """Operating system release.""" + version: str - """Versió del sistema operatiu. (versió)""" + """Operating system version.""" + machine: str - """Identificador del maquinari. (màquina)""" + """Hardware identifier.""" def uname() -> uname_result: - """Retorna informació que identifica el sistema operatiu actual. + """Returns information identifying the current operating system. -Example: ``os.uname()`` + Example: ``os.uname()`` -The return value is an object with five attributes: + The return value is an object with five attributes: -- ``sysname`` - operating system name -- ``nodename`` - name of machine on network (implementation-defined) -- ``release`` - operating system release -- ``version`` - operating system version -- ``machine`` - hardware identifier + - ``sysname`` - operating system name + - ``nodename`` - name of machine on network (implementation-defined) + - ``release`` - operating system release + - ``version`` - operating system version + - ``machine`` - hardware identifier -There is no underlying operating system in MicroPython. As a result the -information returned by the ``uname`` function is mostly useful for -versioning details.""" - ... \ No newline at end of file + There is no underlying operating system in MicroPython. As a result the + information returned by the ``uname`` function is mostly useful for + versioning details. + """ + ... diff --git a/lang/ca/typeshed/stdlib/radio.pyi b/lang/ca/typeshed/stdlib/radio.pyi index 8b7bc98..8dd0267 100644 --- a/lang/ca/typeshed/stdlib/radio.pyi +++ b/lang/ca/typeshed/stdlib/radio.pyi @@ -1,130 +1,152 @@ -"""Comunicar-se entre micro:bits amb la ràdio integrada. (ràdio)""" +"""Communicate between micro:bits with the built-in radio. +""" + from _typeshed import WriteableBuffer from typing import Optional, Tuple + RATE_1MBIT: int -"""La constant utilitzada per indicar un rendiment d'1 Mbit per segon. (velocitat de transmissió 1mbit)""" +"""Constant used to indicate a throughput of 1 MBit a second.""" + RATE_2MBIT: int -"""La constant utilitzada per indicar un rendiment de 2 Mbit per segon. (velocitat de transmissió 2mbit)""" +"""Constant used to indicate a throughput of 2 MBit a second.""" def on() -> None: - """Encén la ràdio. + """Turns the radio on. -Example: ``radio.on()`` + Example: ``radio.on()`` -This needs to be explicitly called since the radio draws power and takes -up memory that you may otherwise need.""" + This needs to be explicitly called since the radio draws power and takes + up memory that you may otherwise need. + """ ... def off() -> None: - """Apaga la ràdio, estalviant energia i memòria. + """Turns off the radio, saving power and memory. -Example: ``radio.off()``""" + Example: ``radio.off()`` + """ ... -def config(length: int=32, queue: int=3, channel: int=7, power: int=6, address: int=1969383796, group: int=0, data_rate: int=RATE_1MBIT) -> None: - """Configura la ràdio. - -Example: ``radio.config(group=42)`` - -The default configuration is suitable for most use. - -:param length: (llargada) (per defecte=32) defineix la longitud màxima, en bytes, d'un missatge enviat a través de la ràdio. -Pot tenir una longitud de fins a 251 bytes (254 - 3 bytes per al preàmbul S0, LENGTH i S1). -:param queue: (cua) (per defecte=3) especifica el nombre de missatges que es poden emmagatzemar a la cua de missatges entrants. -Si no queden espais a la cua per als missatges entrants, s'elimina el missatge entrant. -:param channel: (canal) (per defecte=7) un valor enter de 0 a 83 (inclosos) que defineix un "canal" arbitrari al qual està sintonitzada la ràdio. -Els missatges s'enviaran a través d'aquest canal i només els missatges rebuts per aquest canal es posaran a la cua de missatges entrants. Cada pas té una amplada d'1MHz, basat en 2400MHz. -:param power: (per defecte=6) és un valor enter de 0 a 7 (inclosos) per indicar la intensitat del senyal utilitzat quan s'emet un missatge. -Com més alt sigui el valor, més fort és el senyal, però més potència consumeix el dispositiu. La numeració es tradueix en posicions a la llista següent de valors en dBm (decibels mil·liwatts): -30, -20, -16, -12, -8, -4, 0, 4. -:param address: (adreça) (per defecte=0x75626974) un nom arbitrari, expressat com una adreça de 32 bits, que s'utilitza per filtrar els paquets entrants a nivell de maquinari, conservant només els que coincideixen amb l'adreça que has establert. -La configuració predeterminada utilitzada per altres plataformes relacionades amb micro:bit és la configuració predeterminada que s'utilitza aquí. -:param group: (grup) (per defecte=0) un valor de 8 bits (0-255) utilitzat amb l'``address`` (adreça) en filtrar missatges. -Conceptualment, "adreça" és com una adreça de casa/oficina i "grup" és com la persona a aquesta adreça a la qual vols enviar el teu missatge. -:param data_rate: (velocitat de dades) (per defecte=``radio.RATE_1MBIT``) indica la velocitat a la qual es produeix la transmissió de les dades. -Pot ser una de les constants següents definides al mòdul ``radio``: ``RATE_250KBIT``, ``RATE_1MBIT`` o ``RATE_2MBIT``. - -If ``config`` is not called then the defaults described above are assumed.""" +def config( + length: int = 32, + queue: int = 3, + channel: int = 7, + power: int = 6, + address: int = 0x75626974, + group: int = 0, + data_rate: int = RATE_1MBIT, +) -> None: + """Configures the radio. + + Example: ``radio.config(group=42)`` + + The default configuration is suitable for most use. + + :param length: (default=32) defines the maximum length, in bytes, of a message sent via the radio. + It can be up to 251 bytes long (254 - 3 bytes for S0, LENGTH and S1 preamble). + :param queue: (default=3) specifies the number of messages that can be stored on the incoming message queue. + If there are no spaces left on the queue for incoming messages, then the incoming message is dropped. + :param channel: (default=7) an integer value from 0 to 83 (inclusive) that defines an arbitrary "channel" to which the radio is tuned. + Messages will be sent via this channel and only messages received via this channel will be put onto the incoming message queue. Each step is 1MHz wide, based at 2400MHz. + :param power: (default=6) is an integer value from 0 to 7 (inclusive) to indicate the strength of signal used when broadcasting a message. + The higher the value the stronger the signal, but the more power is consumed by the device. The numbering translates to positions in the following list of dBm (decibel milliwatt) values: -30, -20, -16, -12, -8, -4, 0, 4. + :param address: (default=0x75626974) an arbitrary name, expressed as a 32-bit address, that's used to filter incoming packets at the hardware level, keeping only those that match the address you set. + The default used by other micro:bit related platforms is the default setting used here. + :param group: (default=0) an 8-bit value (0-255) used with the ``address`` when filtering messages. + Conceptually, "address" is like a house/office address and "group" is like the person at that address to which you want to send your message. + :param data_rate: (default=``radio.RATE_1MBIT``) indicates the speed at which data throughput takes place. + Can be one of the following constants defined in the ``radio`` module: ``RATE_250KBIT``, ``RATE_1MBIT`` or ``RATE_2MBIT``. + + If ``config`` is not called then the defaults described above are assumed. + """ ... def reset() -> None: - """Restableix la configuració als seus valors predeterminats. (reiniciar) + """Reset the settings to their default values. -Example: ``radio.reset()`` + Example: ``radio.reset()`` -The defaults as as per the ``config`` function above.""" + The defaults as as per the ``config`` function above. + """ ... def send_bytes(message: bytes) -> None: - """Envia un missatge que conté bytes. (enviar bytes) + """Sends a message containing bytes. -Example: ``radio.send_bytes(b'hello')`` + Example: ``radio.send_bytes(b'hello')`` -:param message: (missatge) Els bytes a ser enviats.""" + :param message: The bytes to send. + """ ... def receive_bytes() -> Optional[bytes]: - """Rebràs el següent missatge entrant a la cua de missatges. (rebre bytes) + """Receive the next incoming message on the message queue. -Example: ``radio.receive_bytes()`` + Example: ``radio.receive_bytes()`` -:return: The message bytes if any, otherwise ``None``.""" + :return: The message bytes if any, otherwise ``None``. + """ ... def receive_bytes_into(buffer: WriteableBuffer) -> Optional[int]: - """Copia el següent missatge entrant de la cua de missatges a una memòria intermèdia. (rebre bytes a) + """Copy the next incoming message on the message queue into a buffer. -Example: ``radio.receive_bytes_info(buffer)`` + Example: ``radio.receive_bytes_info(buffer)`` -:param buffer: (memòria intermèdia) La memòria intermèdia objectiu. El missatge es trunca si és més gran que la memòria intermèdia. -:return: ``None`` if there are no pending messages, otherwise it returns the length of the message (which might be more than the length of the buffer).""" + :param buffer: The target buffer. The message is truncated if larger than the buffer. + :return: ``None`` if there are no pending messages, otherwise it returns the length of the message (which might be more than the length of the buffer). + """ ... def send(message: str) -> None: - """Envia una cadena de missatge. (envia) + """Sends a message string. -Example: ``radio.send('hello')`` + Example: ``radio.send('hello')`` -This is the equivalent of ``radio.send_bytes(bytes(message, 'utf8'))`` but with ``b'\x01\x00\x01'`` -prepended to the front (to make it compatible with other platforms that target the micro:bit). + This is the equivalent of ``radio.send_bytes(bytes(message, 'utf8'))`` but with ``b'\x01\x00\x01'`` + prepended to the front (to make it compatible with other platforms that target the micro:bit). -:param message: (missatge) La cadena a enviar.""" + :param message: The string to send. + """ ... def receive() -> Optional[str]: - """Funciona exactament de la mateixa manera que ``receive_bytes`` però retorna el que s'ha enviat. + """Works in exactly the same way as ``receive_bytes`` but returns whatever was sent. -Example: ``radio.receive()`` + Example: ``radio.receive()`` -Equivalent to ``str(receive_bytes(), 'utf8')`` but with a check that the the first -three bytes are ``b'\x01\x00\x01'`` (to make it compatible with other platforms that -may target the micro:bit). + Equivalent to ``str(receive_bytes(), 'utf8')`` but with a check that the the first + three bytes are ``b'\x01\x00\x01'`` (to make it compatible with other platforms that + may target the micro:bit). -:return: The message with the prepended bytes stripped and converted to a string. + :return: The message with the prepended bytes stripped and converted to a string. -A ``ValueError`` exception is raised if conversion to string fails.""" + A ``ValueError`` exception is raised if conversion to string fails. + """ ... def receive_full() -> Optional[Tuple[bytes, int, int]]: - """Retorna una tupla que conté tres valors que representen el següent missatge entrant a la cua de missatges. (rebre ple) + """Returns a tuple containing three values representing the next incoming message on the message queue. -Example: ``radio.receive_full()`` + Example: ``radio.receive_full()`` -If there are no pending messages then ``None`` is returned. + If there are no pending messages then ``None`` is returned. -The three values in the tuple represent: + The three values in the tuple represent: -- the next incoming message on the message queue as bytes. -- the RSSI (signal strength): a value between 0 (strongest) and -255 (weakest) as measured in dBm. -- a microsecond timestamp: the value returned by ``time.ticks_us()`` when the message was received. + - the next incoming message on the message queue as bytes. + - the RSSI (signal strength): a value between 0 (strongest) and -255 (weakest) as measured in dBm. + - a microsecond timestamp: the value returned by ``time.ticks_us()`` when the message was received. -For example:: + For example:: - details = radio.receive_full() - if details: - msg, rssi, timestamp = details + details = radio.receive_full() + if details: + msg, rssi, timestamp = details -This function is useful for providing information needed for triangulation -and/or trilateration with other micro:bit devices. + This function is useful for providing information needed for triangulation + and/or trilateration with other micro:bit devices. -:return: ``None`` if there is no message, otherwise a tuple of length three with the bytes, strength and timestamp values.""" - ... \ No newline at end of file + :return: ``None`` if there is no message, otherwise a tuple of length three with the bytes, strength and timestamp values. + """ + ... diff --git a/lang/ca/typeshed/stdlib/random.pyi b/lang/ca/typeshed/stdlib/random.pyi index 34ccc2b..a2c2ef3 100644 --- a/lang/ca/typeshed/stdlib/random.pyi +++ b/lang/ca/typeshed/stdlib/random.pyi @@ -1,81 +1,93 @@ -"""Genera nombres aleatoris. (aleatori)""" +"""Generate random numbers. +""" from typing import TypeVar, Sequence, Union, overload def getrandbits(n: int) -> int: - """Genera un nombre enter amb ``n`` bits aleatoris. + """Generate an integer with ``n`` random bits. -Example: ``random.getrandbits(1)`` + Example: ``random.getrandbits(1)`` -:param n: Un valor entre 1-30 (inclusiu).""" + :param n: A value between 1-30 (inclusive). + """ ... def seed(n: int) -> None: - """Inicialitza el generador de nombres aleatoris. (llavor) + """Initialize the random number generator. -Example: ``random.seed(0)`` + Example: ``random.seed(0)`` -:param n: The integer seed + :param n: The integer seed -This will give you reproducibly deterministic randomness from a given starting -state (``n``).""" + This will give you reproducibly deterministic randomness from a given starting + state (``n``). + """ ... def randint(a: int, b: int) -> int: - """Tria un nombre enter aleatori entre ``a`` i ``b`` inclosos. + """Choose a random integer between ``a`` and ``b`` inclusive. -Example: ``random.randint(0, 9)`` + Example: ``random.randint(0, 9)`` -:param a: Valor inicial de l'interval (inclòs) -:param b: Valor final de l'interval (inclòs) + :param a: Start value for the range (inclusive) + :param b: End value for the range (inclusive) -Alias for ``randrange(a, b + 1)``.""" + Alias for ``randrange(a, b + 1)``. + """ ... @overload def randrange(stop: int) -> int: - """Tria un nombre enter seleccionat aleatòriament entre zero i fins a (però no -inclòs) ``stop``. + """Choose a randomly selected integer between zero and up to (but not + including) ``stop``. -Example: ``random.randrange(10)`` + Example: ``random.randrange(10)`` -:param stop: (atura) Valor final de l'interval (exclòs)""" + :param stop: End value for the range (exclusive) + """ ... @overload -def randrange(start: int, stop: int, step: int=1) -> int: - """Tria un element seleccionat aleatòriament de ``range(start, stop, step)``. +def randrange(start: int, stop: int, step: int = 1) -> int: + """ + Choose a randomly selected element from ``range(start, stop, step)``. -Example: ``random.randrange(0, 10)`` + Example: ``random.randrange(0, 10)`` -:param start: L'inici de l'interval (inclòs) -:param stop: (atura) El final de l'interval (exclusiu) -:param step: El pas.""" + :param start: The start of the range (inclusive) + :param stop: The end of the range (exclusive) + :param step: The step. + """ ... -_T = TypeVar('_T') + +_T = TypeVar("_T") def choice(seq: Sequence[_T]) -> _T: - """Tria un element aleatori de la seqüència no buida ``seq``. + """Choose a random element from the non-empty sequence ``seq``. -Example: ``random.choice([Image.HAPPY, Image.SAD])`` + Example: ``random.choice([Image.HAPPY, Image.SAD])`` -:param seq: Una seqüència. + :param seq: A sequence. -If ``seq`` is empty, raises ``IndexError``.""" + If ``seq`` is empty, raises ``IndexError``. + """ ... def random() -> float: - """Genera un nombre aleatori de coma flotant en l'interval [0.0, 1.0). (aleatori) + """Generate a random floating point number in the range [0.0, 1.0). -Example: ``random.random()`` + Example: ``random.random()`` -:return: The random floating point number""" + :return: The random floating point number + """ ... def uniform(a: float, b: float) -> float: - """Retorna un nombre de coma flotant aleatori entre ``a`` i ``b`` inclosos. (uniforme) + """ + Return a random floating point number between ``a`` and ``b`` inclusive. -Example: ``random.uniform(0, 9)`` + Example: ``random.uniform(0, 9)`` -:param a: Valor inicial de l'interval (inclòs) -:param b: Valor final de l'interval (inclòs)""" - ... \ No newline at end of file + :param a: Start value for the range (inclusive) + :param b: End value for the range (inclusive) + """ + ... diff --git a/lang/ca/typeshed/stdlib/speech.pyi b/lang/ca/typeshed/stdlib/speech.pyi index 2e29ea3..349d188 100644 --- a/lang/ca/typeshed/stdlib/speech.pyi +++ b/lang/ca/typeshed/stdlib/speech.pyi @@ -1,79 +1,106 @@ -"""Fes que la micro:bit parli, canti i fer altres expressions com els sons.""" +"""Make the micro:bit talk, sing and make other speech like sounds. +""" + from typing import Optional from .microbit import MicroBitDigitalPin, pin0 def translate(words: str) -> str: - """Tradueix paraules angleses a fonemes. (tradueix) + """Translate English words to phonemes. -Example: ``speech.translate('hello world')`` + Example: ``speech.translate('hello world')`` -:param words: (paraules) Una cadena de paraules angleses. -:return: A string containing a best guess at the appropriate phonemes to pronounce. -The output is generated from this `text to phoneme translation table `_. + :param words: A string of English words. + :return: A string containing a best guess at the appropriate phonemes to pronounce. + The output is generated from this `text to phoneme translation table `_. -This function should be used to generate a first approximation of phonemes -that can be further hand-edited to improve accuracy, inflection and -emphasis. + This function should be used to generate a first approximation of phonemes + that can be further hand-edited to improve accuracy, inflection and + emphasis. -See `the online documentation `_ for detailed information.""" + See `the online documentation `_ for detailed information. + """ ... -def pronounce(phonemes: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: Optional[MicroBitDigitalPin]=pin0) -> None: - """Pronuncia fonemes. (pronuncia) - -Example: ``speech.pronounce(' /HEHLOW WERLD')`` - -:param phonemes: (fonemes) La cadena de fonemes a pronunciar -:param pitch: (to) Un nombre que representa la freqüència de la veu -:param speed: (velocitat) Un nombre que representa la velocitat de la veu -:param mouth: (boca) Un nombre que representa la boca de la veu -:param throat: Un nombre que representa la gola de la veu -:param pin: L'argument opcional per especificar el pin de sortida es pot utilitzar per anul·lar el valor predeterminat de ``pin0``. -Si no vols que es reprodueixi cap so en els pins, podts utilitzar ``pin=None``. Només micro:bit V2. - -Override the optional pitch, speed, mouth and throat settings to change the -timbre (quality) of the voice. - -See `the online documentation `_ for detailed information.""" +def pronounce( + phonemes: str, + pitch: int = 64, + speed: int = 72, + mouth: int = 128, + throat: int = 128, + pin: Optional[MicroBitDigitalPin] = pin0, +) -> None: + """Pronounce phonemes. + + Example: ``speech.pronounce(' /HEHLOW WERLD')`` + + :param phonemes: The string of phonemes to pronounce + :param pitch: A number representing the pitch of the voice + :param speed: A number representing the speed of the voice + :param mouth: A number representing the mouth of the voice + :param throat: A number representing the throat of the voice + :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. + If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. + + Override the optional pitch, speed, mouth and throat settings to change the + timbre (quality) of the voice. + + See `the online documentation `_ for detailed information. + """ ... -def say(words: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: MicroBitDigitalPin=pin0) -> None: - """Digues paraules en anglès. - -Example: ``speech.say('hello world')`` - -:param words: (paraules) La cadena de paraules a dir. -:param pitch: (to) Un nombre que representa la freqüència de la veu -:param speed: (velocitat) Un nombre que representa la velocitat de la veu -:param mouth: (boca) Un nombre que representa la boca de la veu -:param throat: Un nombre que representa la gola de la veu -:param pin: L'argument opcional per especificar el pin de sortida es pot utilitzar per anul·lar el valor predeterminat del ``pin0``. -Si no vols que es reprodueixi cap so en els pins, pots utilitzar ``pin=None``. Només micro:bit V2. - -The result is semi-accurate for English. Override the optional pitch, speed, -mouth and throat settings to change the timbre (quality) of the voice. - -This is a short-hand equivalent of: -``speech.pronounce(speech.translate(words))`` - -See `the online documentation `_ for detailed information.""" +def say( + words: str, + pitch: int = 64, + speed: int = 72, + mouth: int = 128, + throat: int = 128, + pin: MicroBitDigitalPin = pin0, +) -> None: + """Say English words. + + Example: ``speech.say('hello world')`` + + :param words: The string of words to say. + :param pitch: A number representing the pitch of the voice + :param speed: A number representing the speed of the voice + :param mouth: A number representing the mouth of the voice + :param throat: A number representing the throat of the voice + :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. + If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. + + The result is semi-accurate for English. Override the optional pitch, speed, + mouth and throat settings to change the timbre (quality) of the voice. + + This is a short-hand equivalent of: + ``speech.pronounce(speech.translate(words))`` + + See `the online documentation `_ for detailed information. + """ ... -def sing(phonemes: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: MicroBitDigitalPin=pin0) -> None: - """Cantar fonemes. - -Example: ``speech.sing(' /HEHLOW WERLD')`` - -:param phonemes: (fonemes) La cadena de paraules a cantar. -:param pitch: (to) Un nombre que representa la freqüència de la veu -:param speed: (velocitat) Un nombre que representa la velocitat de la veu -:param mouth: (boca) Un nombre que representa la boca de la veu -:param throat: Un nombre que representa la gola de la veu -:param pin: L'argument opcional per especificar el pin de sortida es pot utilitzar per anul·lar el valor predeterminat de ``pin0``. -Si no vols que es reprodueixi cap so en els pins, podts utilitzar ``pin=None``. Només micro:bit V2. - -Override the optional pitch, speed, mouth and throat settings to change -the timbre (quality) of the voice. - -See `the online documentation `_ for detailed information.""" - ... \ No newline at end of file +def sing( + phonemes: str, + pitch: int = 64, + speed: int = 72, + mouth: int = 128, + throat: int = 128, + pin: MicroBitDigitalPin = pin0, +) -> None: + """Sing phonemes. + + Example: ``speech.sing(' /HEHLOW WERLD')`` + + :param phonemes: The string of words to sing. + :param pitch: A number representing the pitch of the voice + :param speed: A number representing the speed of the voice + :param mouth: A number representing the mouth of the voice + :param throat: A number representing the throat of the voice + :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. + If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. + + Override the optional pitch, speed, mouth and throat settings to change + the timbre (quality) of the voice. + + See `the online documentation `_ for detailed information. + """ + ... diff --git a/lang/ca/typeshed/stdlib/struct.pyi b/lang/ca/typeshed/stdlib/struct.pyi index 75c7eee..53b3e0b 100644 --- a/lang/ca/typeshed/stdlib/struct.pyi +++ b/lang/ca/typeshed/stdlib/struct.pyi @@ -1,56 +1,65 @@ -"""Empaquetar i desempaquetar tipus de dades primitius.""" +"""Pack and unpack primitive data types. +""" + from _typeshed import ReadableBuffer, WriteableBuffer from typing import Any, Tuple, Union def calcsize(fmt: str) -> int: - """Obté el nombre de bytes necessaris per emmagatzemar el ``fmt`` donat. + """Get the number of bytes needed to store the given ``fmt``. -Example: ``struct.calcsize('hf')`` + Example: ``struct.calcsize('hf')`` -:param fmt: Una cadena de format. -:return The number of bytes needed to store such a value.""" + :param fmt: A format string. + :return The number of bytes needed to store such a value. + """ ... def pack(fmt: str, v1: Any, *vn: Any) -> bytes: - """Empaqueta els valors segons una cadena de format. + """Pack values according to a format string. -Example: ``struct.pack('hf', 1, 3.1415)`` + Example: ``struct.pack('hf', 1, 3.1415)`` -:param fmt: La cadena de format. -:param v1: El primer valor. -:param *vn: La resta de valors. -:return A bytes object encoding the values.""" + :param fmt: The format string. + :param v1: The first value. + :param *vn: The remaining values. + :return A bytes object encoding the values. + """ ... -def pack_into(fmt: str, buffer: WriteableBuffer, offset: int, v1: Any, *vn: Any) -> None: - """Empaqueta els valors segons una cadena de format. +def pack_into( + fmt: str, buffer: WriteableBuffer, offset: int, v1: Any, *vn: Any +) -> None: + """Pack values according to a format string. -Example: ``struct.pack_info('hf', buffer, 1, 3.1415)`` + Example: ``struct.pack_info('hf', buffer, 1, 3.1415)`` -:param fmt: La cadena de format. -:param buffer: (memòria intermèdia) La memòria intermèdia de destinació on escriure. -:param offset: El desplaçament a la memòria intermèdia. Pot ser negatiu per comptar des del final de la memòria intermèdia. -:param v1: El primer valor. -:param *vn: La resta de valors.""" + :param fmt: The format string. + :param buffer: The target buffer to write into. + :param offset: The offset into the buffer. May be negative to count from the end of the buffer. + :param v1: The first value. + :param *vn: The remaining values. + """ ... def unpack(fmt: str, data: ReadableBuffer) -> Tuple[Any, ...]: - """Desempaqueta les dades segons una cadena de format. + """Unpack data according to a format string. -Example: ``v1, v2 = struct.unpack('hf', buffer)`` + Example: ``v1, v2 = struct.unpack('hf', buffer)`` -:param fmt: La cadena de format. -:param data: Les dades. -:return: A tuple of the unpacked values.""" + :param fmt: The format string. + :param data: The data. + :return: A tuple of the unpacked values. + """ ... -def unpack_from(fmt: str, buffer: ReadableBuffer, offset: int=0) -> Tuple: - """Desempaqueta les dades d'una memòria intermèdia segons una cadena de format. (desempaqueta des de) +def unpack_from(fmt: str, buffer: ReadableBuffer, offset: int = 0) -> Tuple: + """Unpack data from a buffer according to a format string. -Example: ``v1, v2 = struct.unpack_from('hf', buffer)`` + Example: ``v1, v2 = struct.unpack_from('hf', buffer)`` -:param fmt: La cadena de format. -:param buffer: (memòria intermèdia) La memòria intermèdia d'origen d'on llegir. -:param offset: El desplaçament a la memòria intermèdia. Pot ser negatiu per comptar des del final de la memòria intermèdia. -:return: A tuple of the unpacked values.""" - ... \ No newline at end of file + :param fmt: The format string. + :param buffer: The source buffer to read from. + :param offset: The offset into the buffer. May be negative to count from the end of the buffer. + :return: A tuple of the unpacked values. + """ + ... diff --git a/lang/ca/typeshed/stdlib/sys.pyi b/lang/ca/typeshed/stdlib/sys.pyi index aea4bac..320bac9 100644 --- a/lang/ca/typeshed/stdlib/sys.pyi +++ b/lang/ca/typeshed/stdlib/sys.pyi @@ -1,36 +1,43 @@ -"""Funcions específiques del sistema""" +"""System specific functions""" + from typing import Any, Dict, List, NoReturn, TextIO, Tuple -def exit(retval: object=...) -> NoReturn: - """Finalitza el programa actual amb un codi de sortida determinat. +def exit(retval: object = ...) -> NoReturn: + """Terminate current program with a given exit code. -Example: ``sys.exit(1)`` + Example: ``sys.exit(1)`` -This function raises a ``SystemExit`` exception. If an argument is given, its -value given as an argument to ``SystemExit``. + This function raises a ``SystemExit`` exception. If an argument is given, its + value given as an argument to ``SystemExit``. -:param retval: El codi o missatge de sortida.""" + :param retval: The exit code or message. + """ ... def print_exception(exc: Exception) -> None: - """Imprimeix una excepció amb un rastreig. + """ + Print an exception with a traceback. + + Example: ``sys.print_exception(e)`` -Example: ``sys.print_exception(e)`` + :param exc: The exception to print -:param exc: L'excepció a imprimir + This is simplified version of a function which appears in the + ``traceback`` module in CPython. + """ -This is simplified version of a function which appears in the -``traceback`` module in CPython.""" argv: List[str] -"""Una llista mutable d'arguments amb què s'ha iniciat el programa actual.""" +"""A mutable list of arguments the current program was started with.""" + byteorder: str -"""L'ordre dels bytes del sistema (``"little"`` o ``"big"``).""" +"""The byte order of the system (``"little"`` or ``"big"``).""" class _implementation: name: str version: Tuple[int, int, int] + implementation: _implementation -"""Objecte amb informació sobre la implementació actual de Python. (implementació) +"""Object with information about the current Python implementation. For MicroPython, it has following attributes: @@ -44,12 +51,13 @@ minimal ports). CPython mandates more attributes for this object, but the actual useful bare minimum is implemented in MicroPython. """ + maxsize: int """ -Valor màxim que pot tenir un tipus d'enter natiu a la plataforma actual, -o valor màxim representable pel tipus d'enter MicroPython, si és més petit -que el valor màxim de la plataforma (és el cas dels ports MicroPython sense -suport d'enter llarg - long int support). +Maximum value which a native integer type can hold on the current platform, +or maximum value representable by MicroPython integer type, if it's smaller +than platform max value (that is the case for MicroPython ports without +long int support). This attribute is useful for detecting "bitness" of a platform (32-bit vs 64-bit, etc.). It's recommended to not compare this attribute to some @@ -69,14 +77,17 @@ value directly, but instead count number of bits in it:: # (e.g. 31) due to peculiarities described above, so use "> 16", # "> 32", "> 64" style of comparisons. """ + modules: Dict[str, Any] -"""Diccionari de mòduls carregats. (mòduls) +"""Dictionary of loaded modules. On some ports, it may not include builtin modules.""" + path: List[str] -"""Una llista mutable de directoris per cercar mòduls importats.""" +"""A mutable list of directories to search for imported modules.""" + platform: str -"""La plataforma en què s'executa MicroPython. (plataforma) +"""The platform that MicroPython is running on. For OS/RTOS ports, this is usually an identifier of the OS, e.g. ``"linux"``. For baremetal ports it is an identifier of a board, e.g. ``"pyboard"`` for @@ -86,11 +97,13 @@ distinguish one board from another. If you need to check whether your program runs on MicroPython (vs other Python implementation), use ``sys.implementation`` instead. """ + version: str -"""Versió del llenguatge Python a la qual s'ajusta aquesta implementació, com a cadena. (versió)""" +"""Python language version that this implementation conforms to, as a string.""" + version_info: Tuple[int, int, int] -"""Versió del llenguatge Python a la qual s'ajusta aquesta implementació, com una tupla d'enters. (informació de la versió) +"""Python language version that this implementation conforms to, as a tuple of ints. Only the first three version numbers (major, minor, micro) are supported and they can be referenced only by index, not by name. -""" \ No newline at end of file +""" diff --git a/lang/ca/typeshed/stdlib/time.pyi b/lang/ca/typeshed/stdlib/time.pyi index c1e151f..598c483 100644 --- a/lang/ca/typeshed/stdlib/time.pyi +++ b/lang/ca/typeshed/stdlib/time.pyi @@ -1,116 +1,132 @@ -"""Mesura el temps i afegeix retards als programes. (temps)""" +"""Measure time and add delays to programs. +""" + from typing import Union def sleep(seconds: Union[int, float]) -> None: - """Retarda uns segons. (dormir) + """ + Delay a number of seconds. -Example: ``time.sleep(1)`` + Example: ``time.sleep(1)`` -:param seconds: (segons) El nombre de segons per posar en pausa. -Utilitza un nombre de coma flotant per posar en pausa durant una fracció de segons.""" + :param seconds: The number of seconds to sleep for. + Use a floating-point number to sleep for a fractional number of seconds. + """ ... def sleep_ms(ms: int) -> None: - """Retard per a un nombre determinat de mil·lisegons. (retard en mil·lisegons) + """ + Delay for given number of milliseconds. -Example: ``time.sleep_ms(1_000_000)`` + Example: ``time.sleep_ms(1_000_000)`` -:param ms: El nombre de mil·lisegons de retard (>= 0).""" + :param ms: The number of milliseconds delay (>= 0). + """ ... def sleep_us(us: int) -> None: - """Retard per a un nombre determinat de microsegons. + """ + Delay for given number of microseconds. -Example: ``time.sleep_us(1000)`` + Example: ``time.sleep_us(1000)`` -:param us: El nombre de microsegons de retard (>= 0).""" + :param us: The number of microseconds delay (>= 0). + """ ... def ticks_ms() -> int: - """Obté un comptador creixent de mil·lisegons amb un punt de referència arbitrari, -que es desborda després d'algun valor. (tics mil·lisegons) + """ + Get an increasing, millisecond counter with an arbitrary reference point, + that wraps around after some value. -Example: ``time.ticks_ms()`` + Example: ``time.ticks_ms()`` -:return: The counter value in milliseconds.""" + :return: The counter value in milliseconds. + """ ... def ticks_us() -> int: - """Obté un comptador creixent de microsegons amb un punt de referència arbitrari, -que es desborda després d'algun valor. (tics microsegons) + """ + Get an increasing, microsecond counter with an arbitrary reference point, + that wraps around after some value. -Example: ``time.ticks_us()`` + Example: ``time.ticks_us()`` -:return: The counter value in microseconds.""" + :return: The counter value in microseconds. + """ ... def ticks_add(ticks: int, delta: int) -> int: - """Afegeix al valor de tics un desplaçament determinat, que pot ser positiu o -negatiu. (tics compensa) + """ + Offset ticks value by a given number, which can be either positive or + negative. -Example: ``time.ticks_add(time.ticks_ms(), 200)`` + Example: ``time.ticks_add(time.ticks_ms(), 200)`` -Given a ticks value, this function allows to calculate ticks -value delta ticks before or after it, following modular-arithmetic -definition of tick values. + Given a ticks value, this function allows to calculate ticks + value delta ticks before or after it, following modular-arithmetic + definition of tick values. -:param ticks: Un valor de tics -:param delta: Un desplaçament enter + :param ticks: A ticks value + :param delta: An integer offset -Example:: + Example:: - # Find out what ticks value there was 100ms ago - print(ticks_add(time.ticks_ms(), -100)) + # Find out what ticks value there was 100ms ago + print(ticks_add(time.ticks_ms(), -100)) - # Calculate deadline for operation and test for it - deadline = ticks_add(time.ticks_ms(), 200) - while ticks_diff(deadline, time.ticks_ms()) > 0: - do_a_little_of_something() + # Calculate deadline for operation and test for it + deadline = ticks_add(time.ticks_ms(), 200) + while ticks_diff(deadline, time.ticks_ms()) > 0: + do_a_little_of_something() - # Find out TICKS_MAX used by this port - print(ticks_add(0, -1))""" + # Find out TICKS_MAX used by this port + print(ticks_add(0, -1)) + """ ... def ticks_diff(ticks1: int, ticks2: int) -> int: - """Mesura la diferència dels tics entre els valors retornats -``time.ticks_ms()`` o ``ticks_us()``, com a valor amb signe -que pot desbordar-se. - -Example: ``time.ticks_diff(scheduled_time, now)`` - -:param ticks1: El valor a restar de -:param ticks2: El valor a restar - -The argument order is the same as for subtraction operator, -``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. - -``ticks_diff()`` is designed to accommodate various usage -patterns, among them: - -Polling with timeout. In this case, the order of events is known, and you -will deal only with positive results of :func:`time.ticks_diff()`:: - - # Wait for GPIO pin to be asserted, but at most 500us - start = time.ticks_us() - while pin.value() == 0: - if time.ticks_diff(time.ticks_us(), start) > 500: - raise TimeoutError - - -Scheduling events. In this case, :func:`time.ticks_diff()` result may be -negative if an event is overdue:: - - # This code snippet is not optimized - now = time.ticks_ms() - scheduled_time = task.scheduled_time() - if ticks_diff(scheduled_time, now) > 0: - print("Too early, let's nap") - sleep_ms(ticks_diff(scheduled_time, now)) - task.run() - elif ticks_diff(scheduled_time, now) == 0: - print("Right at time!") - task.run() - elif ticks_diff(scheduled_time, now) < 0: - print("Oops, running late, tell task to run faster!") - task.run(run_faster=True)""" - ... \ No newline at end of file + """ + Measure ticks difference between values returned from + ``time.ticks_ms()`` or ``ticks_us()``, as a signed value + which may wrap around. + + Example: ``time.ticks_diff(scheduled_time, now)`` + + :param ticks1: The value to subtract from + :param ticks2: The value to subtract + + The argument order is the same as for subtraction operator, + ``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. + + ``ticks_diff()`` is designed to accommodate various usage + patterns, among them: + + Polling with timeout. In this case, the order of events is known, and you + will deal only with positive results of :func:`time.ticks_diff()`:: + + # Wait for GPIO pin to be asserted, but at most 500us + start = time.ticks_us() + while pin.value() == 0: + if time.ticks_diff(time.ticks_us(), start) > 500: + raise TimeoutError + + + Scheduling events. In this case, :func:`time.ticks_diff()` result may be + negative if an event is overdue:: + + # This code snippet is not optimized + now = time.ticks_ms() + scheduled_time = task.scheduled_time() + if ticks_diff(scheduled_time, now) > 0: + print("Too early, let's nap") + sleep_ms(ticks_diff(scheduled_time, now)) + task.run() + elif ticks_diff(scheduled_time, now) == 0: + print("Right at time!") + task.run() + elif ticks_diff(scheduled_time, now) < 0: + print("Oops, running late, tell task to run faster!") + task.run(run_faster=True) + """ + ... diff --git a/lang/de/typeshed/stdlib/gc.pyi b/lang/de/typeshed/stdlib/gc.pyi index 0d8aee5..1370abf 100644 --- a/lang/de/typeshed/stdlib/gc.pyi +++ b/lang/de/typeshed/stdlib/gc.pyi @@ -1,68 +1,73 @@ -"""Steuerung des Garbage Collectors""" +"""Control the garbage collector""" + from typing import overload def enable() -> None: - """Automatische Garbage Collection aktivieren.""" + """Enable automatic garbage collection.""" ... def disable() -> None: - """Automatische Garbage Collection deaktivieren. + """Disable automatic garbage collection. -Heap memory can still be allocated, -and garbage collection can still be initiated manually using ``gc.collect``.""" + Heap memory can still be allocated, + and garbage collection can still be initiated manually using ``gc.collect``.""" def collect() -> None: - """Garbage Collection ausführen.""" + """Run a garbage collection.""" ... def mem_alloc() -> int: - """Ermittelt die Anzahl der dem Heap-Speicher zugewiesen Bytes. + """Get the number of bytes of heap RAM that are allocated. -:return: The number of bytes allocated. + :return: The number of bytes allocated. -This function is MicroPython extension.""" + This function is MicroPython extension. + """ ... def mem_free() -> int: - """Gibt die Anzahl der Bytes des verfügbaren dynamischen Speichers zurück. -1 wird zurückgegeben, wenn dieser Wert unbekannt ist. + """Get the number of bytes of available heap RAM, or -1 if this amount is not known. -:return: The number of bytes free. + :return: The number of bytes free. -This function is MicroPython extension.""" + This function is MicroPython extension. + """ ... @overload def threshold() -> int: - """Den zusätzlichen GC-Zuteilungsschwellwert abfragen. + """Query the additional GC allocation threshold. -:return: The GC allocation threshold. + :return: The GC allocation threshold. -This function is a MicroPython extension. CPython has a similar -function - ``set_threshold()``, but due to different GC -implementations, its signature and semantics are different.""" + This function is a MicroPython extension. CPython has a similar + function - ``set_threshold()``, but due to different GC + implementations, its signature and semantics are different. + """ ... @overload def threshold(amount: int) -> None: - """Den zusätzlichen GC-Schwellenwert festlegen. - -Normally, a collection is triggered only when a new allocation -cannot be satisfied, i.e. on an out-of-memory (OOM) condition. -If this function is called, in addition to OOM, a collection -will be triggered each time after ``amount`` bytes have been -allocated (in total, since the previous time such an amount of bytes -have been allocated). ``amount`` is usually specified as less than the -full heap size, with the intention to trigger a collection earlier than when the -heap becomes exhausted, and in the hope that an early collection will prevent -excessive memory fragmentation. This is a heuristic measure, the effect -of which will vary from application to application, as well as -the optimal value of the ``amount`` parameter. - -A value of -1 means a disabled allocation threshold. - -This function is a MicroPython extension. CPython has a similar -function - ``set_threshold()``, but due to different GC -implementations, its signature and semantics are different. - -:param amount: Die Anzahl der Bytes, nach denen eine Garbage Collection ausgelöst werden soll.""" - ... \ No newline at end of file + """Set the additional GC allocation threshold. + + Normally, a collection is triggered only when a new allocation + cannot be satisfied, i.e. on an out-of-memory (OOM) condition. + If this function is called, in addition to OOM, a collection + will be triggered each time after ``amount`` bytes have been + allocated (in total, since the previous time such an amount of bytes + have been allocated). ``amount`` is usually specified as less than the + full heap size, with the intention to trigger a collection earlier than when the + heap becomes exhausted, and in the hope that an early collection will prevent + excessive memory fragmentation. This is a heuristic measure, the effect + of which will vary from application to application, as well as + the optimal value of the ``amount`` parameter. + + A value of -1 means a disabled allocation threshold. + + This function is a MicroPython extension. CPython has a similar + function - ``set_threshold()``, but due to different GC + implementations, its signature and semantics are different. + + :param amount: The number of bytes after which a garbage collection should be triggered. + """ + ... diff --git a/lang/de/typeshed/stdlib/log.pyi b/lang/de/typeshed/stdlib/log.pyi index 4ba6cce..c9870fa 100644 --- a/lang/de/typeshed/stdlib/log.pyi +++ b/lang/de/typeshed/stdlib/log.pyi @@ -1,89 +1,104 @@ -"""Zeichne Daten auf deinem micro:bit V2 auf.""" +"""Log data to your micro:bit V2.""" + from typing import Literal, Mapping, Optional, Union, overload + MILLISECONDS = 1 -"""Millisekunden Zeitstempelformat. (millisekunden)""" +"""Milliseconds timestamp format.""" + SECONDS = 10 -"""Sekunden Zeitstempelformat. (sekunden)""" +"""Seconds timestamp format.""" + MINUTES = 600 -"""Minuten Zeitstempelformat. (minuten)""" +"""Minutes timestamp format.""" + HOURS = 36000 -"""Stunden Zeitstempelformat. (stunden)""" +"""Hours timestamp format.""" + DAYS = 864000 -"""Tage Zeitstempelformat.""" +"""Days timestamp format.""" -def set_labels(*labels: str, timestamp: Optional[Literal[1, 10, 36000, 864000]]=SECONDS) -> None: - """Den Logdatei-Header setzen (Beschriftungen festlegen) +def set_labels( + *labels: str, timestamp: Optional[Literal[1, 10, 36000, 864000]] = SECONDS +) -> None: + """Set up the log file header. -Example: ``log.set_labels('X', 'Y', 'Z', timestamp=log.MINUTES)`` + Example: ``log.set_labels('X', 'Y', 'Z', timestamp=log.MINUTES)`` -Ideally this function should be called a single time, before any data is -logged, to configure the data table header once. + Ideally this function should be called a single time, before any data is + logged, to configure the data table header once. -If a log file already exists when the program starts, or if this function -is called multiple times, it will check the labels already defined in the -log file. If this function call contains any new labels not already -present, it will generate a new header row with the additional columns. + If a log file already exists when the program starts, or if this function + is called multiple times, it will check the labels already defined in the + log file. If this function call contains any new labels not already + present, it will generate a new header row with the additional columns. -By default the first column contains a timestamp for each row. The time -unit can be selected via the timestamp argument. + By default the first column contains a timestamp for each row. The time + unit can be selected via the timestamp argument. -:param *labels: Eine beliebige Anzahl von Positionsargumenten, die jeweils einem Eintrag in der Kopfzeile des Logs entsprechen. -:param timestamp: Wähle die Zeitstempel-Einheit, die automatisch als erste Spalte in jeder Zeile hinzugefügt wird. Der Zeitstempel kann einen der folgenden Werte annehmen: ``log.MILLISECONDS``, ``log.SECONDS``, ``log.MINUTES``, ``log.HOURS``, ``log.DAYS`` oder ``None``, um den Zeitstempel zu deaktivieren. Der Standardwert ist ``log.SECONDS``.""" + :param *labels: Any number of positional arguments, each corresponding to an entry in the log header. + :param timestamp: Select the timestamp unit that will be automatically added as the first column in every row. Timestamp values can be one of ``log.MILLISECONDS``, ``log.SECONDS``, ``log.MINUTES``, ``log.HOURS``, ``log.DAYS`` or ``None`` to disable the timestamp. The default value is ``log.SECONDS``. + """ ... @overload -def add(data_dictionary: Optional[Mapping[str, Union[str, int, float]]]) -> None: - """Füge dem Protokoll eine Datenzeile hinzu, indem du ein Dictionary mit Kopfzeileneinträgen und Werten übergibst. (hinzufügen) +def add( + data_dictionary: Optional[Mapping[str, Union[str, int, float]]], +) -> None: + """Add a data row to the log by passing a dictionary of headers and values. -Example: ``log.add({ 'temp': temperature() })`` + Example: ``log.add({ 'temp': temperature() })`` -Each call to this function adds a row to the log. + Each call to this function adds a row to the log. -New labels not previously specified via the set_labels function, or by a -previous call to this function, will trigger a new header entry to be added -to the log with the extra labels. + New labels not previously specified via the set_labels function, or by a + previous call to this function, will trigger a new header entry to be added + to the log with the extra labels. -Labels previously specified and not present in a call to this function will -be skipped with an empty value in the log row. + Labels previously specified and not present in a call to this function will + be skipped with an empty value in the log row. -:param data_dictionary: (daten wörterbuch) Die zu protokollierenden Daten in Form eines Dictionarys mit einem Schlüssel für jeden Kopfzeileneintrag.""" + :param data_dictionary: The data to log as a dictionary with a key for each header. + """ ... @overload def add(**kwargs: Union[str, int, float]) -> None: - """Füge dem Protokoll eine Datenzeile mit Schlüsselwörtern als Argumenten hinzu. (hinzufügen) + """Add a data row to the log using keyword arguments. -Example: ``log.add(temp=temperature())`` + Example: ``log.add(temp=temperature())`` -Each call to this function adds a row to the log. + Each call to this function adds a row to the log. -New labels not previously specified via the set_labels function, or by a -previous call to this function, will trigger a new header entry to be added -to the log with the extra labels. + New labels not previously specified via the set_labels function, or by a + previous call to this function, will trigger a new header entry to be added + to the log with the extra labels. -Labels previously specified and not present in a call to this function will -be skipped with an empty value in the log row.""" + Labels previously specified and not present in a call to this function will + be skipped with an empty value in the log row. + """ ... def delete(full=False): - """Löscht den Inhalt des Protokolls, einschließlich der Kopfzeilen. (löschen) + """Deletes the contents of the log, including headers. -Example: ``log.delete()`` + Example: ``log.delete()`` -To add the log headers again the ``set_labels`` function should to be called after this function. + To add the log headers again the ``set_labels`` function should to be called after this function. -There are two erase modes; “full” completely removes the data from the physical storage, -and “fast” invalidates the data without removing it. + There are two erase modes; “full” completely removes the data from the physical storage, + and “fast” invalidates the data without removing it. -:param full: (vollständig) Mit ``True`` wird ein " vollständiges" Löschen und mit ``False`` die "schnelle" Löschmethode gewählt.""" + :param full: ``True`` selects a “full” erase and ``False`` selects the “fast” erase method. + """ ... def set_mirroring(serial: bool): - """Richte die Spiegelung der Datenprotokollierung auf dem seriellen Ausgang ein. (spiegeln) + """Configure mirroring of the data logging activity to the serial output. -Example: ``log.set_mirroring(True)`` + Example: ``log.set_mirroring(True)`` -Serial mirroring is disabled by default. When enabled, it will print to serial each row logged into the log file. + Serial mirroring is disabled by default. When enabled, it will print to serial each row logged into the log file. -:param serial: (seriell) ``True`` aktiviert die Spiegelung von Daten auf dem seriellen Ausgang.""" - ... \ No newline at end of file + :param serial: ``True`` enables mirroring data to the serial output. + """ + ... diff --git a/lang/de/typeshed/stdlib/machine.pyi b/lang/de/typeshed/stdlib/machine.pyi index eda1989..2e82f5b 100644 --- a/lang/de/typeshed/stdlib/machine.pyi +++ b/lang/de/typeshed/stdlib/machine.pyi @@ -1,84 +1,97 @@ -"""Low-Level-Utilities. (maschine)""" +"""Low-level utilities. +""" from typing import Any from .microbit import MicroBitDigitalPin def unique_id() -> bytes: - """Liefert eine Byte-Zeichenkette mit einem eindeutigen Bezeichner für ein Board. (Eindeutige ID) + """Get a byte string with a unique identifier of a board. -Example: ``machine.unique_id()`` + Example: ``machine.unique_id()`` -:return: An identifier that varies from one board instance to another.""" + :return: An identifier that varies from one board instance to another. + """ ... def reset() -> None: - """Setzt das Gerät zurück, als würde man die externe RESET-Taste drückt. (zurücksetzen) + """Reset the device in a manner similar to pushing the external RESET button. -Example: ``machine.reset()``""" + Example: ``machine.reset()`` + """ ... def freq() -> int: - """Ermittelt die Taktfrequenz der CPU in Hertz. + """Get the CPU frequency in hertz. -Example: ``machine.freq()`` + Example: ``machine.freq()`` -:return: The CPU frequency.""" + :return: The CPU frequency. + """ ... def disable_irq() -> Any: - """Deaktiviere Interrupt-Anforderungen. (IRQ deaktivieren) + """Disable interrupt requests. -Example: ``interrupt_state = machine.disable_irq()`` + Example: ``interrupt_state = machine.disable_irq()`` -:return: the previous IRQ state which should be considered an opaque value + :return: the previous IRQ state which should be considered an opaque value -The return value should be passed to the ``enable_irq`` function to restore -interrupts to their original state.""" + The return value should be passed to the ``enable_irq`` function to restore + interrupts to their original state. + """ ... def enable_irq(state: Any) -> None: - """Interrupt-Anfragen wieder aktivieren. (IRQ aktivieren) + """Re-enable interrupt requests. -Example: ``machine.enable_irq(interrupt_state)`` + Example: ``machine.enable_irq(interrupt_state)`` -:param state: Der Wert, der beim letzten Aufruf der Funktion ``disable_irq`` zurückgegeben wurde.""" + :param state: The value that was returned from the most recent call to the ``disable_irq`` function. + """ ... -def time_pulse_us(pin: MicroBitDigitalPin, pulse_level: int, timeout_us: int=1000000) -> int: - """Gibt die Dauer eines Impulses an einem Pin zurück. (zeitimpuls us) +def time_pulse_us( + pin: MicroBitDigitalPin, pulse_level: int, timeout_us: int = 1000000 +) -> int: + """Time a pulse on a pin. -Example: ``time_pulse_us(pin0, 1)`` + Example: ``time_pulse_us(pin0, 1)`` -If the current input value of the pin is different to ``pulse_level``, the -function first waits until the pin input becomes equal to -``pulse_level``, then times the duration that the pin is equal to -``pulse_level``. If the pin is already equal to ``pulse_level`` then timing -starts straight away. + If the current input value of the pin is different to ``pulse_level``, the + function first waits until the pin input becomes equal to + ``pulse_level``, then times the duration that the pin is equal to + ``pulse_level``. If the pin is already equal to ``pulse_level`` then timing + starts straight away. -:param pin: Der zu verwendende Pin -:param pulse_level: (pulsstufe) 0, um einen Low-Impuls oder 1, um einen High-Impuls zu messen -:param timeout_us: Eine Verzögerung in Mikrosekunden -:return: The duration of the pulse in microseconds, or -1 for a timeout waiting for the level to match ``pulse_level``, or -2 on timeout waiting for the pulse to end""" + :param pin: The pin to use + :param pulse_level: 0 to time a low pulse or 1 to time a high pulse + :param timeout_us: A microsecond timeout + :return: The duration of the pulse in microseconds, or -1 for a timeout waiting for the level to match ``pulse_level``, or -2 on timeout waiting for the pulse to end + """ ... class mem: - """Die Klasse für die ``mem8``, ``mem16`` und ``mem32`` Speicheranzeigen.""" + """The class for the ``mem8``, ``mem16`` and ``mem32`` memory views.""" def __getitem__(self, address: int) -> int: - """Greife auf einen Wert im Speicher zu. + """Access a value from memory. -:param address: (adresse) Die Speicheradresse. -:return: The value at that address as an integer.""" + :param address: The memory address. + :return: The value at that address as an integer. + """ ... - def __setitem__(self, address: int, value: int) -> None: - """Setzt einen Wert an der angegebenen Adresse. + """Set a value at the given address. -:param address: (adresse) Die Speicheradresse. -:param value: (wert) Der zu setzende Integer-Wert.""" + :param address: The memory address. + :param value: The integer value to set. + """ ... + mem8: mem -"""8-Bit (Byte) Ansicht des Speichers.""" +"""8-bit (byte) view of memory.""" + mem16: mem -"""16-Bit (Byte) Ansicht des Speichers.""" +"""16-bit view of memory.""" + mem32: mem -"""32-Bit (Byte) Ansicht des Speichers.""" \ No newline at end of file +"""32-bit view of memory.""" diff --git a/lang/de/typeshed/stdlib/math.pyi b/lang/de/typeshed/stdlib/math.pyi index c81f9d0..f82d4de 100644 --- a/lang/de/typeshed/stdlib/math.pyi +++ b/lang/de/typeshed/stdlib/math.pyi @@ -1,246 +1,273 @@ -"""Mathematische Funktionen.""" +"""Mathematical functions. +""" + from typing import Tuple def acos(x: float) -> float: - """Berechnet den Arkuskosinus. + """Calculate the inverse cosine. -Example: ``math.acos(1)`` + Example: ``math.acos(1)`` -:param x: Eine Zahl -:return: The inverse cosine of ``x``""" + :param x: A number + :return: The inverse cosine of ``x`` + """ ... def asin(x: float) -> float: - """Berechnet den Arkussinus. + """Calculate the inverse sine. -Example: ``math.asin(0)`` + Example: ``math.asin(0)`` -:param x: Eine Zahl -:return: The inverse sine of ``x``""" + :param x: A number + :return: The inverse sine of ``x`` + """ ... def atan(x: float) -> float: - """Berechnet den Arkustangens. + """Calculate the inverse tangent. -Example: ``math.atan(0)`` + Example: ``math.atan(0)`` -:param x: Eine Zahl -:return: The inverse tangent of ``x``""" + :param x: A number + :return: The inverse tangent of ``x`` + """ ... def atan2(y: float, x: float) -> float: - """Berechnet den Hauptwert des Arkustangens von ``y/x``. + """Calculate the principal value of the inverse tangent of ``y/x``. -Example: ``math.atan2(0, -1)`` + Example: ``math.atan2(0, -1)`` -:param y: Eine Zahl -:param x: Eine Zahl -:return: The principal value of the inverse tangent of ``y/x``""" + :param y: A number + :param x: A number + :return: The principal value of the inverse tangent of ``y/x`` + """ ... def ceil(x: float) -> float: - """Rundet eine Zahl in Richtung positiver Unendlichkeit. + """Round a number towards positive infinity. -Example: ``math.ceil(0.1)`` + Example: ``math.ceil(0.1)`` -:param x: Eine Zahl -:return: ``x`` rounded towards positive infinity.""" + :param x: A number + :return: ``x`` rounded towards positive infinity. + """ ... def copysign(x: float, y: float) -> float: - """Berechne ``x`` mit dem Vorzeichen von ``y``. + """Calculate ``x`` with the sign of ``y``. -Example: ``math.copysign(1, -1)`` + Example: ``math.copysign(1, -1)`` -:param x: Eine Zahl -:param y: Die Herkunft des Vorzeichens für den Rückgabewert -:return: ``x`` with the sign of ``y``""" + :param x: A number + :param y: The source of the sign for the return value + :return: ``x`` with the sign of ``y`` + """ ... def cos(x: float) -> float: - """Berechnet den Kosinus von ``x``. + """Calculate the cosine of ``x``. -Example: ``math.cos(0)`` + Example: ``math.cos(0)`` -:param x: Eine Zahl -:return: The cosine of ``x``""" + :param x: A number + :return: The cosine of ``x`` + """ ... def degrees(x: float) -> float: - """Wandelt Bogenmaß (Radiant) in Grad um. + """Convert radians to degrees. -Example: ``math.degrees(2 * math.pi)`` + Example: ``math.degrees(2 * math.pi)`` -:param x: Ein Wert in Radiant -:return: The value converted to degrees""" + :param x: A value in radians + :return: The value converted to degrees""" ... def exp(x: float) -> float: - """Berechnet den Exponentialwert von ``x``. + """Calculate the exponential of ``x``. -Example: ``math.exp(1)`` + Example: ``math.exp(1)`` -:param x: Eine Zahl -:return: The exponential of ``x``.""" + :param x: A number + :return: The exponential of ``x``. + """ ... def fabs(x: float) -> float: - """Gibt den absoluten Wert von ``x`` zurück. + """Return the absolute value of ``x``. -Example: ``math.fabs(-0.1)`` + Example: ``math.fabs(-0.1)`` -:param x: Eine Zahl -:return: The absolute value of ``x``""" + :param x: A number + :return: The absolute value of ``x`` + """ ... def floor(x: float) -> int: - """Rundet eine Zahl in Richtung negativer Unendlichkeit. + """Round a number towards negative infinity. -Example: ``math.floor(0.9)`` + Example: ``math.floor(0.9)`` -:param x: Eine Zahl -:return: ``x`` rounded towards negative infinity.""" + :param x: A number + :return: ``x`` rounded towards negative infinity. + """ ... def fmod(x: float, y: float) -> float: - """Berechne den Rest von ``x/y``. + """Calculate the remainder of ``x/y``. -Example: ``math.fmod(10, 3)`` + Example: ``math.fmod(10, 3)`` -:param x: Der Zähler -:param y: Der Nenner""" + :param x: The numerator + :param y: The denominator + """ ... def frexp(x: float) -> Tuple[float, int]: - """Zerlegt eine Gleitkommazahl in ihre Mantisse und ihren Exponenten. + """Decomposes a floating-point number into its mantissa and exponent. -Example: ``mantissa, exponent = math.frexp(2)`` + Example: ``mantissa, exponent = math.frexp(2)`` -The returned value is the tuple ``(m, e)`` such that ``x == m * 2**e`` -exactly. If ``x == 0`` then the function returns ``(0.0, 0)``, otherwise -the relation ``0.5 <= abs(m) < 1`` holds. + The returned value is the tuple ``(m, e)`` such that ``x == m * 2**e`` + exactly. If ``x == 0`` then the function returns ``(0.0, 0)``, otherwise + the relation ``0.5 <= abs(m) < 1`` holds. -:param x: Eine Fließkommazahl -:return: A tuple of length two containing its mantissa then exponent""" + :param x: A floating-point number + :return: A tuple of length two containing its mantissa then exponent + """ ... def isfinite(x: float) -> bool: - """Überprüft, ob ein Wert endlich ist. + """Check if a value is finite. -Example: ``math.isfinite(float('inf'))`` + Example: ``math.isfinite(float('inf'))`` -:param x: Eine Zahl. -:return: ``True`` if ``x`` is finite, ``False`` otherwise.""" + :param x: A number. + :return: ``True`` if ``x`` is finite, ``False`` otherwise. + """ ... def isinf(x: float) -> bool: - """Überprüft, ob ein Wert unendlich ist. + """Check if a value is infinite. -Example: ``math.isinf(float('-inf'))`` + Example: ``math.isinf(float('-inf'))`` -:param x: Eine Zahl. -:return: ``True`` if ``x`` is infinite, ``False`` otherwise.""" + :param x: A number. + :return: ``True`` if ``x`` is infinite, ``False`` otherwise. + """ ... def isnan(x: float) -> bool: - """Prüft, ob ein Wert keine Zahl (NaN ... Not A Number) ist. + """Check if a value is not-a-number (NaN). -Example: ``math.isnan(float('nan'))`` + Example: ``math.isnan(float('nan'))`` -:param x: Eine Zahl -:return: ``True`` if ``x`` is not-a-number (NaN), ``False`` otherwise.""" + :param x: A number + :return: ``True`` if ``x`` is not-a-number (NaN), ``False`` otherwise.""" ... def ldexp(x: float, exp: int) -> float: - """Berechne ``x * (2**exp)``. + """Calculate ``x * (2**exp)``. -Example: ``math.ldexp(0.5, 2)`` + Example: ``math.ldexp(0.5, 2)`` -:param x: Eine Zahl -:param exp: Ganzzahl-Exponent -:return: ``x * (2**exp)``""" + :param x: A number + :param exp: Integer exponent + :return: ``x * (2**exp)`` + """ ... -def log(x: float, base: float=e) -> float: - """Berechnet den Logarithmus von ``x`` zur angegebenen Basis (standardmäßig den natürlichen Logarithmus). +def log(x: float, base: float = e) -> float: + """Calculate the logarithm of ``x`` to the given base (defaults to natural logorithm). -Example: ``math.log(math.e)`` + Example: ``math.log(math.e)`` -With one argument, return the natural logarithm of x (to base e). + With one argument, return the natural logarithm of x (to base e). -With two arguments, return the logarithm of x to the given base, calculated as ``log(x)/log(base)``. + With two arguments, return the logarithm of x to the given base, calculated as ``log(x)/log(base)``. -:param x: Eine Zahl -:param base: Die zu verwendende Basis -:return: The natural logarithm of ``x``""" + :param x: A number + :param base: The base to use + :return: The natural logarithm of ``x`` + """ ... def modf(x: float) -> Tuple[float, float]: - """Berechne die gebrochenen und ganzzahligen Teile von ``x``. + """Calculate the fractional and integral parts of ``x``. -Example: ``fractional, integral = math.modf(1.5)`` + Example: ``fractional, integral = math.modf(1.5)`` -:param x: Eine Zahl -:return: A tuple of two floats representing the fractional then integral parts of ``x``. + :param x: A number + :return: A tuple of two floats representing the fractional then integral parts of ``x``. -Both the fractional and integral values have the same sign as ``x``.""" + Both the fractional and integral values have the same sign as ``x``. + """ ... def pow(x: float, y: float) -> float: - """Gibt ``x`` hoch ``y`` zurück. + """Returns ``x`` to the power of ``y``. -Example: ``math.pow(4, 0.5)`` + Example: ``math.pow(4, 0.5)`` -:param x: Eine Zahl -:param y: Der Exponent -:return: ``x`` to the power of ``y``""" + :param x: A number + :param y: The exponent + :return: ``x`` to the power of ``y`` + """ ... def radians(x: float) -> float: - """Wandelt Grad in Bogenmaß (Radiant) um. + """Convert a degrees to radians. -Example: ``math.radians(360)`` + Example: ``math.radians(360)`` -:param x: Ein Wert in Grad -:return: The value converted to radians""" + :param x: A value in degrees + :return: The value converted to radians + """ ... def sin(x: float) -> float: - """Berechnet den Sinus von ``x``. + """Calculate the sine of ``x``. -Example: ``math.sin(math.pi/2)`` + Example: ``math.sin(math.pi/2)`` -:param x: Eine Zahl -:return: The sine of ``x``""" + :param x: A number + :return: The sine of ``x`` + """ ... def sqrt(x: float) -> float: - """Berechnet die Quadratwurzel von ``x``. + """Calculate the square root of ``x``. -Example: ``math.sqrt(4)`` + Example: ``math.sqrt(4)`` -:param x: Eine Zahl -:return: The square root of ``x``""" + :param x: A number + :return: The square root of ``x`` + """ ... def tan(x: float) -> float: - """Berechnet den Tangens von ``x``. + """Calculate the tangent of ``x``. -Example: ``math.tan(0)`` + Example: ``math.tan(0)`` -:param x: Eine Zahl -:return: The tangent of ``x``.""" + :param x: A number + :return: The tangent of ``x``. + """ ... def trunc(x: float) -> int: - """Rundet eine Zahl gegen 0 ab. + """Round a number towards 0. -Example: ``math.trunc(-0.9)`` + Example: ``math.trunc(-0.9)`` -:param x: Eine Zahl -:return: ``x`` rounded towards zero.""" + :param x: A number + :return: ``x`` rounded towards zero. + """ ... + e: float -"""Basis des natürlichen Logarithmus""" +"""Base of the natural logarithm""" + pi: float -"""Das Verhältnis des Umfangs eines Kreises zu seinem Durchmesser""" \ No newline at end of file +"""The ratio of a circle's circumference to its diameter""" diff --git a/lang/de/typeshed/stdlib/microbit/__init__.pyi b/lang/de/typeshed/stdlib/microbit/__init__.pyi index 023ebc6..f12158f 100644 --- a/lang/de/typeshed/stdlib/microbit/__init__.pyi +++ b/lang/de/typeshed/stdlib/microbit/__init__.pyi @@ -1,6 +1,11 @@ -"""Pins, Bilder, Töne, Temperatur und Lautstärke.""" +"""Pins, images, sounds, temperature and volume. +""" + from typing import Any, Callable, List, Optional, Tuple, Union, overload + from _typeshed import ReadableBuffer + +# V2 only from . import accelerometer as accelerometer from . import audio as audio from . import compass as compass @@ -11,696 +16,831 @@ from . import speaker as speaker from . import spi as spi from . import uart as uart -def run_every(callback: Optional[Callable[[], None]]=None, days: int=0, h: int=0, min: int=0, s: int=0, ms: int=0) -> Callable[[Callable[[], None]], Callable[[], None]]: - """Plant die Ausführung einer Funktion in dem durch die Zeitargumente festgelegten Intervall **nur V2**. +def run_every( + callback: Optional[Callable[[], None]] = None, + days: int = 0, + h: int = 0, + min: int = 0, + s: int = 0, + ms: int = 0, +) -> Callable[[Callable[[], None]], Callable[[], None]]: + """Schedule to run a function at the interval specified by the time arguments **V2 only**. -Example: ``run_every(my_logging, min=5)`` + Example: ``run_every(my_logging, min=5)`` -``run_every`` can be used in two ways: + ``run_every`` can be used in two ways: -As a Decorator - placed on top of the function to schedule. For example:: + As a Decorator - placed on top of the function to schedule. For example:: - @run_every(h=1, min=20, s=30, ms=50) - def my_function(): - # Do something here + @run_every(h=1, min=20, s=30, ms=50) + def my_function(): + # Do something here -As a Function - passing the callback as a positional argument. For example:: + As a Function - passing the callback as a positional argument. For example:: - def my_function(): - # Do something here - run_every(my_function, s=30) + def my_function(): + # Do something here + run_every(my_function, s=30) -Each argument corresponds to a different time unit and they are additive. -So ``run_every(min=1, s=30)`` schedules the callback every minute and a half. + Each argument corresponds to a different time unit and they are additive. + So ``run_every(min=1, s=30)`` schedules the callback every minute and a half. -When an exception is thrown inside the callback function it deschedules the -function. To avoid this you can catch exceptions with ``try/except``. + When an exception is thrown inside the callback function it deschedules the + function. To avoid this you can catch exceptions with ``try/except``. -:param callback: Funktion, die in dem angegebenen Intervall aufgerufen wird. Bei Verwendung als Dekorator weglassen. -:param days: Legt den Tag für die Planung fest. -:param h: Legt die Uhrzeit für die Planung fest. -:param min: Legt die Minute für die Planung fest. -:param s: Legt die Sekunde für die Planung fest. -:param ms: Legt die Millisekunde für die Planung fest.""" + :param callback: Function to call at the provided interval. Omit when using as a decorator. + :param days: Sets the day mark for the scheduling. + :param h: Sets the hour mark for the scheduling. + :param min: Sets the minute mark for the scheduling. + :param s: Sets the second mark for the scheduling. + :param ms: Sets the millisecond mark for the scheduling. + """ def panic(n: int) -> None: - """In einen Panik-Modus wechseln. + """Enter a panic mode. -Example: ``panic(127)`` + Example: ``panic(127)`` -:param n: Eine beliebige ganze Zahl <= 255, um einen Status anzugeben. + :param n: An arbitrary integer <= 255 to indicate a status. -Requires restart.""" + Requires restart. + """ def reset() -> None: - """Board neu starten.""" + """Restart the board.""" + @overload def scale(value: float, from_: Tuple[float, float], to: Tuple[int, int]) -> int: - """Konvertiert einen Wert aus einem Bereich in einen Ganzzahlenbereich. + """Converts a value from a range to an integer range. -Example: ``volume = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255))`` + Example: ``volume = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255))`` -For example, to convert an accelerometer X value to a speaker volume. + For example, to convert an accelerometer X value to a speaker volume. -If one of the numbers in the ``to`` parameter is a floating point -(i.e a decimal number like ``10.0``), this function will return a -floating point number. + If one of the numbers in the ``to`` parameter is a floating point + (i.e a decimal number like ``10.0``), this function will return a + floating point number. - temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0)) + temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0)) -:param value: (wert) Eine umzurechnende Zahl. -:param from_: Ein Tupel, das den Bereich definiert, aus dem konvertiert werden soll. -:param to: Ein Tupel, das den Bereich definiert, in den konvertiert werden soll. -:return: The ``value`` converted to the ``to`` range.""" + :param value: A number to convert. + :param from_: A tuple to define the range to convert from. + :param to: A tuple to define the range to convert to. + :return: The ``value`` converted to the ``to`` range. + """ @overload def scale(value: float, from_: Tuple[float, float], to: Tuple[float, float]) -> float: - """Konvertiert einen Wert von einem Bereich in einen Gleitkommabereich. + """Converts a value from a range to a floating point range. -Example: ``temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0))`` + Example: ``temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0))`` -For example, to convert temperature from a Celsius scale to Fahrenheit. + For example, to convert temperature from a Celsius scale to Fahrenheit. -If one of the numbers in the ``to`` parameter is a floating point -(i.e a decimal number like ``10.0``), this function will return a -floating point number. -If they are both integers (i.e ``10``), it will return an integer:: + If one of the numbers in the ``to`` parameter is a floating point + (i.e a decimal number like ``10.0``), this function will return a + floating point number. + If they are both integers (i.e ``10``), it will return an integer:: - returns_int = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255)) + returns_int = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255)) -:param value: Eine umzurechnende Zahl. -:param from_: Ein Tupel, das den Bereich definiert, aus dem konvertiert werden soll. -:param to: Ein Tupel, das den Bereich definiert, in den konvertiert werden soll. -:return: The ``value`` converted to the ``to`` range.""" + :param value: A number to convert. + :param from_: A tuple to define the range to convert from. + :param to: A tuple to define the range to convert to. + :return: The ``value`` converted to the ``to`` range. + """ def sleep(n: float) -> None: - """Warte auf ``n`` Millisekunden. + """Wait for ``n`` milliseconds. -Example: ``sleep(1000)`` + Example: ``sleep(1000)`` -:param n: Die Anzahl der zu wartenden Millisekunden + :param n: The number of milliseconds to wait -One second is 1000 milliseconds, so:: + One second is 1000 milliseconds, so:: - microbit.sleep(1000) + microbit.sleep(1000) -will pause the execution for one second.""" + will pause the execution for one second. + """ def running_time() -> int: - """Ermittelt die Laufzeit des Boards. + """Get the running time of the board. -:return: The number of milliseconds since the board was switched on or restarted.""" + :return: The number of milliseconds since the board was switched on or restarted. + """ def temperature() -> int: - """Ermittelt die Temperatur des micro:bit in Grad Celcius.""" + """Get the temperature of the micro:bit in degrees Celsius.""" def set_volume(v: int) -> None: - """Legt die Lautstärke fest. + """Sets the volume. -Example: ``set_volume(127)`` + Example: ``set_volume(127)`` -:param v: ein Wert zwischen 0 (niedrig) und 255 (hoch). + :param v: a value between 0 (low) and 255 (high). -Out of range values will be clamped to 0 or 255. + Out of range values will be clamped to 0 or 255. -**V2** only.""" + **V2** only. + """ ... class Button: - """Die Klasse für die Tasten ``button_a`` und ``button_b``.""" + """The class for the buttons ``button_a`` and ``button_b``.""" def is_pressed(self) -> bool: - """Überprüft, ob die Taste gedrückt ist. + """Check if the button is pressed. -:return: ``True`` if the specified button ``button`` is pressed, and ``False`` otherwise.""" + :return: ``True`` if the specified button ``button`` is pressed, and ``False`` otherwise. + """ ... - def was_pressed(self) -> bool: - """Überprüft, ob die Taste seit dem Start des Geräts oder dem letzten Aufruf dieser Methode gedrückt wurde. + """Check if the button was pressed since the device started or the last time this method was called. -Calling this method will clear the press state so -that the button must be pressed again before this method will return -``True`` again. + Calling this method will clear the press state so + that the button must be pressed again before this method will return + ``True`` again. -:return: ``True`` if the specified button ``button`` was pressed, and ``False`` otherwise""" + :return: ``True`` if the specified button ``button`` was pressed, and ``False`` otherwise + """ ... - def get_presses(self) -> int: - """Ermittelt die Gesamtzahl der Tastendrücke und setzt diese Summe auf Null zurück, bevor sie zurückgegeben wird. + """Get the running total of button presses, and resets this total + to zero before returning. -:return: The number of presses since the device started or the last time this method was called""" + :return: The number of presses since the device started or the last time this method was called + """ ... + button_a: Button -"""Das ``Button``-Objekt der linken Taste.""" +"""The left button ``Button`` object.""" + button_b: Button -"""Das ``Button``-Objekt der rechten Taste.""" +"""The right button ``Button`` object.""" class MicroBitDigitalPin: - """Ein digitaler Pin. + """A digital pin. + + Some pins support analog and touch features using the ``MicroBitAnalogDigitalPin`` and ``MicroBitTouchPin`` subclasses. + """ -Some pins support analog and touch features using the ``MicroBitAnalogDigitalPin`` and ``MicroBitTouchPin`` subclasses.""" NO_PULL: int PULL_UP: int PULL_DOWN: int - def read_digital(self) -> int: - """Ermittelt den digitalen Wert des Pins. + """Get the digital value of the pin. -Example: ``value = pin0.read_digital()`` + Example: ``value = pin0.read_digital()`` -:return: 1 if the pin is high, and 0 if it's low.""" + :return: 1 if the pin is high, and 0 if it's low. + """ ... - def write_digital(self, value: int) -> None: - """Stellt den digitalen Wert des Pins ein. (digital schreiben) + """Set the digital value of the pin. -Example: ``pin0.write_digital(1)`` + Example: ``pin0.write_digital(1)`` -:param value: (wert) 1, um den Pin zu aktivieren, oder 0, um den Pin zu deaktivieren""" + :param value: 1 to set the pin high or 0 to set the pin low""" ... - def set_pull(self, value: int) -> None: - """Setze den Status des Pull-Widerstands auf einen von drei möglichen Werten: ``PULL_UP``, ``PULL_DOWN`` oder ``NO_PULL``. (setze Pull-Widerstand) + """Set the pull state to one of three possible values: ``PULL_UP``, ``PULL_DOWN`` or ``NO_PULL``. -Example: ``pin0.set_pull(pin0.PULL_UP)`` + Example: ``pin0.set_pull(pin0.PULL_UP)`` -:param value: (wert) Der Status des Pull-Widerstands vom relevanten Pin, z.B. ``pin0.PULL_UP``.""" + :param value: The pull state from the relevant pin, e.g. ``pin0.PULL_UP``. + """ ... - def get_pull(self) -> int: - """Abrufen des Status des Pull-Widerstands eines Pins. (gib Pull-Widerstand) + """Get the pull state on a pin. -Example: ``pin0.get_pull()`` + Example: ``pin0.get_pull()`` -:return: ``NO_PULL``, ``PULL_DOWN``, or ``PULL_UP`` + :return: ``NO_PULL``, ``PULL_DOWN``, or ``PULL_UP`` -These are set using the ``set_pull()`` method or automatically configured -when a pin mode requires it.""" + These are set using the ``set_pull()`` method or automatically configured + when a pin mode requires it. + """ ... - def get_mode(self) -> str: - """Gibt den Pin-Modus zurück. (gib Pin-Modus) + """Returns the pin mode. -Example: ``pin0.get_mode()`` + Example: ``pin0.get_mode()`` -When a pin is used for a specific function, like -writing a digital value, or reading an analog value, the pin mode -changes. + When a pin is used for a specific function, like + writing a digital value, or reading an analog value, the pin mode + changes. -:return: ``"unused"``, ``"analog"``, ``"read_digital"``, ``"write_digital"``, ``"display"``, ``"button"``, ``"music"``, ``"audio"``, ``"touch"``, ``"i2c"``, or ``"spi"``""" + :return: ``"unused"``, ``"analog"``, ``"read_digital"``, ``"write_digital"``, ``"display"``, ``"button"``, ``"music"``, ``"audio"``, ``"touch"``, ``"i2c"``, or ``"spi"`` + """ ... - def write_analog(self, value: int) -> None: - """Erzeugt ein PWM-Signal am Pin mit der Einschaltdauer proportional zu ``value``. (analog schreiben) - -Example: ``pin0.write_analog(254)`` + """Output a PWM signal on the pin, with the duty cycle proportional to ``value``. -:param value: (wert) Eine Ganzzahl oder eine Gleitpunktzahl zwischen 0 (0% Einschaltdauer) und 1023 (100% Einschaltdauer).""" + Example: ``pin0.write_analog(254)`` + :param value: An integer or a floating point number between 0 (0% duty cycle) and 1023 (100% duty). + """ def set_analog_period(self, period: int) -> None: - """Setzt die Periodendauer des PWM-Signals, das ausgegeben wird, auf ``period`` in Millisekunden. (setze analoge Periodendauer) + """Set the period of the PWM signal being output to ``period`` in milliseconds. -Example: ``pin0.set_analog_period(10)`` - -:param period: (Periodendauer) Der Periodendauer in Millisekunden mit einem Mindestwert von 1ms.""" + Example: ``pin0.set_analog_period(10)`` + :param period: The period in milliseconds with a minimum valid value of 1ms. + """ def set_analog_period_microseconds(self, period: int) -> None: - """Setze die Periodendauer für die Ausgabe des PWM-Signals auf ``period`` in Mikrosekunden. (setze analoge Periodendauer) + """Set the period of the PWM signal being output to ``period`` in microseconds. -Example: ``pin0.set_analog_period_microseconds(512)`` + Example: ``pin0.set_analog_period_microseconds(512)`` -:param period: (Periodendauer) Die Periodendauer in Mikrosekunden mit einem Mindestwert von 256μs.""" + :param period: The period in microseconds with a minimum valid value of 256µs. + """ class MicroBitAnalogDigitalPin(MicroBitDigitalPin): - """Ein Pin, der analogen und digitalen Signale erlaubt.""" + """A pin with analog and digital features.""" def read_analog(self) -> int: - """Einlesen der Spannung, die am Pin anliegt. (analog lesen) + """Read the voltage applied to the pin. -Example: ``pin0.read_analog()`` + Example: ``pin0.read_analog()`` -:return: An integer between 0 (meaning 0V) and 1023 (meaning 3.3V).""" + :return: An integer between 0 (meaning 0V) and 1023 (meaning 3.3V). + """ class MicroBitTouchPin(MicroBitAnalogDigitalPin): - """Ein Pin mit analogen, digitalen und Touchfunktionen.""" + """A pin with analog, digital and touch features.""" + CAPACITIVE: int RESISTIVE: int - def is_touched(self) -> bool: - """Überprüft, ob der Pin berührt wird. (wird berührt) + """Check if the pin is being touched. -Example: ``pin0.is_touched()`` + Example: ``pin0.is_touched()`` -The default touch mode for the pins on the edge connector is ``resistive``. -The default for the logo pin **V2** is ``capacitive``. + The default touch mode for the pins on the edge connector is ``resistive``. + The default for the logo pin **V2** is ``capacitive``. -**Resistive touch** -This test is done by measuring how much resistance there is between the -pin and ground. A low resistance gives a reading of ``True``. To get -a reliable reading using a finger you may need to touch the ground pin -with another part of your body, for example your other hand. + **Resistive touch** + This test is done by measuring how much resistance there is between the + pin and ground. A low resistance gives a reading of ``True``. To get + a reliable reading using a finger you may need to touch the ground pin + with another part of your body, for example your other hand. -**Capacitive touch** -This test is done by interacting with the electric field of a capacitor -using a finger as a conductor. `Capacitive touch -`_ -does not require you to make a ground connection as part of a circuit. + **Capacitive touch** + This test is done by interacting with the electric field of a capacitor + using a finger as a conductor. `Capacitive touch + `_ + does not require you to make a ground connection as part of a circuit. -:return: ``True`` if the pin is being touched with a finger, otherwise return ``False``.""" + :return: ``True`` if the pin is being touched with a finger, otherwise return ``False``. + """ ... - def set_touch_mode(self, value: int) -> None: - """Legt den Touchmodus für den Pin fest. (definiert Berührungsmodus) + """Set the touch mode for the pin. -Example: ``pin0.set_touch_mode(pin0.CAPACITIVE)`` + Example: ``pin0.set_touch_mode(pin0.CAPACITIVE)`` -The default touch mode for the pins on the edge connector is -``resistive``. The default for the logo pin **V2** is ``capacitive``. + The default touch mode for the pins on the edge connector is + ``resistive``. The default for the logo pin **V2** is ``capacitive``. -:param value: (wert) ``CAPACITIVE`` oder ``RESISTIVE`` Touchmodus des entsprechenden Pins.""" + :param value: ``CAPACITIVE`` or ``RESISTIVE`` from the relevant pin. + """ ... + pin0: MicroBitTouchPin -"""Pin mit digitalen, analogen und Touchfunktionen.""" +"""Pin with digital, analog and touch features.""" + pin1: MicroBitTouchPin -"""Pin mit digitalen, analogen und Touchfunktionen.""" +"""Pin with digital, analog and touch features.""" + pin2: MicroBitTouchPin -"""Pin mit digitalen, analogen und Touchfunktionen.""" +"""Pin with digital, analog and touch features.""" + pin3: MicroBitAnalogDigitalPin -"""Pin mit digitalen und analogen Funktionen.""" +"""Pin with digital and analog features.""" + pin4: MicroBitAnalogDigitalPin -"""Pin mit digitalen und analogen Funktionen.""" +"""Pin with digital and analog features.""" + pin5: MicroBitDigitalPin -"""Pin mit Unterstützung für digitale Signale.""" +"""Pin with digital features.""" + pin6: MicroBitDigitalPin -"""Pin mit Unterstützung für digitale Signale.""" +"""Pin with digital features.""" + pin7: MicroBitDigitalPin -"""Pin mit digitalen Funktionen.""" +"""Pin with digital features.""" + pin8: MicroBitDigitalPin -"""Pin mit digitalen Funktionen.""" +"""Pin with digital features.""" + pin9: MicroBitDigitalPin -"""Pin mit digitalen Funktionen.""" +"""Pin with digital features.""" + pin10: MicroBitAnalogDigitalPin -"""Pin mit digitalen und analogen Funktionen.""" +"""Pin with digital and analog features.""" + pin11: MicroBitDigitalPin -"""Pin mit digitalen Funktionen.""" +"""Pin with digital features.""" + pin12: MicroBitDigitalPin -"""Pin mit digitalen Funktionen.""" +"""Pin with digital features.""" + pin13: MicroBitDigitalPin -"""Pin mit digitalen Funktionen.""" +"""Pin with digital features.""" + pin14: MicroBitDigitalPin -"""Pin mit digitalen Funktionen.""" +"""Pin with digital features.""" + pin15: MicroBitDigitalPin -"""Pin mit digitalen Funktionen.""" +"""Pin with digital features.""" + pin16: MicroBitDigitalPin -"""Pin mit digitalen Funktionen.""" +"""Pin with digital features.""" + pin19: MicroBitDigitalPin -"""Pin mit digitalen Funktionen.""" +"""Pin with digital features.""" + pin20: MicroBitDigitalPin -"""Pin mit digitalen Funktionen.""" +"""Pin with digital features.""" + pin_logo: MicroBitTouchPin -"""Ein berührungsempfindlicher Logo-Pin auf der Vorderseite des micro:bit, der standardmäßig auf den kapazitiven Touch-Modus eingestellt ist.""" +"""A touch sensitive logo pin on the front of the micro:bit, which by default is set to capacitive touch mode.""" + pin_speaker: MicroBitAnalogDigitalPin -"""Ein Pin zur Ansteuerung des micro:bit Lautsprechers. +"""A pin to address the micro:bit speaker. This API is intended only for use in Pulse-Width Modulation pin operations e.g. pin_speaker.write_analog(128). """ class Image: - """Ein Bild, das auf dem micro:bit LED-Display angezeigt werden soll. + """An image to show on the micro:bit LED display. -Given an image object it's possible to display it via the ``display`` API:: + Given an image object it's possible to display it via the ``display`` API:: + + display.show(Image.HAPPY) + """ - display.show(Image.HAPPY)""" HEART: Image - """Herz-Bild.""" + """Heart image.""" + HEART_SMALL: Image - """Kleines Herz-Bild.""" + """Small heart image.""" + HAPPY: Image - """Glückliches Gesichtsbild.""" + """Happy face image.""" + SMILE: Image - """Lächelndes Gesichtsbild.""" + """Smiling mouth image.""" + SAD: Image - """Trauriges Gesichtsbild.""" + """Sad face image.""" + CONFUSED: Image - """Verwirrtes Gesichtsbild.""" + """Confused face image.""" + ANGRY: Image - """Wütendes Gesichtsbild.""" + """Angry face image.""" + ASLEEP: Image - """Schlafendes Gesichtsbild.""" + """Sleeping face image.""" + SURPRISED: Image - """Überraschtes Gesichtsbild.""" + """Surprised face image.""" + SILLY: Image - """Albernes Gesichtsbild.""" + """Silly face image.""" + FABULOUS: Image - """Bild mit Sonnenbrillengesicht. (fabelhaft)""" + """Sunglasses face image.""" + MEH: Image - """Gleichgültiges Gesicht Bild.""" + """Unimpressed face image.""" + YES: Image - """abgehakt-Bild""" + """Tick image.""" + NO: Image - """angekreuzt-Bild""" + """Cross image.""" + CLOCK12: Image - """Bild mit Linie, die auf 12 Uhr zeigt.""" + """Image with line pointing to 12 o'clock.""" + CLOCK11: Image - """Bild mit Linie, die auf 11 Uhr zeigt.""" + """Image with line pointing to 11 o'clock.""" + CLOCK10: Image - """Bild mit Linie, die auf 10 Uhr zeigt.""" + """Image with line pointing to 10 o'clock.""" + CLOCK9: Image - """Bild mit Linie, die auf 9 Uhr zeigt.""" + """Image with line pointing to 9 o'clock.""" + CLOCK8: Image - """Bild mit Linie, die auf 8 Uhr zeigt.""" + """Image with line pointing to 8 o'clock.""" + CLOCK7: Image - """Bild mit Linie, die auf 7 Uhr zeigt.""" + """Image with line pointing to 7 o'clock.""" + CLOCK6: Image - """Bild mit Linie, die auf 6 Uhr zeigt.""" + """Image with line pointing to 6 o'clock.""" + CLOCK5: Image - """Bild mit Linie, die auf 5 Uhr zeigt.""" + """Image with line pointing to 5 o'clock.""" + CLOCK4: Image - """Bild mit Linie, die auf 4 Uhr zeigt.""" + """Image with line pointing to 4 o'clock.""" + CLOCK3: Image - """Bild mit Linie, die auf 3 Uhr zeigt.""" + """Image with line pointing to 3 o'clock.""" + CLOCK2: Image - """Bild mit Linie, die auf 2 Uhr zeigt.""" + """Image with line pointing to 2 o'clock.""" + CLOCK1: Image - """Bild mit Linie, die auf 1 Uhr zeigt.""" + """Image with line pointing to 1 o'clock.""" + ARROW_N: Image - """Bild eines Pfeils, der nach Norden zeigt.""" + """Image of arrow pointing north.""" + ARROW_NE: Image - """Bild eines Pfeils, der nach Nordosten zeigt.""" + """Image of arrow pointing north east.""" + ARROW_E: Image - """Bild eines Pfeils, der nach Osten zeigt.""" + """Image of arrow pointing east.""" + ARROW_SE: Image - """Bild eines Pfeils, der nach Südosten zeigt.""" + """Image of arrow pointing south east.""" + ARROW_S: Image - """Bild eines Pfeils, der nach Süden zeigt.""" + """Image of arrow pointing south.""" + ARROW_SW: Image - """Bild eines Pfeils, der nach Südwesten zeigt.""" + """Image of arrow pointing south west.""" + ARROW_W: Image - """Bild eines Pfeils, der nach Westen zeigt.""" + """Image of arrow pointing west.""" + ARROW_NW: Image - """Bild eines Pfeils, der nach Nordwesten zeigt.""" + """Image of arrow pointing north west.""" + TRIANGLE: Image - """Bild eines Dreiecks, das nach oben zeigt.""" + """Image of a triangle pointing up.""" + TRIANGLE_LEFT: Image - """Bild eines Dreiecks in der linken Ecke.""" + """Image of a triangle in the left corner.""" + CHESSBOARD: Image - """Abwechselnd leuchtende LEDs in einem Schachbrettmuster.""" + """Alternate LEDs lit in a chessboard pattern.""" + DIAMOND: Image - """Diamant-Bild.""" + """Diamond image.""" + DIAMOND_SMALL: Image - """Kleines Diamant-Bild.""" + """Small diamond image.""" + SQUARE: Image - """Quadrat-Bild""" + """Square image.""" + SQUARE_SMALL: Image - """Kleines Quadrat-Bild.""" + """Small square image.""" + RABBIT: Image - """Kaninchen-Bild.""" + """Rabbit image.""" + COW: Image - """Kuh-Bild.""" + """Cow image.""" + MUSIC_CROTCHET: Image - """Viertelnoten-Bild.""" + """Crotchet note image.""" + MUSIC_QUAVER: Image - """Achtelnoten-Bild.""" + """Quaver note image.""" + MUSIC_QUAVERS: Image - """Achtelnotenpaar-Bild.""" + """Pair of quavers note image.""" + PITCHFORK: Image - """Heugabel-Bild""" + """Pitchfork image.""" + XMAS: Image - """Weihnachtsbaum-Bild.""" + """Christmas tree image.""" + PACMAN: Image - """Pac-Man Spielfigurenbild.""" + """Pac-Man arcade character image.""" + TARGET: Image - """Ziel-Bild""" + """Target image.""" + TSHIRT: Image - """T-Shirt-Bild.""" + """T-shirt image.""" + ROLLERSKATE: Image - """Rollerskate-Bild.""" + """Rollerskate image.""" + DUCK: Image - """Ente-Bild""" + """Duck image.""" + HOUSE: Image - """Haus-Bild""" + """House image.""" + TORTOISE: Image - """Schildkröte-Bild""" + """Tortoise image.""" + BUTTERFLY: Image - """Schmetterling-Bild.""" + """Butterfly image.""" + STICKFIGURE: Image - """Strichmännchen-Bild.""" + """Stick figure image.""" + GHOST: Image - """Geist-Bild.""" + """Ghost image.""" + SWORD: Image - """Schwert-Bild""" + """Sword image.""" + GIRAFFE: Image - """Giraffe-Bild.""" + """Giraffe image.""" + SKULL: Image - """Schädel-Bild.""" + """Skull image.""" + UMBRELLA: Image - """Bild eines Schirms.""" + """Umbrella image.""" + SNAKE: Image - """Bild einer Schlange. (Schlange)""" + """Snake image.""" + SCISSORS: Image - """BIld einer Schere. (Schere)""" + """Scissors image.""" + ALL_CLOCKS: List[Image] - """Eine Liste mit allen CLOCK_ Bildern. (alle Uhren)""" - ALL_ARROWS: List[Image] - """Eine Liste mit allen ARROW_ Bildern. (alle Pfeile)""" + """A list containing all the CLOCK_ images in sequence.""" + ALL_ARROWS: List[Image] + """A list containing all the ARROW_ images in sequence.""" @overload def __init__(self, string: str) -> None: - """Erstellen Sie ein Bild aus einer Zeichenkette, die beschreibt, welche LEDs leuchten. + """Create an image from a string describing which LEDs are lit. -``string`` has to consist of digits 0-9 arranged into lines, -describing the image, for example:: + ``string`` has to consist of digits 0-9 arranged into lines, + describing the image, for example:: - image = Image("90009:" - "09090:" - "00900:" - "09090:" - "90009") + 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 newlines (\\n) insead of the colons. + 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 newlines (\\n) insead of the colons. -:param string: (Zeichenkette) Eine Zeichenkette, die das Bild beschreibt.""" + :param string: The string describing the image. + """ ... - @overload - def __init__(self, width: int=5, height: int=5, buffer: ReadableBuffer=None) -> None: - """Erstelle ein leeres Bild mit ``width`` Spalten und ``height`` Zeilen. + def __init__( + self, width: int = 5, height: int = 5, buffer: ReadableBuffer = None + ) -> None: + """Create an empty image with ``width`` columns and ``height`` rows. -:param width: (Breite) Optionale Breite des Bildes -:param height: (Höhe) Optionale Höhe des Bildes -:param buffer: (Puffer) Optionales Array oder Bytes von ``width``×``height`` Ganzzahlen im Bereich 0-9 um das Bild zu initialisieren + :param width: Optional width of the image + :param height: Optional height of the image + :param buffer: Optional array or bytes of ``width``×``height`` integers in range 0-9 to initialize the image -Examples:: + Examples:: - Image(2, 2, b'\x08\x08\x08\x08') - Image(2, 2, bytearray([9,9,9,9])) + Image(2, 2, b'\x08\x08\x08\x08') + Image(2, 2, bytearray([9,9,9,9])) -These create 2 x 2 pixel images at full brightness.""" + These create 2 x 2 pixel images at full brightness. + """ ... - def width(self) -> int: - """Ermittelt die Anzahl der Spalten. (Breite) + """Get the number of columns. -:return: The number of columns in the image""" + :return: The number of columns in the image + """ ... - def height(self) -> int: - """Ermittelt die Anzahl der Zeilen. (Höhe) + """Get the number of rows. -:return: The number of rows in the image""" + :return: The number of rows in the image + """ ... - def set_pixel(self, x: int, y: int, value: int) -> None: - """Legt die Helligkeit eines Pixels fest. (Pixelwerte setzen) + """Set the brightness of a pixel. -Example: ``my_image.set_pixel(0, 0, 9)`` + Example: ``my_image.set_pixel(0, 0, 9)`` -:param x: Die Spaltennummer -:param y: Die Zeilennummer -:param value: (wert) Die Helligkeit als Ganzzahl zwischen 0 (dunkel) und 9 (hell) + :param x: The column number + :param y: The row number + :param value: The brightness as an integer 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``.""" + 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: - """Ermittle die Helligkeit eines Pixels. (Pixelwerte holen) + """Get the brightness of a pixel. -Example: ``my_image.get_pixel(0, 0)`` + Example: ``my_image.get_pixel(0, 0)`` -:param x: Die Spaltennummer -:param y: Die Zeilennummer -:return: The brightness as an integer between 0 and 9.""" + :param x: The column number + :param y: The row number + :return: The brightness as an integer between 0 and 9. + """ ... - def shift_left(self, n: int) -> Image: - """Erstellen Sie ein neues Bild, indem Sie das Bild nach links verschieben. (links verschieben) + """Create a new image by shifting the picture left. -Example: ``Image.HEART_SMALL.shift_left(1)`` + Example: ``Image.HEART_SMALL.shift_left(1)`` -:param n: Die Anzahl der Spalten um die verschoben wird -:return: The shifted image""" + :param n: The number of columns to shift by + :return: The shifted image + """ ... - def shift_right(self, n: int) -> Image: - """Erstellen Sie ein neues Bild, indem Sie das Bild nach rechts verschieben. (rechts verschieben) + """Create a new image by shifting the picture right. -Example: ``Image.HEART_SMALL.shift_right(1)`` + Example: ``Image.HEART_SMALL.shift_right(1)`` -:param n: Die Anzahl der Spalten um die verschoben wird -:return: The shifted image""" + :param n: The number of columns to shift by + :return: The shifted image + """ ... - def shift_up(self, n: int) -> Image: - """Erstellen Sie ein neues Bild, indem Sie das Bild nach oben verschoben wird. (nach oben verschieben) + """Create a new image by shifting the picture up. -Example: ``Image.HEART_SMALL.shift_up(1)`` + Example: ``Image.HEART_SMALL.shift_up(1)`` -:param n: Die Anzahl der Zeilen um die verschoben wird -:return: The shifted image""" + :param n: The number of rows to shift by + :return: The shifted image + """ ... - def shift_down(self, n: int) -> Image: - """Erstellen Sie ein neues Bild, indem Sie das Bild nach unten verschoben wird. (nach unten verschieben) + """Create a new image by shifting the picture down. -Example: ``Image.HEART_SMALL.shift_down(1)`` + Example: ``Image.HEART_SMALL.shift_down(1)`` -:param n: Die Anzahl der Zeilen um die verschoben wird -:return: The shifted image""" + :param n: The number of rows to shift by + :return: The shifted image + """ ... - def crop(self, x: int, y: int, w: int, h: int) -> Image: - """Erstellen Sie ein neues Bild, indem das Bild zugeschnitten wird. + """Create a new image by cropping the picture. -Example: ``Image.HEART.crop(1, 1, 3, 3)`` + Example: ``Image.HEART.crop(1, 1, 3, 3)`` -:param x: Die Offset-Spalte des Zuschneidens -:param y: Die Offset-Zeile des Zuschneidens -:param w: Die Zuschneide-Breite -:param h: Die Zuschneide-Höhe -:return: The new image""" + :param x: The crop offset column + :param y: The crop offset row + :param w: The crop width + :param h: The crop height + :return: The new image + """ ... - def copy(self) -> Image: - """Erstellt eine exakte Kopie des Bildes. (kopieren) + """Create an exact copy of the image. -Example: ``Image.HEART.copy()`` + Example: ``Image.HEART.copy()`` -:return: The new image""" + :return: The new image + """ ... - def invert(self) -> Image: - """Erstellt ein neues Bild, indem es die Helligkeit der Pixel des Ausgangsbildes invertiert. + """Create a new image by inverting the brightness of the pixels in the + source image. -Example: ``Image.SMALL_HEART.invert()`` + Example: ``Image.SMALL_HEART.invert()`` -:return: The new image.""" + :return: The new image. + """ ... - def fill(self, value: int) -> None: - """Legt die Helligkeit für alle Pixel des Bildes fest. + """Set the brightness of all the pixels in the image. -Example: ``my_image.fill(5)`` + Example: ``my_image.fill(5)`` -:param value: Die neue Helligkeit als Zahl zwischen 0 (dunkel) und 9 (hell). + :param value: The new brightness as a number 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``.""" + 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: - """Kopiert einen Bereich aus einem anderen Bild in dieses Bild. - -Example: ``my_image.blit(Image.HEART, 1, 1, 3, 3, 1, 1)`` - -:param src: Das Ausgangsbild -:param x: Der Anfangsspalten-Offset im Ausgangsbild -:param y: Der Anfangszeilen-Offset im Ausgangsbild -:param w: Die Anzahl der zu kopierenden Spalten -:param h: Die Anzahl der zu kopierenden Zeilen -:param xdest: Der Spalten-Offset, der in diesem Bild geändert werden soll -:param ydest: Der Zeilen-Offset, der in diesem Bild geändert werden soll - -Pixels outside the source image are treated as having a brightness 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 blit( + self, + src: Image, + x: int, + y: int, + w: int, + h: int, + xdest: int = 0, + ydest: int = 0, + ) -> None: + """Copy an area from another image into this image. + + Example: ``my_image.blit(Image.HEART, 1, 1, 3, 3, 1, 1)`` + + :param src: The source image + :param x: The starting column offset in the source image + :param y: The starting row offset in the source image + :param w: The number of columns to copy + :param h: The number of rows to copy + :param xdest: The column offset to modify in this image + :param ydest: The row offset to modify in this image + + Pixels outside the source image are treated as having a brightness 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: - """Liefert eine kompakte Stringrepräsentation des Bildes.""" + """Get a compact string representation of the image.""" ... - def __str__(self) -> str: - """Liefert eine lesbare String-Repräsentation des Bildes.""" + """Get a readable string representation of the image.""" ... - def __add__(self, other: Image) -> Image: - """Erstellt ein neues Bild, indem für jedes Pixel die Helligkeitswerte der beiden Bilder addiert werden. + """Create a new image by adding the brightness values from the two + images for each pixel. -Example: ``Image.HEART + Image.HAPPY`` + Example: ``Image.HEART + Image.HAPPY`` -:param other: Das zu addierende Bild.""" + :param other: The image to add. + """ ... - def __sub__(self, other: Image) -> Image: - """Erstellt ein neues Bild, indem für jedes Pixel die Helligkeitswerte der beiden Bilder subtrahiert werden. + """Create a new image by subtracting the brightness values of the + other image from this image. -Example: ``Image.HEART - Image.HEART_SMALL`` + Example: ``Image.HEART - Image.HEART_SMALL`` -:param other: Das zu subtrahierende Bild.""" + :param other: The image to subtract. + """ ... - def __mul__(self, n: float) -> Image: - """Erstellt ein neues Bild, indem der Helligkeitswert jedes Pixels mit ``n`` multipliziert wird. + """Create a new image by multiplying the brightness of each pixel by + ``n``. -Example: ``Image.HEART * 0.5`` + Example: ``Image.HEART * 0.5`` -:param n: Der Wert, mit dem multipliziert werden soll.""" + :param n: The value to multiply by. + """ ... - def __truediv__(self, n: float) -> Image: - """Erstellt ein neues Bild, indem der Helligkeitswert jedes Pixels durch ``n`` dividiert wird. + """Create a new image by dividing the brightness of each pixel by + ``n``. -Example: ``Image.HEART / 2`` + Example: ``Image.HEART / 2`` -:param n: Der Wert, durch den dividiert werden soll.""" + :param n: The value to divide by. + """ ... class SoundEvent: LOUD: SoundEvent - """Stellt den Übergang von Klangereignissen von ``quiet`` auf ``loud`` dar; wie beim Klatschen oder Rufen.""" + """Represents the transition of sound events, from ``quiet`` to ``loud`` like clapping or shouting.""" + QUIET: SoundEvent - """Stellt den Übergang von akustischen Ereignissen, wie Sprechen oder Hintergrundmusik, von ``loud`` zu ``quiet`` dar. (stumm)""" + """Represents the transition of sound events, from ``loud`` to ``quiet`` like speaking or background music.""" class Sound: - """Die eingebauten Klänge können mit ``audio.play(Sound.NAME)`` aufgerufen werden.""" + """The built-in sounds can be called using ``audio.play(Sound.NAME)``.""" + GIGGLE: Sound - """Kichern-Sound.""" + """Giggling sound.""" + HAPPY: Sound - """Happy-Sound.""" + """Happy sound.""" + HELLO: Sound - """Begrüßung-Sound""" + """Greeting sound.""" + MYSTERIOUS: Sound - """Geheimnisvoll-Sound""" + """Mysterious sound.""" + SAD: Sound - """Traurig-Sound.""" + """Sad sound.""" + SLIDE: Sound - """Gleitender Ton.""" + """Sliding sound.""" + SOARING: Sound - """Aufsteigender Klang. (aufsteigend)""" + """Soaring sound.""" + SPRING: Sound - """Springfeder Klang (Sppringfeder)""" + """Spring sound.""" + TWINKLE: Sound - """Funkeln Klang (Funkeln)""" + """Twinkling sound.""" + YAWN: Sound - """Gähnen Klang""" \ No newline at end of file + """Yawning sound.""" diff --git a/lang/de/typeshed/stdlib/microbit/accelerometer.pyi b/lang/de/typeshed/stdlib/microbit/accelerometer.pyi index 3274570..bac82c0 100644 --- a/lang/de/typeshed/stdlib/microbit/accelerometer.pyi +++ b/lang/de/typeshed/stdlib/microbit/accelerometer.pyi @@ -1,103 +1,115 @@ -"""Messen Sie die Beschleunigung des micro:bit und erkennen Sie Gesten. (Beschleunigungssensor)""" +"""Measure the acceleration of the micro:bit and recognise gestures. +""" + from typing import Tuple def get_x() -> int: - """Erhalte die Beschleunigungsmessung in der ``x`` -Achse in Milli-g. + """Get the acceleration measurement in the ``x`` axis in milli-g. -Example: ``accelerometer.get_x()`` + Example: ``accelerometer.get_x()`` -:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" + :return: A positive or negative integer depending on direction in the range +/- 2000mg. + """ ... def get_y() -> int: - """Erhalte die Beschleunigungsmessung in der ``y`` -Achse in Milli-g. + """Get the acceleration measurement in the ``y`` axis in milli-g. -Example: ``accelerometer.get_y()`` + Example: ``accelerometer.get_y()`` -:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" + :return: A positive or negative integer depending on direction in the range +/- 2000mg. + """ ... def get_z() -> int: - """Erhalte die Beschleunigungsmessung in der ``z`` -Achse in Milli-g. + """Get the acceleration measurement in the ``z`` axis in milli-g. -Example: ``accelerometer.get_z()`` + Example: ``accelerometer.get_z()`` -:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" + :return: A positive or negative integer depending on direction in the range +/- 2000mg. + """ ... def get_values() -> Tuple[int, int, int]: - """Erhalten Sie die Beschleunigungsmessungen in allen Achsen auf einmal als Tupel. + """Get the acceleration measurements in all axes at once as a tuple. -Example: ``x, y, z = accelerometer.get_values()`` + Example: ``x, y, z = accelerometer.get_values()`` -:return: a three-element tuple of integers ordered as X, Y, Z, each value a positive or negative integer depending on direction in the range +/- 2000mg""" + :return: a three-element tuple of integers ordered as X, Y, Z, each value a positive or negative integer depending on direction in the range +/- 2000mg + """ ... def get_strength() -> int: - """Erhalte die Beschleunigungsmessung aller Achsen als positive Ganzzahl. Dies ist die euklidische Summe der X-, Y- und Z-Achsen. + """Get the acceleration measurement of all axes combined, as a positive integer. This is the Pythagorean sum of the X, Y and Z axes. -Example: ``accelerometer.get_strength()`` + Example: ``accelerometer.get_strength()`` -:return: The combined acceleration strength of all the axes, in milli-g.""" + :return: The combined acceleration strength of all the axes, in milli-g. + """ ... def current_gesture() -> str: - """Erhalte den Namen der aktuellen Geste. (derzeitige Geste) + """Get the name of the current gesture. -Example: ``accelerometer.current_gesture()`` + Example: ``accelerometer.current_gesture()`` -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. + 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. -:return: The current gesture""" + :return: The current gesture + """ ... def is_gesture(name: str) -> bool: - """Überprüft, ob die benannte Geste derzeit aktiv ist. (ist Geste) + """Check if the named gesture is currently active. -Example: ``accelerometer.is_gesture('shake')`` + Example: ``accelerometer.is_gesture('shake')`` -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. + 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. -:param name: Der Name der Geste. -:return: ``True`` if the gesture is active, ``False`` otherwise.""" + :param name: The gesture name. + :return: ``True`` if the gesture is active, ``False`` otherwise. + """ ... def was_gesture(name: str) -> bool: - """Überprüft, ob die benannte Geste seit dem letzten Aufruf aktiv war. (war Geste) + """Check if the named gesture was active since the last call. -Example: ``accelerometer.was_gesture('shake')`` + Example: ``accelerometer.was_gesture('shake')`` -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. + 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. -:param name: Der Name der Geste. -:return: ``True`` if the gesture was active since the last call, ``False`` otherwise.""" + :param name: The gesture name. + :return: ``True`` if the gesture was active since the last call, ``False`` otherwise. + """ def get_gestures() -> Tuple[str, ...]: - """Gibt ein Tupel der vergangenen Gesten zurück. + """Return a tuple of the gesture history. -Example: ``accelerometer.get_gestures()`` + Example: ``accelerometer.get_gestures()`` -Clears the gesture history before returning. + Clears the gesture history before returning. -Gestures are not updated in the background so there needs to be constant -calls to some accelerometer method to do the gesture detection. Usually -gestures can be detected using a loop with a small :func:`microbit.sleep` delay. + Gestures are not updated in the background so there needs to be constant + calls to some accelerometer method to do the gesture detection. Usually + gestures can be detected using a loop with a small :func:`microbit.sleep` delay. -:return: The history as a tuple, most recent last.""" + :return: The history as a tuple, most recent last. + """ ... def set_range(value: int) -> None: - """Legen Sie den Bereich des Beschleunigungsmessers in g (Fallbeschleunigung) auf den nächstgelegenen Wert fest, welcher von der Hardware unterstützt wird. Diese sind ``2``, ``4``oder ``8`` g. (Bereich einstellen) + """Set the accelerometer sensitivity range, in g (standard gravity), to the closest values supported by the hardware, so it rounds to either ``2``, ``4``, or ``8`` g. -Example: ``accelerometer.set_range(8)`` + Example: ``accelerometer.set_range(8)`` -:param value: (wert) Neuer Bereich für den Beschleunigungssensor, eine Ganzzahl in ``g``.""" \ No newline at end of file + :param value: New range for the accelerometer, an integer in ``g``. + """ diff --git a/lang/de/typeshed/stdlib/microbit/audio.pyi b/lang/de/typeshed/stdlib/microbit/audio.pyi index fad5da1..3b1e327 100644 --- a/lang/de/typeshed/stdlib/microbit/audio.pyi +++ b/lang/de/typeshed/stdlib/microbit/audio.pyi @@ -1,124 +1,160 @@ -"""Töne mit dem micro:bit abspielen (Importiere ``audio`` für V1-Kompatibilität). (Audio)""" +"""Play sounds using the micro:bit (import ``audio`` for V1 compatibility). +""" + from ..microbit import MicroBitDigitalPin, Sound, pin0 from typing import ClassVar, Iterable, Union -def play(source: Union[Iterable[AudioFrame], Sound, SoundEffect], wait: bool=True, pin: MicroBitDigitalPin=pin0, return_pin: Union[MicroBitDigitalPin, None]=None) -> None: - """Wiedergeben eines eingebauten Sounds, Soundeffekts oder benutzerdefinierten Aufnahme . +def play( + source: Union[Iterable[AudioFrame], Sound, SoundEffect], + wait: bool = True, + pin: MicroBitDigitalPin = pin0, + return_pin: Union[MicroBitDigitalPin, None] = None, +) -> None: + """Play a built-in sound, sound effect or custom audio frames. -Example: ``audio.play(Sound.GIGGLE)`` + Example: ``audio.play(Sound.GIGGLE)`` -:param source: (Quelle) Ein eingebauter ``Sound`` wie ``Sound.GIGGLE``, ein ``SoundEffect`` oder Beispieldaten als Teil eines ``AudioFrame`` Objekts. -:param wait: Wenn ``wait`` ``True`` ist, wird diese Funktion blockiert, bis der Klang abgeschlossen ist. -:param pin: Ein optionales Argument für den Ausgabepin kann angegeben werden, um die Standardeinstellung von ``pin0``zu überschreiben. Wenn kein Ton wiedergegeben werden soll, kann ``pin=None`` verwendet werden. -:param return_pin: Bestimmt einen Pin, mit dem der externen Lautsprecher anstatt mit Ground verbunden wird. Dies wird bei der **V2** Revision ignoriert.""" + :param source: A built-in ``Sound`` such as ``Sound.GIGGLE``, a ``SoundEffect`` or sample data as an iterable of ``AudioFrame`` objects. + :param wait: If ``wait`` is ``True``, this function will block until the sound is complete. + :param pin: An optional argument to specify the output pin can be used to override the default of ``pin0``. If we do not want any sound to play we can use ``pin=None``. + :param return_pin: Specifies a differential edge connector pin to connect to an external speaker instead of ground. This is ignored for the **V2** revision. + """ def is_playing() -> bool: - """Überprüfen Sie, ob ein Ton abgespielt wird. (spielt gerade) + """Check whether a sound is playing. -Example: ``audio.is_playing()`` + Example: ``audio.is_playing()`` -:return: ``True`` if audio is playing, otherwise ``False``.""" + :return: ``True`` if audio is playing, otherwise ``False``.""" ... def stop() -> None: - """Stoppe jede Audio-Wiedergabe. (Stop) + """Stop all audio playback. -Example: ``audio.stop()``""" + Example: ``audio.stop()`` + """ ... class SoundEffect: - """Ein Soundeffekt, zusammengestellt aus einer Reihe von Parametern, die über den Konstruktor oder durch Attribute konfiguriert werden.""" + """A sound effect, composed by a set of parameters configured via the constructor or attributes.""" + WAVEFORM_SINE: ClassVar[int] - """Sinuswelle als Parameter für ``waveform``. (Sinuswelle)""" + """Sine wave option used for the ``waveform`` parameter.""" + WAVEFORM_SAWTOOTH: ClassVar[int] - """Sägezahnkurve als Parameter für ``waveform``. (Sägezahnkurve)""" + """Sawtooth wave option used for the ``waveform`` parameter.""" + WAVEFORM_TRIANGLE: ClassVar[int] - """Dreiecksignal als Parameter für ``waveform``. (Dreiecksignal)""" + """Triangle wave option used for the ``waveform`` parameter.""" + WAVEFORM_SQUARE: ClassVar[int] - """Rechtecksignal als Parameter für ``waveform``. (Rechtecksignal)""" + """Square wave option used for the ``waveform`` parameter.""" + WAVEFORM_NOISE: ClassVar[int] - """Rauschsignal als Parameter für ``waveform``. (Rauschsignal)""" + """Noise option used for the ``waveform`` parameter.""" + SHAPE_LINEAR: ClassVar[int] - """Lineare Interpolation als Parameter für ``shape``. (lineare Interpolation)""" + """Linear interpolation option used for the ``shape`` parameter.""" + SHAPE_CURVE: ClassVar[int] - """Kurven-Interpolation als Parameter für ``shape``. (geschwungene Kurve)""" + """Curve interpolation option used for the ``shape`` parameter.""" + SHAPE_LOG: ClassVar[int] - """Logarithmische Interpolation als Parameter für ``shape``. (logarithmische Interpolation)""" + """Logarithmic interpolation option used for the ``shape`` parameter.""" + FX_NONE: ClassVar[int] - """Kein Effekt für ``fx`` verwendet. (kein fx)""" + """No effect option used for the ``fx`` parameter.""" + FX_TREMOLO: ClassVar[int] - """Tremelo-Effekt als Parameter für ``fx``. (fx Tremolo)""" + """Tremolo effect option used for the ``fx`` parameter.""" + FX_VIBRATO: ClassVar[int] - """Vibrato-Effekt als Parameter für ``fx``. (fx Vibrato)""" + """Vibrato effect option used for the ``fx`` parameter.""" + FX_WARBLE: ClassVar[int] - """Triller-Effekt als Parameter für ``fx``. (fx Trillereffekt)""" + """Warble effect option used for the ``fx`` parameter.""" + freq_start: int - """Startfrequenz in Hertz (Hz), eine Zahl zwischen ``0`` und ``9999`` (Startfrequenz)""" + """Start frequency in Hertz (Hz), a number between ``0`` and ``9999``""" + freq_end: int - """Endfrequenz in Hertz (Hz), eine Zahl zwischen ``0`` und ``9999`` (Endfrequenz)""" + """End frequency in Hertz (Hz), a number between ``0`` and ``9999``""" + duration: int - """Dauer des Klangs in Millisekunden, eine Zahl zwischen ``0`` und ``9999`` (Dauer)""" - vol_start: int - """Startlautstärke, eine Zahl zwischen ``0`` und ``255`` (vol Start)""" - vol_end: int - """Endlautstärke, eine Nummer zwischen ``0`` und ``255`` (vol Ende)""" - waveform: int - """Typ der Sinuswelle, einer dieser Werte: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (zufällig generiertes Geräusch)""" - fx: int - """Effekt, der dem Sound hinzugefügt werden soll, in Frage kommende Werte: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, oder ``FX_NONE``""" - shape: int - """Die Art der Interpolationskurve zwischen der Anfangs- und der Endfrequenz. Verschiedene Wellenformen haben unterschiedliche Frequenzänderungsraten. In Frage kommende Werte: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``""" + """Duration of the sound in milliseconds, a number between ``0`` and ``9999``""" - def __init__(self, freq_start: int=500, freq_end: int=2500, duration: int=500, vol_start: int=255, vol_end: int=0, waveform: int=WAVEFORM_SQUARE, fx: int=FX_NONE, shape: int=SHAPE_LOG): - """Erstelle einen neuen Soundeffekt. + vol_start: int + """Start volume value, a number between ``0`` and ``255``""" -Example: ``my_effect = SoundEffect(duration=1000)`` + vol_end: int + """End volume value, a number between ``0`` and ``255``""" -All the parameters are optional, with default values as shown above, and -they can all be modified via attributes of the same name. For example, we -can first create an effect ``my_effect = SoundEffect(duration=1000)``, -and then change its attributes ``my_effect.duration = 500``. + waveform: int + """Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise)""" -:param freq_start: (Startfrequenz) Startfrequenz in Hertz (Hz), eine Zahl zwischen ``0`` und ``9999``. -:param freq_end: (Endfrequenz) Endfrequenz in Hertz (Hz), eine Zahl zwischen ``0`` und ``9999``. -:param duration: (Dauer) Dauer des Tons in Millisekunden, eine Zahl zwischen ``0`` und ``9999``. -:param vol_start: (vol Start) Startlautstärke, eine Zahl zwischen ``0`` und ``255``. -:param vol_end: (vol Ende) Endlautstärke, eine Nummer zwischen ``0`` und ``255``. -:param waveform: Typ der Sinuswelle, einer dieser Werte: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (zufällig generiertes Geräusch). -:param fx: Effekt, der dem Sound hinzugefügt werden soll, in Frage kommende Werte: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, oder ``FX_NONE``. -:param shape: Die Art der Interpolationskurve zwischen der Anfangs- und der Endfrequenz. Verschiedene Wellenformen haben unterschiedliche Frequenzänderungsraten. In Frage kommende Werte: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``.""" + fx: int + """Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``""" + shape: int + """The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``""" + + def __init__( + self, + freq_start: int = 500, + freq_end: int = 2500, + duration: int = 500, + vol_start: int = 255, + vol_end: int = 0, + waveform: int = WAVEFORM_SQUARE, + fx: int = FX_NONE, + shape: int = SHAPE_LOG, + ): + """Create a new sound effect. + + Example: ``my_effect = SoundEffect(duration=1000)`` + + All the parameters are optional, with default values as shown above, and + they can all be modified via attributes of the same name. For example, we + can first create an effect ``my_effect = SoundEffect(duration=1000)``, + and then change its attributes ``my_effect.duration = 500``. + + :param freq_start: Start frequency in Hertz (Hz), a number between ``0`` and ``9999``. + :param freq_end: End frequency in Hertz (Hz), a number between ``0`` and ``9999``. + :param duration: Duration of the sound in milliseconds, a number between ``0`` and ``9999``. + :param vol_start: Start volume value, a number between ``0`` and ``255``. + :param vol_end: End volume value, a number between ``0`` and ``255``. + :param waveform: Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise). + :param fx: Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``. + :param shape: The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``. + """ def copy(self) -> SoundEffect: - """Erstelle eine Kopie dieses ``SoundEffect``. (kopieren) + """Create a copy of this ``SoundEffect``. -Example: ``sound_2 = sound_1.copy()`` + Example: ``sound_2 = sound_1.copy()`` -:return: A copy of the SoundEffect.""" + :return: A copy of the SoundEffect. + """ class AudioFrame: - """Ein ``AudioFrame``-Objekt ist eine Liste von 32 Samples, von denen jedes ein vorzeichenloses Byte ist -(ganze Zahl zwischen 0 und 255). + """An ``AudioFrame`` object is a list of 32 samples each of which is a unsigned byte + (whole number between 0 and 255). -It takes just over 4 ms to play a single frame. + It takes just over 4 ms to play a single frame. -Example:: + Example:: - frame = AudioFrame() - for i in range(len(frame)): - frame[i] = 252 - i * 8""" + frame = AudioFrame() + for i in range(len(frame)): + frame[i] = 252 - i * 8 + """ def copyfrom(self, other: AudioFrame) -> None: - """Überschreibe die Daten in diesem ``AudioFrame`` mit den Daten einer anderen ``AudioFrame`` Instanz. - -Example: ``my_frame.copyfrom(source_frame)`` - -:param other: ``AudioFrame`` Instanz von der die Daten kopiert werden sollen.""" - - def __len__(self) -> int: - ... + """Overwrite the data in this ``AudioFrame`` with the data from another ``AudioFrame`` instance. - def __setitem__(self, key: int, value: int) -> None: - ... + Example: ``my_frame.copyfrom(source_frame)`` - def __getitem__(self, key: int) -> int: - ... \ No newline at end of file + :param other: ``AudioFrame`` instance from which to copy the data. + """ + def __len__(self) -> int: ... + def __setitem__(self, key: int, value: int) -> None: ... + def __getitem__(self, key: int) -> int: ... diff --git a/lang/de/typeshed/stdlib/microbit/compass.pyi b/lang/de/typeshed/stdlib/microbit/compass.pyi index 6d515d9..c74a47b 100644 --- a/lang/de/typeshed/stdlib/microbit/compass.pyi +++ b/lang/de/typeshed/stdlib/microbit/compass.pyi @@ -1,70 +1,78 @@ -"""Benutze den eingebauten Kompass. (Kompass)""" +"""Use the built-in compass. +""" def calibrate() -> None: - """Startet den Kalibrierungsprozess. + """Starts the calibration process. -Example: ``compass.calibrate()`` + Example: ``compass.calibrate()`` -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.""" + 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: - """Überprüfe, dass der Kompass kalibriert ist. (ist kalibriert) + """Check is the compass is calibrated. -Example: ``compass.is_calibrated()`` + Example: ``compass.is_calibrated()`` -:return: ``True`` if the compass has been successfully calibrated, ``False`` otherwise.""" + :return: ``True`` if the compass has been successfully calibrated, ``False`` otherwise. + """ ... def clear_calibration() -> None: - """Setzt die Kalibrierung zurück, sodass der Kompass nicht mehr kalibriert ist. + """Undoes the calibration, making the compass uncalibrated again. -Example: ``compass.clear_calibration()``""" + Example: ``compass.clear_calibration()`` + """ ... def get_x() -> int: - """Liefert die Magnetfeldstärke der ``x``-Achse. + """Get the magnetic field strength on the ``x`` axis. -Example: ``compass.get_x()`` + Example: ``compass.get_x()`` -Call ``calibrate`` first or the results will be inaccurate. + Call ``calibrate`` first or the results will be inaccurate. -:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" + :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. + """ ... def get_y() -> int: - """Liefert die Magnetfeldstärke der ``y``-Achse. + """Get the magnetic field strength on the ``y`` axis. -Example: ``compass.get_y()`` + Example: ``compass.get_y()`` -Call ``calibrate`` first or the results will be inaccurate. + Call ``calibrate`` first or the results will be inaccurate. -:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" + :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. + """ ... def get_z() -> int: - """Liefert die Magnetfeldstärke der ``z``-Achse. + """Get the magnetic field strength on the ``z`` axis. -Example: ``compass.get_z()`` + Example: ``compass.get_z()`` -Call ``calibrate`` first or the results will be inaccurate. + Call ``calibrate`` first or the results will be inaccurate. -:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" + :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. + """ ... def heading() -> int: - """Ermittle die Kompassrichtung. (Ausrichtung) + """Get the compass heading. -Example: ``compass.heading()`` + Example: ``compass.heading()`` -:return: An integer in the range from 0 to 360, representing the angle in degrees, clockwise, with north as 0.""" + :return: An integer in the range from 0 to 360, representing the angle in degrees, clockwise, with north as 0. + """ ... def get_field_strength() -> int: - """Ermittle die Größe des Magnetfelds um das Gerät herum. + """Get the magnitude of the magnetic field around the device. -Example: ``compass.get_field_strength()`` + Example: ``compass.get_field_strength()`` -:return: An integer indication of the magnitude of the magnetic field in nano tesla.""" - ... \ No newline at end of file + :return: An integer indication of the magnitude of the magnetic field in nano tesla.""" + ... diff --git a/lang/de/typeshed/stdlib/microbit/display.pyi b/lang/de/typeshed/stdlib/microbit/display.pyi index bd6beb5..aa4013e 100644 --- a/lang/de/typeshed/stdlib/microbit/display.pyi +++ b/lang/de/typeshed/stdlib/microbit/display.pyi @@ -1,92 +1,115 @@ -"""Texte, Bilder und Animationen auf dem 5x5 LED-Display anzeigen. (Display)""" +"""Show text, images and animations on the 5×5 LED display. +""" + from ..microbit import Image from typing import Union, overload, Iterable def get_pixel(x: int, y: int) -> int: - """Ermittelt die Helligkeit der LED in Spalte ``x`` und Zeile ``y``. + """Get the brightness of the LED at column ``x`` and row ``y``. -Example: ``display.get_pixel(0, 0)`` + Example: ``display.get_pixel(0, 0)`` -:param x: Die Anzeige-Spalte (0..4) -:param y: Die Anzeigezeile (0..4) -:return: A number between 0 (off) and 9 (bright)""" + :param x: The display column (0..4) + :param y: The display row (0..4) + :return: A number between 0 (off) and 9 (bright) + """ ... def set_pixel(x: int, y: int, value: int) -> None: - """Stellt die Helligkeit der LED in Spalte ``x`` und Zeile ``y`` ein. + """Set the brightness of the LED at column ``x`` and row ``y``. -Example: ``display.set_pixel(0, 0, 9)`` + Example: ``display.set_pixel(0, 0, 9)`` -:param x: Die Anzeige-Spalte (0..4) -:param y: Die Anzeigezeile (0..4) -:param value: Die Helligkeit zwischen 0 (aus) und 9 (am hellsten)""" + :param x: The display column (0..4) + :param y: The display row (0..4) + :param value: The brightness between 0 (off) and 9 (bright) + """ ... def clear() -> None: - """Setzt die Helligkeit aller LEDs auf 0 (aus). + """Set the brightness of all LEDs to 0 (off). -Example: ``display.clear()``""" + Example: ``display.clear()`` + """ ... -def show(image: Union[str, float, int, Image, Iterable[Image]], delay: int=400, wait: bool=True, loop: bool=False, clear: bool=False) -> None: - """Zeigt Bilder, Buchstaben oder Ziffern auf der LED-Anzeige an. +def show( + image: Union[str, float, int, Image, Iterable[Image]], + delay: int = 400, + wait: bool = True, + loop: bool = False, + clear: bool = False, +) -> None: + """Shows images, letters or digits on the LED display. -Example: ``display.show(Image.HEART)`` + Example: ``display.show(Image.HEART)`` -When ``image`` is an image or a list of images then each image is displayed in turn. -If ``image`` is a string or number, each letter or digit is displayed in turn. + When ``image`` is an image or a list of images then each image is displayed in turn. + If ``image`` is a string or number, each letter or digit is displayed in turn. -:param image: Eine Zeichenkette, eine Zahl, ein Bild oder eine Liste von Bildern, die angezeigt werden sollen. -:param delay: Jeder Buchstabe, jede Ziffer oder jedes Bild wird mit einer Verzögerung von ``delay`` Millisekunden angezeigt. -:param wait: Wenn ``wait`` ``True`` ist, wird diese Funktion das Programm so lange anhalten, bis die Animation beendet ist, andernfalls wird die Animation im Hintergrund ausgeführt. -:param loop: Wenn ``loop`` ``True`` ist, wird die Animation endlos wiederholt. -:param clear: Wenn ``clear`` ``True`` ist, wird die Anzeige nach Beendigung der Sequenz gelöscht. + :param image: A string, number, image or list of images to show. + :param delay: Each letter, digit or image is shown with ``delay`` milliseconds between them. + :param wait: If ``wait`` is ``True``, this function will block until the animation is finished, otherwise the animation will happen in the background. + :param loop: If ``loop`` is ``True``, the animation will repeat forever. + :param clear: If ``clear`` is ``True``, the display will be cleared after the sequence has finished. -The ``wait``, ``loop`` and ``clear`` arguments must be specified using their keyword.""" + The ``wait``, ``loop`` and ``clear`` arguments must be specified using their keyword. + """ ... -def scroll(text: Union[str, float, int], delay: int=150, wait: bool=True, loop: bool=False, monospace: bool=False) -> None: - """Scrollt eine Zahl oder einen Text auf dem LED-Display. - -Example: ``display.scroll('micro:bit')`` - -:param text: Die zu scrollende Zeichenkette. Wenn ``text`` ein Integer oder Float ist, wird der Text vorher mit ``str()`` in einen String umgewandelt. -:param delay: Der Parameter ``delay`` bestimmt, wie schnell der Text gescrollt wird. -:param wait: Wenn ``wait`` ``True`` ist, wird diese Funktion das Programm anhalten, bis die Animation beendet ist, andernfalls läuft die Animation im Hintergrund ab. -:param loop: Wenn ``loop`` ``True`` ist, wird die Animation endlos wiederholt. -:param monospace: Wenn ``monospace`` ``True``ist, werden alle Zeichen 5 Pixel breit sein. Zwischen den Zeichen gibt es beim scrollen genau 1 leere Pixelspalte. - -The ``wait``, ``loop`` and ``monospace`` arguments must be specified -using their keyword.""" +def scroll( + text: Union[str, float, int], + delay: int = 150, + wait: bool = True, + loop: bool = False, + monospace: bool = False, +) -> None: + """Scrolls a number or text on the LED display. + + Example: ``display.scroll('micro:bit')`` + + :param text: The string to scroll. If ``text`` is an integer or float it is first converted to a string using ``str()``. + :param delay: The ``delay`` parameter controls how fast the text is scrolling. + :param wait: If ``wait`` is ``True``, this function will block until the animation is finished, otherwise the animation will happen in the background. + :param loop: If ``loop`` is ``True``, the animation will repeat forever. + :param monospace: 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. + + The ``wait``, ``loop`` and ``monospace`` arguments must be specified + using their keyword. + """ ... def on() -> None: - """Das LED-Display einschalten. + """Turn on the LED display. -Example: ``display.on()``""" + Example: ``display.on()`` + """ ... def off() -> None: - """Die LED-Anzeige ausschalten (Deaktivieren des Displays ermöglicht es dir, die GPIO-Pins für andere Zwecke zu verwenden). + """Turn off the LED display (disabling the display allows you to re-use the GPIO pins for other purposes). -Example: ``display.off()``""" + Example: ``display.off()`` + """ ... def is_on() -> bool: - """Überprüfung, ob die LED-Anzeige aktiviert ist. + """Check whether the LED display is enabled. -Example: ``display.is_on()`` + Example: ``display.is_on()`` -:return: ``True`` if the display is on, otherwise returns ``False``.""" + :return: ``True`` if the display is on, otherwise returns ``False``. + """ ... def read_light_level() -> int: - """Bestimmt die Lichtintensität. + """Read the light level. -Example: ``display.read_light_level()`` + Example: ``display.read_light_level()`` -Uses the display's LEDs in reverse-bias mode to sense the amount of light -falling on the display. + Uses the display's LEDs in reverse-bias mode to sense the amount of light + falling on the display. -:return: An integer between 0 and 255 representing the light level, with larger meaning more light.""" - ... \ No newline at end of file + :return: An integer between 0 and 255 representing the light level, with larger meaning more light. + """ + ... diff --git a/lang/de/typeshed/stdlib/microbit/i2c.pyi b/lang/de/typeshed/stdlib/microbit/i2c.pyi index 5258d5b..df26efa 100644 --- a/lang/de/typeshed/stdlib/microbit/i2c.pyi +++ b/lang/de/typeshed/stdlib/microbit/i2c.pyi @@ -1,49 +1,57 @@ -"""Kommunikation mit Geräten über das I2C-Busprotokoll.""" +"""Communicate with devices using the I²C bus protocol. +""" + from _typeshed import ReadableBuffer from ..microbit import MicroBitDigitalPin, pin19, pin20 from typing import List -def init(freq: int=100000, sda: MicroBitDigitalPin=pin20, scl: MicroBitDigitalPin=pin19) -> None: - """Eine Peripherie neu initialisieren. +def init( + freq: int = 100000, sda: MicroBitDigitalPin = pin20, scl: MicroBitDigitalPin = pin19 +) -> None: + """Re-initialize a peripheral. -Example: ``i2c.init()`` + Example: ``i2c.init()`` -:param freq: Taktfrequenz -:param sda: ``sda`` Pin (standardmäßig 20) -:param scl: ``scl`` Pin (standardmäßig 19) + :param freq: clock frequency + :param sda: ``sda`` pin (default 20) + :param scl: ``scl`` pin (default 19) -On a micro:bit V1 board, changing the I²C pins from defaults will make -the accelerometer and compass stop working, as they are connected -internally to those pins. This warning does not apply to the **V2** -revision of the micro:bit as this has `separate I²C lines `_ -for the motion sensors and the edge connector.""" + On a micro:bit V1 board, changing the I²C pins from defaults will make + the accelerometer and compass stop working, as they are connected + internally to those pins. This warning does not apply to the **V2** + revision of the micro:bit as this has `separate I²C lines `_ + for the motion sensors and the edge connector. + """ ... def scan() -> List[int]: - """Scannt den Bus nach Geräten. + """Scan the bus for devices. -Example: ``i2c.scan()`` + Example: ``i2c.scan()`` -:return: A list of 7-bit addresses corresponding to those devices that responded to the scan.""" + :return: A list of 7-bit addresses corresponding to those devices that responded to the scan. + """ ... -def read(addr: int, n: int, repeat: bool=False) -> bytes: - """Liest Bytes von einem Gerät.. +def read(addr: int, n: int, repeat: bool = False) -> bytes: + """Read bytes from a device. -Example: ``i2c.read(0x50, 64)`` + Example: ``i2c.read(0x50, 64)`` -:param addr: Die 7-Bit-Adresse des Geräts -:param n: Die Anzahl der zu lesenden Bytes -:param repeat: (wiederholen) Wenn ``True``wird kein Stop-Bit gesendet -:return: The bytes read""" + :param addr: The 7-bit address of the device + :param n: The number of bytes to read + :param repeat: If ``True``, no stop bit will be sent + :return: The bytes read + """ ... -def write(addr: int, buf: ReadableBuffer, repeat: bool=False) -> None: - """Schreibe Bytes auf ein Gerät. (schreiben) +def write(addr: int, buf: ReadableBuffer, repeat: bool = False) -> None: + """Write bytes to a device. -Example: ``i2c.write(0x50, bytes([1, 2, 3]))`` + Example: ``i2c.write(0x50, bytes([1, 2, 3]))`` -:param addr: Die 7-Bit-Adresse des Geräts -:param buf: Ein Puffer mit den zu schreibenden Bytes -:param repeat: (wiederholen) Wenn ``True``wird kein Stop-Bit gesendet""" - ... \ No newline at end of file + :param addr: The 7-bit address of the device + :param buf: A buffer containing the bytes to write + :param repeat: If ``True``, no stop bit will be sent + """ + ... diff --git a/lang/de/typeshed/stdlib/microbit/microphone.pyi b/lang/de/typeshed/stdlib/microbit/microphone.pyi index 2b09e41..68e8f3a 100644 --- a/lang/de/typeshed/stdlib/microbit/microphone.pyi +++ b/lang/de/typeshed/stdlib/microbit/microphone.pyi @@ -1,62 +1,70 @@ -"""Reagiere auf Ton mithilfe des integrierten Mikrofons (nur V2). (Mikrofon)""" +"""Respond to sound using the built-in microphone (V2 only). +""" + from typing import Optional, Tuple from ..microbit import SoundEvent def current_event() -> Optional[SoundEvent]: - """Abrufen des letzten aufgezeichneten Sound-Ereignisses + """Get the last recorded sound event -Example: ``microphone.current_event()`` + Example: ``microphone.current_event()`` -:return: The event, ``SoundEvent('loud')`` or ``SoundEvent('quiet')``.""" + :return: The event, ``SoundEvent('loud')`` or ``SoundEvent('quiet')``. + """ ... def was_event(event: SoundEvent) -> bool: - """Überprüfung, ob seit dem letzten Anruf mindestens einmal ein Geräusch gehört wurde. + """Check if a sound was heard at least once since the last call. -Example: ``microphone.was_event(SoundEvent.LOUD)`` + Example: ``microphone.was_event(SoundEvent.LOUD)`` -This call clears the sound history before returning. + This call clears the sound history before returning. -:param event: Das Ereignis, auf das geprüft werden soll, z. B. ``SoundEvent.LOUD`` oder ``SoundEvent.QUIET`` -:return: ``True`` if sound was heard at least once since the last call, otherwise ``False``.""" + :param event: The event to check for, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET`` + :return: ``True`` if sound was heard at least once since the last call, otherwise ``False``. + """ ... def is_event(event: SoundEvent) -> bool: - """Überprüfe das zuletzt erkannte Sound-Ereignis. + """Check the most recent sound event detected. -Example: ``microphone.is_event(SoundEvent.LOUD)`` + Example: ``microphone.is_event(SoundEvent.LOUD)`` -This call does not clear the sound event history. + This call does not clear the sound event history. -:param event: Das Ereignis, auf das geprüft werden soll, z. B. ``SoundEvent.LOUD`` oder ``SoundEvent.QUIET`` -:return: ``True`` if sound was the most recent heard, ``False`` otherwise.""" + :param event: The event to check for, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET`` + :return: ``True`` if sound was the most recent heard, ``False`` otherwise. + """ ... def get_events() -> Tuple[SoundEvent, ...]: - """Liefert den Verlauf der Sound-Ereignisse in Form eines Tupels. + """Get the sound event history as a tuple. -Example: ``microphone.get_events()`` + Example: ``microphone.get_events()`` -This call clears the sound history before returning. + This call clears the sound history before returning. -:return: A tuple of the event history with the most recent event last.""" + :return: A tuple of the event history with the most recent event last. + """ ... def set_threshold(event: SoundEvent, value: int) -> None: - """Legt den Schwellenwert für ein Sound-Ereignis fest. + """Set the threshold for a sound event. -Example: ``microphone.set_threshold(SoundEvent.LOUD, 250)`` + Example: ``microphone.set_threshold(SoundEvent.LOUD, 250)`` -A high threshold means the event will only trigger if the sound is very loud (>= 250 in the example). + A high threshold means the event will only trigger if the sound is very loud (>= 250 in the example). -:param event: Ein Sound-Ereignis, wie ``SoundEvent.LOUD`` oder ``SoundEvent.QUIET``. -:param value: (wert) Der Schwellenwert im Bereich 0-255.""" + :param event: A sound event, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET``. + :param value: The threshold level in the range 0-255. + """ ... def sound_level() -> int: - """Ermittle den Schalldruckpegel. (Lautstärke) + """Get the sound pressure level. -Example: ``microphone.sound_level()`` + Example: ``microphone.sound_level()`` -:return: A representation of the sound pressure level in the range 0 to 255.""" - ... \ No newline at end of file + :return: A representation of the sound pressure level in the range 0 to 255. + """ + ... diff --git a/lang/de/typeshed/stdlib/microbit/speaker.pyi b/lang/de/typeshed/stdlib/microbit/speaker.pyi index 205091c..5a74a4d 100644 --- a/lang/de/typeshed/stdlib/microbit/speaker.pyi +++ b/lang/de/typeshed/stdlib/microbit/speaker.pyi @@ -1,15 +1,18 @@ -"""Steuere den integrierten Lautsprecher (nur V2). (Lautsprecher)""" +"""Control the built-in speaker (V2 only). +""" def off() -> None: - """Lautsprecher ausschalten. + """Turn the speaker off. -Example: ``speaker.off()`` + Example: ``speaker.off()`` -This does not disable sound output to an edge connector pin.""" + This does not disable sound output to an edge connector pin. + """ ... def on() -> None: - """Lautsprecher einschalten. + """Turn the speaker on. -Example: ``speaker.on()``""" - ... \ No newline at end of file + Example: ``speaker.on()`` + """ + ... diff --git a/lang/de/typeshed/stdlib/microbit/spi.pyi b/lang/de/typeshed/stdlib/microbit/spi.pyi index 47bde2c..09c4046 100644 --- a/lang/de/typeshed/stdlib/microbit/spi.pyi +++ b/lang/de/typeshed/stdlib/microbit/spi.pyi @@ -1,47 +1,60 @@ -"""Kommunikation mit Geräten über die serielle Schnittstelle (SPI).""" +"""Communicate with devices using the serial peripheral interface (SPI) bus. +""" + from _typeshed import ReadableBuffer, WriteableBuffer from ..microbit import pin13, pin14, pin15, MicroBitDigitalPin -def init(baudrate: int=1000000, bits: int=8, mode: int=0, sclk: MicroBitDigitalPin=pin13, mosi: MicroBitDigitalPin=pin15, miso: MicroBitDigitalPin=pin14) -> None: - """SPI-Kommunikation initialisieren. - -Example: ``spi.init()`` - -For correct communication, the parameters have to be the same on both communicating devices. - -:param baudrate: Die Übertragungsgeschwindigkeit. -:param bits: Die Breite in Bits jeder Übertragung. Derzeit wird nur ``bits=8`` unterstützt. Dies kann sich jedoch in Zukunft ändern. -:param mode: Legt die Kombination aus Taktpolarität und Phase fest - `siehe Online-Tabelle `_. -:param sclk: SCLK Pin (standardmäßig 13) -:param mosi: MOSI Pin (standardmäßig 15) -:param miso: miso pin (Voreinstellung 14)""" +def init( + baudrate: int = 1000000, + bits: int = 8, + mode: int = 0, + sclk: MicroBitDigitalPin = pin13, + mosi: MicroBitDigitalPin = pin15, + miso: MicroBitDigitalPin = pin14, +) -> None: + """Initialize SPI communication. + + Example: ``spi.init()`` + + For correct communication, the parameters have to be the same on both communicating devices. + + :param baudrate: The speed of communication. + :param bits: The width in bits of each transfer. Currently only ``bits=8`` is supported. However, this may change in the future. + :param mode: Determines the combination of clock polarity and phase - `see online table `_. + :param sclk: sclk pin (default 13) + :param mosi: mosi pin (default 15) + :param miso: miso pin (default 14) + """ ... -def read(nbytes: int, out: int=0) -> bytes: - """Bytes lesen. +def read(nbytes: int, out: int = 0) -> bytes: + """Read at most ``nbytes`` while continuously writing the single byte given by ``out``. -Example: ``spi.read(64)`` + Example: ``spi.read(64)`` -:param nbytes: Maximum der zu lesenden Bytes. -:param out: The byte value to write (default 0). -:return: The bytes read.""" + :param nbytes: Maximum number of bytes to read. + :param out: The byte value to write (default 0). + :return: The bytes read. + """ ... def write(buffer: ReadableBuffer) -> None: - """Schreibe Bytes auf den Bus. (schreiben) + """Write bytes to the bus. -Example: ``spi.write(bytes([1, 2, 3]))`` + Example: ``spi.write(bytes([1, 2, 3]))`` -:param buffer: (Puffer) Ein Puffer, von dem Daten gelesen werden.""" + :param buffer: A buffer to read data from. + """ ... def write_readinto(out: WriteableBuffer, in_: ReadableBuffer) -> None: - """Schreibe den ``out`` Zwischenspeicher (Buffer) auf den Bus und lies jede Antwort in den ``in_`` Buffer. + """Write the ``out`` buffer to the bus and read any response into the ``in_`` buffer. -Example: ``spi.write_readinto(out_buffer, in_buffer)`` + Example: ``spi.write_readinto(out_buffer, in_buffer)`` -The length of the buffers should be the same. The buffers can be the same object. + The length of the buffers should be the same. The buffers can be the same object. -:param out: Der Puffer, in den eine Antwort geschrieben werden soll. -:param in_: Der Puffer, von dem Daten gelesen werden.""" - ... \ No newline at end of file + :param out: The buffer to write any response to. + :param in_: The buffer to read data from. + """ + ... diff --git a/lang/de/typeshed/stdlib/microbit/uart.pyi b/lang/de/typeshed/stdlib/microbit/uart.pyi index 979692c..2ab650f 100644 --- a/lang/de/typeshed/stdlib/microbit/uart.pyi +++ b/lang/de/typeshed/stdlib/microbit/uart.pyi @@ -1,79 +1,96 @@ -"""Verbindet mit einem Gerät über eine serielle Schnittstelle.""" +"""Communicate with a device using a serial interface. +""" + from _typeshed import WriteableBuffer from ..microbit import MicroBitDigitalPin from typing import Optional, Union -ODD: int -"""Ungerade Parität""" -EVEN: int -"""Gerade Parität (gerade)""" - -def init(baudrate: int=9600, bits: int=8, parity: Optional[int]=None, stop: int=1, tx: Optional[MicroBitDigitalPin]=None, rx: Optional[MicroBitDigitalPin]=None) -> None: - """Initialisiere die serielle Kommunikation. - -Example: ``uart.init(115200, tx=pin0, rx=pin1)`` -:param baudrate: (Baudrate) Die Übertragungsgeschwindigkeit. -:param bits: (Bits) Die Größe der Bytes die übertragen werden. micro:bit unterstützt nur 8. -:param parity: (Parität) Wie Parität geprüft wird, ``None``, ``uart.ODD`` oder ``uart.EVEN``. -:param stop: (Stop) Die Anzahl der Stopbits, muss 1 für micro:bit sein. -:param tx: Sendepin. -:param rx: Empfangspin. - -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. +ODD: int +"""Odd parity""" -For more details see `the online documentation `_.""" +EVEN: int +"""Even parity""" + +def init( + baudrate: int = 9600, + bits: int = 8, + parity: Optional[int] = None, + stop: int = 1, + tx: Optional[MicroBitDigitalPin] = None, + rx: Optional[MicroBitDigitalPin] = None, +) -> None: + """Initialize serial communication. + + Example: ``uart.init(115200, tx=pin0, rx=pin1)`` + + :param baudrate: The speed of communication. + :param bits: The size of bytes being transmitted. micro:bit only supports 8. + :param parity: How parity is checked, ``None``, ``uart.ODD`` or ``uart.EVEN``. + :param stop: The number of stop bits, has to be 1 for micro:bit. + :param tx: Transmitting pin. + :param rx: Receiving pin. + + 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. + + For more details see `the online documentation `_. + """ ... def any() -> bool: - """Überprüfen Sie, ob irgendwelche Daten warten. + """Check if any data is waiting. -Example: ``uart.any()`` + Example: ``uart.any()`` -:return: ``True`` if any data is waiting, else ``False``.""" + :return: ``True`` if any data is waiting, else ``False``. + """ ... -def read(nbytes: Optional[int]=None) -> Optional[bytes]: - """Bytes lesen. +def read(nbytes: Optional[int] = None) -> Optional[bytes]: + """Read bytes. -Example: ``uart.read()`` + Example: ``uart.read()`` -:param nbytes: Wenn ``nbytes`` angegeben ist, werden höchstens so viele Bytes gelesen. Andernfalls werden so viele Bytes wie möglich gelesen. -:return: A bytes object or ``None`` on timeout""" + :param nbytes: If ``nbytes`` is specified then read at most that many bytes, otherwise read as many bytes as possible + :return: A bytes object or ``None`` on timeout + """ ... -def readinto(buf: WriteableBuffer, nbytes: Optional[int]=None) -> Optional[int]: - """Lese Bytes in ``buf``. +def readinto(buf: WriteableBuffer, nbytes: Optional[int] = None) -> Optional[int]: + """Read bytes into the ``buf``. -Example: ``uart.readinto(input_buffer)`` + Example: ``uart.readinto(input_buffer)`` -:param buf: Der Puffer, in den geschrieben werden soll. -:param nbytes: Wenn ``nbytes`` angegeben ist, werden höchstens so viele Bytes gelesen. Andernfalls werden ``len(buf)`` Bytes gelesen. -:return: number of bytes read and stored into ``buf`` or ``None`` on timeout.""" + :param buf: The buffer to write to. + :param nbytes: If ``nbytes`` is specified then read at most that many bytes, otherwise read ``len(buf)`` bytes. + :return: number of bytes read and stored into ``buf`` or ``None`` on timeout. + """ ... def readline() -> Optional[bytes]: - """Liest eine Zeile bis zum Zeilenumbruch. + """Read a line, ending in a newline character. -Example: ``uart.readline()`` + Example: ``uart.readline()`` -:return: The line read or ``None`` on timeout. The newline character is included in the returned bytes.""" + :return: The line read or ``None`` on timeout. The newline character is included in the returned bytes. + """ ... def write(buf: Union[bytes, str]) -> Optional[int]: - """Schreibt einen Puffer auf den Bus. (schreiben) + """Write a buffer to the bus. -Example: ``uart.write('hello world')`` + Example: ``uart.write('hello world')`` -:param buf: Ein Byte-Objekt oder ein String. -:return: The number of bytes written, or ``None`` on timeout. + :param buf: A bytes object or a string. + :return: The number of bytes written, or ``None`` on timeout. -Examples:: + Examples:: - uart.write('hello world') - uart.write(b'hello world') - uart.write(bytes([1, 2, 3]))""" - ... \ No newline at end of file + uart.write('hello world') + uart.write(b'hello world') + uart.write(bytes([1, 2, 3])) + """ + ... diff --git a/lang/de/typeshed/stdlib/micropython.pyi b/lang/de/typeshed/stdlib/micropython.pyi index 78b3834..7a6079f 100644 --- a/lang/de/typeshed/stdlib/micropython.pyi +++ b/lang/de/typeshed/stdlib/micropython.pyi @@ -1,131 +1,144 @@ -"""MicroPython Grundlagen.""" +"""MicroPython internals.""" + from typing import Any, TypeVar, overload -_T = TypeVar('_T') + +_T = TypeVar("_T") def const(expr: _T) -> _T: - """Wird verwendet, um zu deklarieren, dass der Ausdruck eine Konstante ist, damit der Compiler ihn optimieren kann. + """Used to declare that the expression is a constant so that the compiler can + optimise it. -The use of this function should be as follows:: + The use of this function should be as follows:: - from micropython import const - CONST_X = const(123) - CONST_Y = const(2 * CONST_X + 1) + from micropython import const + CONST_X = const(123) + CONST_Y = const(2 * CONST_X + 1) -Constants declared this way are still accessible as global variables from -outside the module they are declared in. On the other hand, if a constant -begins with an underscore then it is hidden, it is not available as a -global variable, and does not take up any memory during execution. + Constants declared this way are still accessible as global variables from + outside the module they are declared in. On the other hand, if a constant + begins with an underscore then it is hidden, it is not available as a + global variable, and does not take up any memory during execution. -:param expr: Ein konstant bleibender Ausdruck.""" + :param expr: A constant expression. + """ ... @overload def opt_level() -> int: - """Ermittelt die aktuelle Optimierungsstufe für die Kompilierung von Skripten. + """Get the current optimisation level for the compilation of scripts. -Example: ``micropython.opt_level()`` + Example: ``micropython.opt_level()`` -The optimisation level controls the following compilation features: + The optimisation level controls the following compilation features: -- Assertions: at level 0 assertion statements are enabled and compiled - into the bytecode; at levels 1 and higher assertions are not compiled. + - Assertions: at level 0 assertion statements are enabled and compiled + into the bytecode; at levels 1 and higher assertions are not compiled. -- Built-in ``__debug__`` variable: at level 0 this variable expands to - True; at levels 1 and higher it expands to False. + - Built-in ``__debug__`` variable: at level 0 this variable expands to + True; at levels 1 and higher it expands to False. -- Source-code line numbers: at levels 0, 1 and 2 source-code line number - are stored along with the bytecode so that exceptions can report the - line number they occurred at; at levels 3 and higher line numbers are - not stored. + - Source-code line numbers: at levels 0, 1 and 2 source-code line number + are stored along with the bytecode so that exceptions can report the + line number they occurred at; at levels 3 and higher line numbers are + not stored. -:return: An integer representing the current level.""" + :return: An integer representing the current level. + """ ... @overload def opt_level(level: int) -> None: - """Legt die Optimierungsstufe für die nachfolgende Kompilierung von Skripten fest. + """Sets the optimisation level for subsequent compilation of scripts. -Example: ``micropython.opt_level(1)`` + Example: ``micropython.opt_level(1)`` -The optimisation level controls the following compilation features: + The optimisation level controls the following compilation features: -- Assertions: at level 0 assertion statements are enabled and compiled - into the bytecode; at levels 1 and higher assertions are not compiled. + - Assertions: at level 0 assertion statements are enabled and compiled + into the bytecode; at levels 1 and higher assertions are not compiled. -- Built-in ``__debug__`` variable: at level 0 this variable expands to - True; at levels 1 and higher it expands to False. + - Built-in ``__debug__`` variable: at level 0 this variable expands to + True; at levels 1 and higher it expands to False. -- Source-code line numbers: at levels 0, 1 and 2 source-code line number - are stored along with the bytecode so that exceptions can report the - line number they occurred at; at levels 3 and higher line numbers are - not stored. + - Source-code line numbers: at levels 0, 1 and 2 source-code line number + are stored along with the bytecode so that exceptions can report the + line number they occurred at; at levels 3 and higher line numbers are + not stored. -The default optimisation level is usually level 0. + The default optimisation level is usually level 0. -:param level: Eine ganzzahlige Optimierungsstufe.""" + :param level: An integer optimisation level. + """ ... -def mem_info(verbose: Any=None) -> None: - """Gibt Informationen über den aktuell verwendeten Speicher zurück. +def mem_info(verbose: Any = None) -> None: + """Print information about currently used memory. -Example: ``micropython.mem_info()`` + Example: ``micropython.mem_info()`` -:param verbose: Wenn das Argument ``verbose`` angegeben wird, werden zusätzliche Informationen ausgegeben.""" + :param verbose: If the ``verbose`` argument is given then extra information is printed. + """ ... -def qstr_info(verbose: Any=None) -> None: - """Gibt Informationen zu aktuell eingebetteten Strings zurück. +def qstr_info(verbose: Any = None) -> None: + """Print information about currently interned strings. -Example: ``micropython.qstr_info()`` + Example: ``micropython.qstr_info()`` -:param verbose: Wenn das Argument ``verbose`` angegeben wird, werden zusätzliche Informationen ausgegeben. + :param verbose: If the ``verbose`` argument is given then extra information is printed. -The information that is printed is implementation dependent, but currently -includes the number of interned strings and the amount of RAM they use. In -verbose mode it prints out the names of all RAM-interned strings.""" + The information that is printed is implementation dependent, but currently + includes the number of interned strings and the amount of RAM they use. In + verbose mode it prints out the names of all RAM-interned strings. + """ ... def stack_use() -> int: - """Gibt einen Integerwert zurück, der dem aktuell verwendeten Stack-Speicher entspricht. + """Return an integer representing the current amount of stack that is being + used. -Example: ``micropython.stack_use()`` + Example: ``micropython.stack_use()`` -The absolute value of this is not particularly useful, rather it -should be used to compute differences in stack usage at different points. + The absolute value of this is not particularly useful, rather it + should be used to compute differences in stack usage at different points. -:return: An integer representing current stack use.""" + :return: An integer representing current stack use. + """ ... def heap_lock() -> None: - """Heap-Speicher sperren. + """Lock the heap. -Example: ``micropython.heap_lock()`` + Example: ``micropython.heap_lock()`` -When locked no memory allocation can occur and a ``MemoryError`` will be -raised if any heap allocation is attempted.""" + When locked no memory allocation can occur and a ``MemoryError`` will be + raised if any heap allocation is attempted. + """ ... def heap_unlock() -> None: - """Heap-Speicher entsperren. + """Unlock the heap. -Example: ``micropython.heap_unlock()`` + Example: ``micropython.heap_unlock()`` -When locked no memory allocation can occur and a ``MemoryError`` will be -raised if any heap allocation is attempted.""" + When locked no memory allocation can occur and a ``MemoryError`` will be + raised if any heap allocation is attempted. + """ ... def kbd_intr(chr: int) -> None: - """Zeichen festlegen, das eine ``KeyboardInterrupt``-Exception auslöst. + """Set the character that will raise a ``KeyboardInterrupt`` exception. -Example: ``micropython.kbd_intr(-1)`` + Example: ``micropython.kbd_intr(-1)`` -:param chr: Zeichencode, um den Interrupt auszulösen, oder -1, um die Erfassung von Ctrl-C zu deaktivieren. + :param chr: Character code to raise the interrupt or -1 to disable capture of Ctrl-C. -By default this is set to 3 during script execution, corresponding to Ctrl-C. -Passing -1 to this function will disable capture of Ctrl-C, and passing 3 -will restore it. + By default this is set to 3 during script execution, corresponding to Ctrl-C. + Passing -1 to this function will disable capture of Ctrl-C, and passing 3 + will restore it. -This function can be used to prevent the capturing of Ctrl-C on the -incoming stream of characters that is usually used for the REPL, in case -that stream is used for other purposes.""" - ... \ No newline at end of file + This function can be used to prevent the capturing of Ctrl-C on the + incoming stream of characters that is usually used for the REPL, in case + that stream is used for other purposes. + """ + ... diff --git a/lang/de/typeshed/stdlib/music.pyi b/lang/de/typeshed/stdlib/music.pyi index 7204b55..5f4778b 100644 --- a/lang/de/typeshed/stdlib/music.pyi +++ b/lang/de/typeshed/stdlib/music.pyi @@ -1,128 +1,167 @@ -"""Erstelle und spiele Lieder. (Musik)""" +"""Create and play melodies. +""" from typing import Optional, Tuple, Union, List + from .microbit import MicroBitDigitalPin, pin0 + DADADADUM: Tuple[str, ...] -"""Melodie: der Anfang von Beethovens 5. Symphonie in c-Moll. (dadadadaam)""" +"""Melody: the opening to Beethoven’s 5th Symphony in C minor.""" + ENTERTAINER: Tuple[str, ...] -"""Melodie: die ersten Takte des Ragtime-Klassikers "The Entertainer" von Scott Joplin. (Entertainer)""" +"""Melody: the opening fragment of Scott Joplin’s Ragtime classic “The Entertainer”.""" + PRELUDE: Tuple[str, ...] -"""Melodie: Beginn des ersten Präludiums in C-Dur der 48 Präludien und Fugen von J.S. Bach.""" +"""Melody: the opening of the first Prelude in C Major of J.S.Bach’s 48 Preludes and Fugues.""" + ODE: Tuple[str, ...] -"""Melodie: Die „Ode an die Freude“ von Beethovens neunter Symphonie in d-Moll. (Ode)""" +"""Melody: the “Ode to Joy” theme from Beethoven’s 9th Symphony in D minor.""" + NYAN: Tuple[str, ...] -"""Melodie: Die Nyan-Katze (http://www.nyan.cat/) (Nyan) +"""Melody: the Nyan Cat theme (http://www.nyan.cat/). The composer is unknown. This is fair use for educational porpoises (as they say in New York).""" + RINGTONE: Tuple[str, ...] -"""Melodie: Etwas das wie ein Handy-Klingelton klingt. (Klingelton) +"""Melody: something that sounds like a mobile phone ringtone. To be used to indicate an incoming message. """ + FUNK: Tuple[str, ...] -"""Melodie: eine funkige Basslinie für Geheimagenten und Superschurken. (Funk)""" +"""Melody: a funky bass line for secret agents and criminal masterminds.""" + BLUES: Tuple[str, ...] -"""Melodie: ein 12-taktiger Boogie-Woogie-Blues mit Walking Bass. (Blues)""" +"""Melody: a boogie-woogie 12-bar blues walking bass.""" + BIRTHDAY: Tuple[str, ...] -"""Melodie: „Alles Gute zum Geburtstag…“ (Geburtstag) +"""Melody: “Happy Birthday to You…” For copyright status see: http://www.bbc.co.uk/news/world-us-canada-34332853 """ + WEDDING: Tuple[str, ...] -"""Melodie: der Hochzeitschor aus Wagners Oper "Lohengrin". (Hochzeit)""" +"""Melody: the bridal chorus from Wagner’s opera “Lohengrin”.""" + FUNERAL: Tuple[str, ...] -"""Melodie: der "Trauermarsch", auch bekannt als Frédéric Chopins Klaviersonate Nr. 2 in b-Moll, op. 35. (Beerdigung)""" +"""Melody: the “funeral march” otherwise known as Frédéric Chopin’s Piano Sonata No. 2 in B♭ minor, Op. 35.""" + PUNCHLINE: Tuple[str, ...] -"""Melodie: ein lustiges Fragment, das anzeigt, dass ein Scherz gemacht worden ist.""" +"""Melody: a fun fragment that signifies a joke has been made.""" + PYTHON: Tuple[str, ...] -"""Melodie: John Philip Sousas Marsch "Liberty Bell", auch bekannt als das Thema von "Monty Python's Flying Circus" (nach dem die Programmiersprache Python benannt ist).""" +"""Melody: John Philip Sousa’s march “Liberty Bell” aka, the theme for “Monty Python’s Flying Circus” (after which the Python programming language is named).""" + BADDY: Tuple[str, ...] -"""Melodie: Auftritt eines Stummfilm-Bösewichts.""" +"""Melody: silent movie era entrance of a baddy.""" + CHASE: Tuple[str, ...] -"""Melodie: Stummfilm-Verfolgungsszene.""" +"""Melody: silent movie era chase scene.""" + BA_DING: Tuple[str, ...] -"""Melodie: ein kurzes Signal, um anzuzeigen, dass etwas passiert ist.""" +"""Melody: a short signal to indicate something has happened.""" + WAWAWAWAA: Tuple[str, ...] -"""Melody: Eine sehr traurige Posaune.""" +"""Melody: a very sad trombone.""" + JUMP_UP: Tuple[str, ...] -"""Melodie: zur Verwendung in einem Spiel, um eine Aufwärtsbewegung zu untermalen.""" +"""Melody: for use in a game, indicating upward movement.""" + JUMP_DOWN: Tuple[str, ...] -"""Melodie: zur Verwendung in einem Spiel, um eine Abwärtsbewegung zu untermalen.""" +"""Melody: for use in a game, indicating downward movement.""" + POWER_UP: Tuple[str, ...] -"""Melodie: eine Fanfare, die einen Erfolg anzeigt oder dass etwas freigeschalten wurde.""" +"""Melody: a fanfare to indicate an achievement unlocked.""" + POWER_DOWN: Tuple[str, ...] -"""Melodie: eine traurige Fanfare, wenn etwas nicht geklappt hat.""" +"""Melody: a sad fanfare to indicate an achievement lost.""" -def set_tempo(ticks: int=4, bpm: int=120) -> None: - """Legt das ungefähre Tempo für die Wiedergabe fest. +def set_tempo(ticks: int = 4, bpm: int = 120) -> None: + """Sets the approximate tempo for playback. -Example: ``music.set_tempo(bpm=120)`` + Example: ``music.set_tempo(bpm=120)`` -:param ticks: Die Anzahl der Ticks in einem Beat. -:param bpm: Ein Integerwert, der die Beats pro Minute angibt. + :param ticks: The number of ticks constituting a beat. + :param bpm: An integer determining how many beats per minute. -Suggested default values allow the following useful behaviour: + Suggested default values allow the following useful behaviour: -- music.set_tempo() – reset the tempo to default of ticks = 4, bpm = 120 -- music.set_tempo(ticks=8) – change the “definition” of a beat -- music.set_tempo(bpm=180) – just change the tempo + - music.set_tempo() – reset the tempo to default of ticks = 4, bpm = 120 + - music.set_tempo(ticks=8) – change the “definition” of a beat + - music.set_tempo(bpm=180) – just change the tempo -To work out the length of a tick in milliseconds is very simple arithmetic: -60000/bpm/ticks_per_beat. For the default values that’s -60000/120/4 = 125 milliseconds or 1 beat = 500 milliseconds.""" + To work out the length of a tick in milliseconds is very simple arithmetic: + 60000/bpm/ticks_per_beat. For the default values that’s + 60000/120/4 = 125 milliseconds or 1 beat = 500 milliseconds. + """ ... def get_tempo() -> Tuple[int, int]: - """Gibt das aktuelle Tempo als Tupel von Integerwerten zurück: ``(ticks, bpm)``. + """Gets the current tempo as a tuple of integers: ``(ticks, bpm)``. -Example: ``ticks, beats = music.get_tempo()`` + Example: ``ticks, beats = music.get_tempo()`` -:return: The temp as a tuple with two integer values, the ticks then the beats per minute.""" + :return: The temp as a tuple with two integer values, the ticks then the beats per minute. + """ ... -def play(music: Union[str, List[str], Tuple[str, ...]], pin: Optional[MicroBitDigitalPin]=pin0, wait: bool=True, loop: bool=False) -> None: - """Spielt Musik. +def play( + music: Union[str, List[str], Tuple[str, ...]], + pin: Optional[MicroBitDigitalPin] = pin0, + wait: bool = True, + loop: bool = False, +) -> None: + """Plays music. -Example: ``music.play(music.NYAN)`` + Example: ``music.play(music.NYAN)`` -:param music: (Musik) Musik, die in `einer speziellen Notation `_ angegeben ist -:param pin: der Ausgangspin zur Verwendung mit einem externen Lautsprecher (Voreinstellung ``pin0``), ``None`` für keinen Ton. -:param wait: Wenn ``wait`` auf ``True`` gesetzt ist, stoppt diese Funktion die weitere Codeausführung. -:param loop: Wenn ``loop`` auf ``True`` gesetzt ist, wird die Melodie wiederholt, bis ``stop`` aufgerufen oder der blockierende Aufruf unterbrochen wird. + :param music: music specified in `a special notation `_ + :param pin: the output pin for use with an external speaker (default ``pin0``), ``None`` for no sound. + :param wait: If ``wait`` is set to ``True``, this function is blocking. + :param loop: If ``loop`` is set to ``True``, the tune repeats until ``stop`` is called or the blocking call is interrupted. -Many built-in melodies are defined in this module.""" + Many built-in melodies are defined in this module. + """ ... -def pitch(frequency: int, duration: int=-1, pin: Optional[MicroBitDigitalPin]=pin0, wait: bool=True) -> None: - """Musiknoten spielen (Tonhöhe) +def pitch( + frequency: int, + duration: int = -1, + pin: Optional[MicroBitDigitalPin] = pin0, + wait: bool = True, +) -> None: + """Play a note. -Example: ``music.pitch(185, 1000)`` + Example: ``music.pitch(185, 1000)`` -:param frequency: (Frequenz) Eine ganzzahlige Frequenz -:param duration: (Dauer) Eine Dauer in Millisekunden. Bei negativem Wert erhält man bis zum nächsten Aufruf oder einem Aufruf von ``stop`` einen Dauerton. -:param pin: Optionaler Ausgabepin (Standard ``pin0``). -:param wait: Wenn ``wait`` auf ``True`` gesetzt ist, stoppt diese Funktion die weitere Codeausführung. + :param frequency: An integer frequency + :param duration: A millisecond duration. If negative then sound is continuous until the next call or a call to ``stop``. + :param pin: Optional output pin (default ``pin0``). + :param wait: If ``wait`` is set to ``True``, this function is blocking. -For example, if the frequency is set to 440 and the length to -1000 then we hear a standard concert A for one second. + For example, if the frequency is set to 440 and the length to + 1000 then we hear a standard concert A for one second. -You can only play one pitch on one pin at any one time.""" + You can only play one pitch on one pin at any one time. + """ ... -def stop(pin: Optional[MicroBitDigitalPin]=pin0) -> None: - """Stoppt die Musikwiedergabe über den eingebauten Lautsprecher sowie jeden Pin, der Sound ausgibt. +def stop(pin: Optional[MicroBitDigitalPin] = pin0) -> None: + """Stops all music playback on the built-in speaker and any pin outputting sound. -Example: ``music.stop()`` + Example: ``music.stop()`` -:param pin: Ein optionales Argument kann zur Angabe eines Pins angegeben werden, z. B. ``music.stop(pin1)``.""" + :param pin: An optional argument can be provided to specify a pin, e.g. ``music.stop(pin1)``. + """ def reset() -> None: - """Setzt Ticks, bpm, Dauer und Oktave auf ihre Standardwerte zurück. (zurücksetzen) + """Resets ticks, bpm, duration and octave to their default values. -Example: ``music.reset()`` + Example: ``music.reset()`` -Values: -- ``ticks = 4`` -- ``bpm = 120`` -- ``duration = 4`` -- ``octave = 4``""" - ... \ No newline at end of file + Values: + - ``ticks = 4`` + - ``bpm = 120`` + - ``duration = 4`` + - ``octave = 4`` + """ + ... diff --git a/lang/de/typeshed/stdlib/neopixel.pyi b/lang/de/typeshed/stdlib/neopixel.pyi index 9c84fea..2d5a749 100644 --- a/lang/de/typeshed/stdlib/neopixel.pyi +++ b/lang/de/typeshed/stdlib/neopixel.pyi @@ -1,81 +1,82 @@ -"""Individuell adressierbare RGB- und RGBW-LED-Streifen.""" +"""Individually addressable RGB and RGBW LED strips. +""" from .microbit import MicroBitDigitalPin from typing import Tuple class NeoPixel: + def __init__(self, pin: MicroBitDigitalPin, n: int, bpp: int = 3) -> None: + """Initialise a new strip of neopixel LEDs controlled via a pin. - def __init__(self, pin: MicroBitDigitalPin, n: int, bpp: int=3) -> None: - """Initialisierung eines neuen Streifens von Neopixel-LEDs, die über einen Pin gesteuert werden. + Example: ``np = neopixel.NeoPixel(pin0, 8)`` -Example: ``np = neopixel.NeoPixel(pin0, 8)`` + To support RGBW neopixels, a third argument can be passed to + ``NeoPixel`` to indicate the number of bytes per pixel (``bpp``). + For RGBW, this is is 4 rather than the default of 3 for RGB and GRB. -To support RGBW neopixels, a third argument can be passed to -``NeoPixel`` to indicate the number of bytes per pixel (``bpp``). -For RGBW, this is is 4 rather than the default of 3 for RGB and GRB. + Each pixel is addressed by a position (starting from 0). Neopixels are + given RGB (red, green, blue) / RGBW (red, green, blue, white) values + between 0-255 as a tuple. For example, in RGB, ``(255,255,255)`` is + white. In RGBW, ``(255,255,255,0)`` or ``(0,0,0,255)`` is white. -Each pixel is addressed by a position (starting from 0). Neopixels are -given RGB (red, green, blue) / RGBW (red, green, blue, white) values -between 0-255 as a tuple. For example, in RGB, ``(255,255,255)`` is -white. In RGBW, ``(255,255,255,0)`` or ``(0,0,0,255)`` is white. + See `the online docs `_ for warnings and other advice. -See `the online docs `_ for warnings and other advice. - -:param pin: Der Pin, der den Neopixelstreifen steuert. -:param n: Die Anzahl der Neopixel auf dem Streifen. -:param bpp: Bytes pro Pixel. Für die RGBW Neopixel-Unterstützung, müssen 4 statt der standardmäßigen 3 Bytes pro Pixel für RGB und GRB übergeben werden.""" + :param pin: The pin controlling the neopixel strip. + :param n: The number of neopixels in the strip. + :param bpp: Bytes per pixel. For RGBW neopixel support, pass 4 rather than the default of 3 for RGB and GRB. + """ ... - def clear(self) -> None: - """Lösche alle Pixel. + """Clear all the pixels. -Example: ``np.clear()``""" + Example: ``np.clear()`` + """ ... - def show(self) -> None: - """Die Pixel anzeigen. + """Show the pixels. -Example: ``np.show()`` + Example: ``np.show()`` -Must be called for any updates to become visible.""" + Must be called for any updates to become visible. + """ ... - def write(self) -> None: - """Pixel anzeigen (nur micro:bit V2) (schreiben) + """Show the pixels (micro:bit V2 only). -Example: ``np.write()`` + Example: ``np.write()`` -Must be called for any updates to become visible. + Must be called for any updates to become visible. -Equivalent to ``show``.""" + Equivalent to ``show``. + """ ... - def fill(self, colour: Tuple[int, ...]) -> None: - """Alle Pixel mit einem bestimmten RGB/RGBW-Wert färben. + """Colour all pixels a given RGB/RGBW value (micro:bit V2 only). -Example: ``np.fill((0, 0, 255))`` + Example: ``np.fill((0, 0, 255))`` -:param colour: (Farbe) Ein Tupel mit der gleichen Länge wie die Anzahl der Bytes pro Pixel (bpp). + :param colour: A tuple of the same length as the number of bytes per pixel (bpp). -Use in conjunction with ``show()`` to update the neopixels.""" + Use in conjunction with ``show()`` to update the neopixels. + """ ... - def __setitem__(self, key: int, value: Tuple[int, ...]) -> None: - """Eine Pixelfarbe festlegen. + """Set a pixel colour. -Example: ``np[0] = (255, 0, 0)`` - -:param key: Die Pixelnummer. -:param value: (wert) Die Farbe.""" + Example: ``np[0] = (255, 0, 0)`` + :param key: The pixel number. + :param value: The colour. + """ def __getitem__(self, key: int) -> Tuple[int, ...]: - """Eine Pixelfarbe erfassen. - -Example: ``r, g, b = np[0]`` + """Get a pixel colour. -:param key: Die Pixelnummer. -:return: The colour tuple.""" + Example: ``r, g, b = np[0]`` + :param key: The pixel number. + :return: The colour tuple. + """ def __len__(self) -> int: - """Liefert die Länge des Pixelstreifens. + """Get length of this pixel strip. -Example: ``len(np)``""" \ No newline at end of file + Example: ``len(np)`` + """ diff --git a/lang/de/typeshed/stdlib/os.pyi b/lang/de/typeshed/stdlib/os.pyi index 1fd4638..2f2db77 100644 --- a/lang/de/typeshed/stdlib/os.pyi +++ b/lang/de/typeshed/stdlib/os.pyi @@ -1,63 +1,73 @@ -"""Auf das Dateisystem zugreifen.""" +"""Access the file system. +""" + from typing import Tuple from typing import List def listdir() -> List[str]: - """Dateien auflisten. + """List files. -Example: ``os.listdir()`` + Example: ``os.listdir()`` -:return: A list of the names of all the files contained within the local -persistent on-device file system.""" + :return: A list of the names of all the files contained within the local + persistent on-device file system. + """ ... def remove(filename: str) -> None: - """Entferne (lösche) eine Datei. (Entfernen) + """Remove (delete) a file. -Example: ``os.remove('data.txt')`` + Example: ``os.remove('data.txt')`` -:param filename: (Dateiname) Die zu löschende Datei. + :param filename: The file to delete. -If the file does not exist an ``OSError`` exception will occur.""" + If the file does not exist an ``OSError`` exception will occur. + """ ... def size(filename: str) -> int: - """Gibt die Größe einer Datei zurück + """Returns the size of a file. -Example: ``os.size('data.txt')`` + Example: ``os.size('data.txt')`` -:param filename: (Dateiname) Die Datei -:return: The size in bytes. + :param filename: The file + :return: The size in bytes. -If the file does not exist an ``OSError`` exception will occur.""" + If the file does not exist an ``OSError`` exception will occur. + """ class uname_result(Tuple[str, str, str, str, str]): - """Ergebnis von ``os.uname()``""" + """Result of ``os.uname()``""" sysname: str - """Name des Betriebssystems.""" + """Operating system name.""" + nodename: str - """Name des Rechners im Netz (durch die Implementierung definiert). (Knotenname)""" + """Name of machine on network (implementation-defined).""" + release: str - """Betriebssystemveröffentlichung. (Veröffentlichung)""" + """Operating system release.""" + version: str - """Betriebssystemversion. (Version)""" + """Operating system version.""" + machine: str - """Hardware-Kennung. (maschine)""" + """Hardware identifier.""" def uname() -> uname_result: - """Gibt Informationen zum aktuellen Betriebssystem zurück. + """Returns information identifying the current operating system. -Example: ``os.uname()`` + Example: ``os.uname()`` -The return value is an object with five attributes: + The return value is an object with five attributes: -- ``sysname`` - operating system name -- ``nodename`` - name of machine on network (implementation-defined) -- ``release`` - operating system release -- ``version`` - operating system version -- ``machine`` - hardware identifier + - ``sysname`` - operating system name + - ``nodename`` - name of machine on network (implementation-defined) + - ``release`` - operating system release + - ``version`` - operating system version + - ``machine`` - hardware identifier -There is no underlying operating system in MicroPython. As a result the -information returned by the ``uname`` function is mostly useful for -versioning details.""" - ... \ No newline at end of file + There is no underlying operating system in MicroPython. As a result the + information returned by the ``uname`` function is mostly useful for + versioning details. + """ + ... diff --git a/lang/de/typeshed/stdlib/radio.pyi b/lang/de/typeshed/stdlib/radio.pyi index a75e188..8dd0267 100644 --- a/lang/de/typeshed/stdlib/radio.pyi +++ b/lang/de/typeshed/stdlib/radio.pyi @@ -1,126 +1,152 @@ -"""Kommunikation zwischen micro:bits mit dem integrierten Funk.""" +"""Communicate between micro:bits with the built-in radio. +""" + from _typeshed import WriteableBuffer from typing import Optional, Tuple + RATE_1MBIT: int -"""Konstante zur Angabe eines Durchsatzes von 1 MBit pro Sekunde.""" +"""Constant used to indicate a throughput of 1 MBit a second.""" + RATE_2MBIT: int -"""Konstante zur Angabe eines Durchsatzes von 2 MBit pro Sekunde.""" +"""Constant used to indicate a throughput of 2 MBit a second.""" def on() -> None: - """Schaltet den Funk ein. + """Turns the radio on. -Example: ``radio.on()`` + Example: ``radio.on()`` -This needs to be explicitly called since the radio draws power and takes -up memory that you may otherwise need.""" + This needs to be explicitly called since the radio draws power and takes + up memory that you may otherwise need. + """ ... def off() -> None: - """Schaltet den Funk aus, um Strom und Speicherplatz zu sparen. + """Turns off the radio, saving power and memory. -Example: ``radio.off()``""" + Example: ``radio.off()`` + """ ... -def config(length: int=32, queue: int=3, channel: int=7, power: int=6, address: int=1969383796, group: int=0, data_rate: int=RATE_1MBIT) -> None: - """Konfiguriert den Funk. - -Example: ``radio.config(group=42)`` - -The default configuration is suitable for most use. - -:param length: (default=32) legt die maximale Länge einer über Funk gesendeten Nachricht in Bytes fest. Sie kann bis zu 251 Bytes lang sein (254 - 3 Bytes für S0, LENGTH und S1-Präambel). -:param queue: (default=3) gibt die Anzahl der Nachrichten an, die in der Warteschlange für eingehende Nachrichten gespeichert werden können. Wenn in der Warteschlange kein Platz mehr für eingehende Nachrichten ist, wird die eingehende Nachricht verworfen. -:param channel: (default=7) ein Integer-Wert zwischen 0 und 83 (einschließlich), der einen beliebigen "Kanal" definiert, auf den der Funk eingestellt ist. -Nachrichten werden über diesen Kanal gesendet und nur Nachrichten, die über diesen Kanal empfangen werden, werden in die Warteschlange der eingehenden Nachricht aufgenommen. Jeder Schritt ist 1MHz breit, beginnend mit 2400MHz. -:param power: (default=6) ist ein ganzzahliger Wert von 0 bis 7 (einschließlich), der die Stärke des Signals angibt, das beim Senden einer Nachricht verwendet wird. Je höher der Wert, desto stärker ist das Signal, aber desto mehr Strom wird vom Gerät verbraucht. Die Nummerierung entspricht den Positionen in der folgenden Liste von dBm-Werten (Dezibel Milliwatt): -30, -20, -16, -12, -8, -4, 0, 4. -:param address: (adresse) (default=0x75626974) ein beliebiger Name, ausgedrückt als 32-Bit-Adresse, der verwendet wird, um eingehende Pakete auf der Hardware-Ebene zu filtern und nur diejenigen zu behalten, die mit der eingestellten Adresse übereinstimmen. -Die Standardeinstellung, die von anderen micro:bit-verwandten Plattformen verwendet wird, wird auch hier verwendet. -:param group: (default=0) ein 8-Bit-Wert (0-255), der zusammen mit ``address`` beim Filtern von Nachrichten verwendet wird. "address" ist wie eine Haus-/Büroadresse und "group" ist wie die Person an dieser Adresse, an die die Nachricht gesendet werden soll. -:param data_rate: (default=``radio.RATE_1MBIT``) zeigt die Geschwindigkeit an, mit der der Datendurchsatz stattfindet. -Kann eine der folgenden Konstanten sein, die im Modul ``radio`` definiert sind: ``RATE_250KBIT``, ``RATE_1MBIT`` oder ``RATE_2MBIT``. - -If ``config`` is not called then the defaults described above are assumed.""" +def config( + length: int = 32, + queue: int = 3, + channel: int = 7, + power: int = 6, + address: int = 0x75626974, + group: int = 0, + data_rate: int = RATE_1MBIT, +) -> None: + """Configures the radio. + + Example: ``radio.config(group=42)`` + + The default configuration is suitable for most use. + + :param length: (default=32) defines the maximum length, in bytes, of a message sent via the radio. + It can be up to 251 bytes long (254 - 3 bytes for S0, LENGTH and S1 preamble). + :param queue: (default=3) specifies the number of messages that can be stored on the incoming message queue. + If there are no spaces left on the queue for incoming messages, then the incoming message is dropped. + :param channel: (default=7) an integer value from 0 to 83 (inclusive) that defines an arbitrary "channel" to which the radio is tuned. + Messages will be sent via this channel and only messages received via this channel will be put onto the incoming message queue. Each step is 1MHz wide, based at 2400MHz. + :param power: (default=6) is an integer value from 0 to 7 (inclusive) to indicate the strength of signal used when broadcasting a message. + The higher the value the stronger the signal, but the more power is consumed by the device. The numbering translates to positions in the following list of dBm (decibel milliwatt) values: -30, -20, -16, -12, -8, -4, 0, 4. + :param address: (default=0x75626974) an arbitrary name, expressed as a 32-bit address, that's used to filter incoming packets at the hardware level, keeping only those that match the address you set. + The default used by other micro:bit related platforms is the default setting used here. + :param group: (default=0) an 8-bit value (0-255) used with the ``address`` when filtering messages. + Conceptually, "address" is like a house/office address and "group" is like the person at that address to which you want to send your message. + :param data_rate: (default=``radio.RATE_1MBIT``) indicates the speed at which data throughput takes place. + Can be one of the following constants defined in the ``radio`` module: ``RATE_250KBIT``, ``RATE_1MBIT`` or ``RATE_2MBIT``. + + If ``config`` is not called then the defaults described above are assumed. + """ ... def reset() -> None: - """Setzt die Einstellungen auf ihre Standardwerte zurück. (zurücksetzen) + """Reset the settings to their default values. -Example: ``radio.reset()`` + Example: ``radio.reset()`` -The defaults as as per the ``config`` function above.""" + The defaults as as per the ``config`` function above. + """ ... def send_bytes(message: bytes) -> None: - """Sendet eine Nachricht bestehend aus Bytes. + """Sends a message containing bytes. -Example: ``radio.send_bytes(b'hello')`` + Example: ``radio.send_bytes(b'hello')`` -:param message: Die zu sendenden Bytes.""" + :param message: The bytes to send. + """ ... def receive_bytes() -> Optional[bytes]: - """Empfängt die nächste eingehende Nachricht in der Nachrichtenwarteschlange. + """Receive the next incoming message on the message queue. -Example: ``radio.receive_bytes()`` + Example: ``radio.receive_bytes()`` -:return: The message bytes if any, otherwise ``None``.""" + :return: The message bytes if any, otherwise ``None``. + """ ... def receive_bytes_into(buffer: WriteableBuffer) -> Optional[int]: - """Kopiert die nächste eingehende Nachricht in der Nachrichtenwarteschlange in einen Puffer. + """Copy the next incoming message on the message queue into a buffer. -Example: ``radio.receive_bytes_info(buffer)`` + Example: ``radio.receive_bytes_info(buffer)`` -:param buffer: (Puffer) Der Zielpuffer. Die Nachricht wird abgeschnitten, wenn sie größer als der Puffer ist. -:return: ``None`` if there are no pending messages, otherwise it returns the length of the message (which might be more than the length of the buffer).""" + :param buffer: The target buffer. The message is truncated if larger than the buffer. + :return: ``None`` if there are no pending messages, otherwise it returns the length of the message (which might be more than the length of the buffer). + """ ... def send(message: str) -> None: - """Sendet eine Nachricht als String. + """Sends a message string. -Example: ``radio.send('hello')`` + Example: ``radio.send('hello')`` -This is the equivalent of ``radio.send_bytes(bytes(message, 'utf8'))`` but with ``b'\x01\x00\x01'`` -prepended to the front (to make it compatible with other platforms that target the micro:bit). + This is the equivalent of ``radio.send_bytes(bytes(message, 'utf8'))`` but with ``b'\x01\x00\x01'`` + prepended to the front (to make it compatible with other platforms that target the micro:bit). -:param message: Der zu sendende String.""" + :param message: The string to send. + """ ... def receive() -> Optional[str]: - """Funktioniert genauso wie ``receive_bytes``, gibt aber zurück, was gesendet wurde. + """Works in exactly the same way as ``receive_bytes`` but returns whatever was sent. -Example: ``radio.receive()`` + Example: ``radio.receive()`` -Equivalent to ``str(receive_bytes(), 'utf8')`` but with a check that the the first -three bytes are ``b'\x01\x00\x01'`` (to make it compatible with other platforms that -may target the micro:bit). + Equivalent to ``str(receive_bytes(), 'utf8')`` but with a check that the the first + three bytes are ``b'\x01\x00\x01'`` (to make it compatible with other platforms that + may target the micro:bit). -:return: The message with the prepended bytes stripped and converted to a string. + :return: The message with the prepended bytes stripped and converted to a string. -A ``ValueError`` exception is raised if conversion to string fails.""" + A ``ValueError`` exception is raised if conversion to string fails. + """ ... def receive_full() -> Optional[Tuple[bytes, int, int]]: - """Gibt ein Tupel mit drei Werten zurück, die die nächste eingehende Nachricht in der Nachrichtenwarteschlange darstellen. + """Returns a tuple containing three values representing the next incoming message on the message queue. -Example: ``radio.receive_full()`` + Example: ``radio.receive_full()`` -If there are no pending messages then ``None`` is returned. + If there are no pending messages then ``None`` is returned. -The three values in the tuple represent: + The three values in the tuple represent: -- the next incoming message on the message queue as bytes. -- the RSSI (signal strength): a value between 0 (strongest) and -255 (weakest) as measured in dBm. -- a microsecond timestamp: the value returned by ``time.ticks_us()`` when the message was received. + - the next incoming message on the message queue as bytes. + - the RSSI (signal strength): a value between 0 (strongest) and -255 (weakest) as measured in dBm. + - a microsecond timestamp: the value returned by ``time.ticks_us()`` when the message was received. -For example:: + For example:: - details = radio.receive_full() - if details: - msg, rssi, timestamp = details + details = radio.receive_full() + if details: + msg, rssi, timestamp = details -This function is useful for providing information needed for triangulation -and/or trilateration with other micro:bit devices. + This function is useful for providing information needed for triangulation + and/or trilateration with other micro:bit devices. -:return: ``None`` if there is no message, otherwise a tuple of length three with the bytes, strength and timestamp values.""" - ... \ No newline at end of file + :return: ``None`` if there is no message, otherwise a tuple of length three with the bytes, strength and timestamp values. + """ + ... diff --git a/lang/de/typeshed/stdlib/random.pyi b/lang/de/typeshed/stdlib/random.pyi index 10b688e..a2c2ef3 100644 --- a/lang/de/typeshed/stdlib/random.pyi +++ b/lang/de/typeshed/stdlib/random.pyi @@ -1,80 +1,93 @@ -"""Gibt eine Zufallszahl zurück.""" +"""Generate random numbers. +""" from typing import TypeVar, Sequence, Union, overload def getrandbits(n: int) -> int: - """Erzeugt einen Integerwert mit ``n`` zufälligen Bits. + """Generate an integer with ``n`` random bits. -Example: ``random.getrandbits(1)`` + Example: ``random.getrandbits(1)`` -:param n: Ein Wert zwischen 1-30 (einschließlich).""" + :param n: A value between 1-30 (inclusive). + """ ... def seed(n: int) -> None: - """Initialisiert den Zufallszahlengenerator. + """Initialize the random number generator. -Example: ``random.seed(0)`` + Example: ``random.seed(0)`` -:param n: Der Integer-Seed + :param n: The integer seed -This will give you reproducibly deterministic randomness from a given starting -state (``n``).""" + This will give you reproducibly deterministic randomness from a given starting + state (``n``). + """ ... def randint(a: int, b: int) -> int: - """Wählt eine zufällige Ganzzahl zwischen ``a`` und ``b`` (einschließlich) aus. + """Choose a random integer between ``a`` and ``b`` inclusive. -Example: ``random.randint(0, 9)`` + Example: ``random.randint(0, 9)`` -:param a: Anfangswert für den Bereich (inklusiv) -:param b: Endwert für den Bereich (inklusiv) + :param a: Start value for the range (inclusive) + :param b: End value for the range (inclusive) -Alias for ``randrange(a, b + 1)``.""" + Alias for ``randrange(a, b + 1)``. + """ ... @overload def randrange(stop: int) -> int: - """Wählt eine zufällige Ganzzahl zwischen Null und ``stop`` (exklusiv) aus. + """Choose a randomly selected integer between zero and up to (but not + including) ``stop``. -Example: ``random.randrange(10)`` + Example: ``random.randrange(10)`` -:param stop: Endwert für den Bereich (exklusiv)""" + :param stop: End value for the range (exclusive) + """ ... @overload -def randrange(start: int, stop: int, step: int=1) -> int: - """Wählt ein zufälliges Element aus ``range(start, stop, step)``. +def randrange(start: int, stop: int, step: int = 1) -> int: + """ + Choose a randomly selected element from ``range(start, stop, step)``. -Example: ``random.randrange(0, 10)`` + Example: ``random.randrange(0, 10)`` -:param start: Anfang des Bereichs (inklusiv) -:param stop: Das Ende des Bereichs (exklusiv) -:param step: Schrittweite""" + :param start: The start of the range (inclusive) + :param stop: The end of the range (exclusive) + :param step: The step. + """ ... -_T = TypeVar('_T') + +_T = TypeVar("_T") def choice(seq: Sequence[_T]) -> _T: - """Wählt ein zufälliges Element aus der nicht leeren Sequenz ``seq``. + """Choose a random element from the non-empty sequence ``seq``. -Example: ``random.choice([Image.HAPPY, Image.SAD])`` + Example: ``random.choice([Image.HAPPY, Image.SAD])`` -:param seq: Eine Sequenz. + :param seq: A sequence. -If ``seq`` is empty, raises ``IndexError``.""" + If ``seq`` is empty, raises ``IndexError``. + """ ... def random() -> float: - """Erzeugt eine zufällige Fließkommazahl im Bereich [0.0, 1.0). + """Generate a random floating point number in the range [0.0, 1.0). -Example: ``random.random()`` + Example: ``random.random()`` -:return: The random floating point number""" + :return: The random floating point number + """ ... def uniform(a: float, b: float) -> float: - """Gibt eine zufällige Fließkommazahl zwischen ``a`` und ``b`` inklusiv aus. + """ + Return a random floating point number between ``a`` and ``b`` inclusive. -Example: ``random.uniform(0, 9)`` + Example: ``random.uniform(0, 9)`` -:param a: Anfangswert für den Bereich (inklusiv) -:param b: Endwert für den Bereich (inklusiv)""" - ... \ No newline at end of file + :param a: Start value for the range (inclusive) + :param b: End value for the range (inclusive) + """ + ... diff --git a/lang/de/typeshed/stdlib/speech.pyi b/lang/de/typeshed/stdlib/speech.pyi index 237802a..349d188 100644 --- a/lang/de/typeshed/stdlib/speech.pyi +++ b/lang/de/typeshed/stdlib/speech.pyi @@ -1,76 +1,106 @@ -"""Bringe den micro:bit dazu zu Sprechen, zu Singen und andere sprachähnliche Geräusche zu machen.""" +"""Make the micro:bit talk, sing and make other speech like sounds. +""" + from typing import Optional from .microbit import MicroBitDigitalPin, pin0 def translate(words: str) -> str: - """Übersetze englische Wörter in Sprache. + """Translate English words to phonemes. -Example: ``speech.translate('hello world')`` + Example: ``speech.translate('hello world')`` -:param words: (Wörter) Ein String englischer Wörter. -:return: A string containing a best guess at the appropriate phonemes to pronounce. -The output is generated from this `text to phoneme translation table `_. + :param words: A string of English words. + :return: A string containing a best guess at the appropriate phonemes to pronounce. + The output is generated from this `text to phoneme translation table `_. -This function should be used to generate a first approximation of phonemes -that can be further hand-edited to improve accuracy, inflection and -emphasis. + This function should be used to generate a first approximation of phonemes + that can be further hand-edited to improve accuracy, inflection and + emphasis. -See `the online documentation `_ for detailed information.""" + See `the online documentation `_ for detailed information. + """ ... -def pronounce(phonemes: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: Optional[MicroBitDigitalPin]=pin0) -> None: - """Laute aussprechen. - -Example: ``speech.pronounce(' /HEHLOW WERLD')`` - -:param phonemes: (Phoneme) Die auszusprechenden Phoneme als Zeichenkette -:param pitch: (Tonhöhe) Eine Zahl, die die Tonhöhe der Stimme angibt -:param speed: (tempo) Eine Zahl, die die Geschwindigkeit der Stimme angibt -:param mouth: (Mund) Eine Zahl, die den Mund der Stimme repräsentiert -:param throat: (klang) Eine Zahl, die den Klang der Stimme angibt -:param pin: Optionales Argument, um den Ausgangspin anzugeben, kann verwendet werden, um den Standardwert von ``pin0`` zu überschreiben. Wenn wir keinen Ton über die Pins abspielen wollen, können wir ``pin=None`` verwenden. nur micro:bit V2. - -Override the optional pitch, speed, mouth and throat settings to change the -timbre (quality) of the voice. - -See `the online documentation `_ for detailed information.""" +def pronounce( + phonemes: str, + pitch: int = 64, + speed: int = 72, + mouth: int = 128, + throat: int = 128, + pin: Optional[MicroBitDigitalPin] = pin0, +) -> None: + """Pronounce phonemes. + + Example: ``speech.pronounce(' /HEHLOW WERLD')`` + + :param phonemes: The string of phonemes to pronounce + :param pitch: A number representing the pitch of the voice + :param speed: A number representing the speed of the voice + :param mouth: A number representing the mouth of the voice + :param throat: A number representing the throat of the voice + :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. + If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. + + Override the optional pitch, speed, mouth and throat settings to change the + timbre (quality) of the voice. + + See `the online documentation `_ for detailed information. + """ ... -def say(words: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: MicroBitDigitalPin=pin0) -> None: - """Sage englische Wörter (sage) - -Example: ``speech.say('hello world')`` - -:param words: (Wörter) Der zu sagene String -:param pitch: (Tonhöhe) Eine Zahl, die die Tonhöhe der Stimme angibt -:param speed: (tempo) Eine Zahl, die die Geschwindigkeit der Stimme angibt -:param mouth: (Mund) Eine Zahl, die den Mund der Stimme repräsentiert -:param throat: (klang) Eine Zahl, die den Klang der Stimme angibt -:param pin: Optionales Argument, um den Ausgangspin anzugeben, kann verwendet werden, um den Standardwert von ``pin0`` zu überschreiben. Wenn wir keinen Ton über die Pins abspielen wollen, können wir ``pin=None`` verwenden. nur micro:bit V2. - -The result is semi-accurate for English. Override the optional pitch, speed, -mouth and throat settings to change the timbre (quality) of the voice. - -This is a short-hand equivalent of: -``speech.pronounce(speech.translate(words))`` - -See `the online documentation `_ for detailed information.""" +def say( + words: str, + pitch: int = 64, + speed: int = 72, + mouth: int = 128, + throat: int = 128, + pin: MicroBitDigitalPin = pin0, +) -> None: + """Say English words. + + Example: ``speech.say('hello world')`` + + :param words: The string of words to say. + :param pitch: A number representing the pitch of the voice + :param speed: A number representing the speed of the voice + :param mouth: A number representing the mouth of the voice + :param throat: A number representing the throat of the voice + :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. + If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. + + The result is semi-accurate for English. Override the optional pitch, speed, + mouth and throat settings to change the timbre (quality) of the voice. + + This is a short-hand equivalent of: + ``speech.pronounce(speech.translate(words))`` + + See `the online documentation `_ for detailed information. + """ ... -def sing(phonemes: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: MicroBitDigitalPin=pin0) -> None: - """Singe Phoneme - -Example: ``speech.sing(' /HEHLOW WERLD')`` - -:param phonemes: (Phoneme) Der zu singende String -:param pitch: (Tonhöhe) Eine Zahl, die die Tonhöhe der Stimme angibt -:param speed: (tempo) Eine Zahl, die die Geschwindigkeit der Stimme angibt -:param mouth: (Mund) Eine Zahl, die den Mund der Stimme repräsentiert -:param throat: (klang) Eine Zahl, die den Klang der Stimme angibt -:param pin: Optionales Argument, um den Ausgangspin anzugeben, kann verwendet werden, um den Standardwert von ``pin0`` zu überschreiben. Wenn wir keinen Ton über die Pins abspielen wollen, können wir ``pin=None`` verwenden. nur micro:bit V2. - -Override the optional pitch, speed, mouth and throat settings to change -the timbre (quality) of the voice. - -See `the online documentation `_ for detailed information.""" - ... \ No newline at end of file +def sing( + phonemes: str, + pitch: int = 64, + speed: int = 72, + mouth: int = 128, + throat: int = 128, + pin: MicroBitDigitalPin = pin0, +) -> None: + """Sing phonemes. + + Example: ``speech.sing(' /HEHLOW WERLD')`` + + :param phonemes: The string of words to sing. + :param pitch: A number representing the pitch of the voice + :param speed: A number representing the speed of the voice + :param mouth: A number representing the mouth of the voice + :param throat: A number representing the throat of the voice + :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. + If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. + + Override the optional pitch, speed, mouth and throat settings to change + the timbre (quality) of the voice. + + See `the online documentation `_ for detailed information. + """ + ... diff --git a/lang/de/typeshed/stdlib/struct.pyi b/lang/de/typeshed/stdlib/struct.pyi index 143f24c..53b3e0b 100644 --- a/lang/de/typeshed/stdlib/struct.pyi +++ b/lang/de/typeshed/stdlib/struct.pyi @@ -1,56 +1,65 @@ -"""Packe und entpacke primitive Datentypen. (struktur)""" +"""Pack and unpack primitive data types. +""" + from _typeshed import ReadableBuffer, WriteableBuffer from typing import Any, Tuple, Union def calcsize(fmt: str) -> int: - """Rufe die Anzahl der benötigten Bytes ab, um den angegebenen ``fmt`` zu speichern. + """Get the number of bytes needed to store the given ``fmt``. -Example: ``struct.calcsize('hf')`` + Example: ``struct.calcsize('hf')`` -:param fmt: Ein Format-String. -:return The number of bytes needed to store such a value.""" + :param fmt: A format string. + :return The number of bytes needed to store such a value. + """ ... def pack(fmt: str, v1: Any, *vn: Any) -> bytes: - """Werte nach einem Format-String packen. (packen) + """Pack values according to a format string. -Example: ``struct.pack('hf', 1, 3.1415)`` + Example: ``struct.pack('hf', 1, 3.1415)`` -:param fmt: Der Formatstring -:param v1: Der erste Wert. -:param *vn: Die verbleibenden Werte. -:return A bytes object encoding the values.""" + :param fmt: The format string. + :param v1: The first value. + :param *vn: The remaining values. + :return A bytes object encoding the values. + """ ... -def pack_into(fmt: str, buffer: WriteableBuffer, offset: int, v1: Any, *vn: Any) -> None: - """Werte nach einem Format-String packen. (packen in) +def pack_into( + fmt: str, buffer: WriteableBuffer, offset: int, v1: Any, *vn: Any +) -> None: + """Pack values according to a format string. -Example: ``struct.pack_info('hf', buffer, 1, 3.1415)`` + Example: ``struct.pack_info('hf', buffer, 1, 3.1415)`` -:param fmt: Der Formatstring -:param buffer: (Puffer) Der Buffer, in den geschrieben werden soll. -:param offset: Der Offset in den Puffer. Kann negativ sein, um vom Ende des Puffers aus zu zählen. -:param v1: Der erste Wert. -:param *vn: Die verbleibenden Werte.""" + :param fmt: The format string. + :param buffer: The target buffer to write into. + :param offset: The offset into the buffer. May be negative to count from the end of the buffer. + :param v1: The first value. + :param *vn: The remaining values. + """ ... def unpack(fmt: str, data: ReadableBuffer) -> Tuple[Any, ...]: - """Daten nach einem Format-String entpacken. + """Unpack data according to a format string. -Example: ``v1, v2 = struct.unpack('hf', buffer)`` + Example: ``v1, v2 = struct.unpack('hf', buffer)`` -:param fmt: Der Formatstring -:param data: (Daten) Die Daten. -:return: A tuple of the unpacked values.""" + :param fmt: The format string. + :param data: The data. + :return: A tuple of the unpacked values. + """ ... -def unpack_from(fmt: str, buffer: ReadableBuffer, offset: int=0) -> Tuple: - """Daten aus einem Puffer nach einem Format-String entpacken. (entpacken von) +def unpack_from(fmt: str, buffer: ReadableBuffer, offset: int = 0) -> Tuple: + """Unpack data from a buffer according to a format string. -Example: ``v1, v2 = struct.unpack_from('hf', buffer)`` + Example: ``v1, v2 = struct.unpack_from('hf', buffer)`` -:param fmt: Der Formatstring -:param buffer: (Puffer) Der Quellpuffer, von dem gelesen werden soll. -:param offset: Der Offset in den Puffer. Kann negativ sein, um vom Ende des Puffers aus zu zählen. -:return: A tuple of the unpacked values.""" - ... \ No newline at end of file + :param fmt: The format string. + :param buffer: The source buffer to read from. + :param offset: The offset into the buffer. May be negative to count from the end of the buffer. + :return: A tuple of the unpacked values. + """ + ... diff --git a/lang/de/typeshed/stdlib/sys.pyi b/lang/de/typeshed/stdlib/sys.pyi index c6fe0f5..320bac9 100644 --- a/lang/de/typeshed/stdlib/sys.pyi +++ b/lang/de/typeshed/stdlib/sys.pyi @@ -1,36 +1,43 @@ -"""Systemspezifische Funktionen""" +"""System specific functions""" + from typing import Any, Dict, List, NoReturn, TextIO, Tuple -def exit(retval: object=...) -> NoReturn: - """Ein Programm mit dem gegebenen Exit-Code beenden. +def exit(retval: object = ...) -> NoReturn: + """Terminate current program with a given exit code. -Example: ``sys.exit(1)`` + Example: ``sys.exit(1)`` -This function raises a ``SystemExit`` exception. If an argument is given, its -value given as an argument to ``SystemExit``. + This function raises a ``SystemExit`` exception. If an argument is given, its + value given as an argument to ``SystemExit``. -:param retval: Der Exit-Code oder die Nachricht.""" + :param retval: The exit code or message. + """ ... def print_exception(exc: Exception) -> None: - """Eine Ausnahme mit einem Traceback ausgeben. (Ausnahme ausgeben) + """ + Print an exception with a traceback. + + Example: ``sys.print_exception(e)`` -Example: ``sys.print_exception(e)`` + :param exc: The exception to print -:param exc: Die auszugebende Ausnahme + This is simplified version of a function which appears in the + ``traceback`` module in CPython. + """ -This is simplified version of a function which appears in the -``traceback`` module in CPython.""" argv: List[str] -"""Eine veränderbare Liste von Argumenten, mit denen das aktuelle Programm gestartet wurde.""" +"""A mutable list of arguments the current program was started with.""" + byteorder: str -"""Die Byte-Reihenfolge des Systems (``"little"`` oder ``"big"``).""" +"""The byte order of the system (``"little"`` or ``"big"``).""" class _implementation: name: str version: Tuple[int, int, int] + implementation: _implementation -"""Objekt mit Informationen über die aktuelle Python-Implementierung. (Implementierung) +"""Object with information about the current Python implementation. For MicroPython, it has following attributes: @@ -44,9 +51,13 @@ minimal ports). CPython mandates more attributes for this object, but the actual useful bare minimum is implemented in MicroPython. """ + maxsize: int """ -Maximaler Wert, den ein nativer Integer-Typ auf der aktuellen Plattform halten kann, oder maximaler Wert, der durch den MicroPython-Integer-Typ darstellbar ist, wenn er kleiner ist als der maximale Plattformwert (das ist der Fall bei MicroPython-Ports ohne "long int"-Unterstützung). +Maximum value which a native integer type can hold on the current platform, +or maximum value representable by MicroPython integer type, if it's smaller +than platform max value (that is the case for MicroPython ports without +long int support). This attribute is useful for detecting "bitness" of a platform (32-bit vs 64-bit, etc.). It's recommended to not compare this attribute to some @@ -66,14 +77,17 @@ value directly, but instead count number of bits in it:: # (e.g. 31) due to peculiarities described above, so use "> 16", # "> 32", "> 64" style of comparisons. """ + modules: Dict[str, Any] -"""Wörterbuch der geladenen Module. (module) +"""Dictionary of loaded modules. On some ports, it may not include builtin modules.""" + path: List[str] -"""Eine veränderbare Liste von Verzeichnissen zum Suchen nach importierten Modulen.""" +"""A mutable list of directories to search for imported modules.""" + platform: str -"""Die Plattform, auf der MicroPython läuft. (plattform) +"""The platform that MicroPython is running on. For OS/RTOS ports, this is usually an identifier of the OS, e.g. ``"linux"``. For baremetal ports it is an identifier of a board, e.g. ``"pyboard"`` for @@ -83,11 +97,13 @@ distinguish one board from another. If you need to check whether your program runs on MicroPython (vs other Python implementation), use ``sys.implementation`` instead. """ + version: str -"""Python-Sprachversion, der diese Implementierung als String entspricht. (Version)""" +"""Python language version that this implementation conforms to, as a string.""" + version_info: Tuple[int, int, int] -"""Python-Sprachversion, der diese Implementierung als Tuple mit Ints entspricht. (Versionsinformationen) +"""Python language version that this implementation conforms to, as a tuple of ints. Only the first three version numbers (major, minor, micro) are supported and they can be referenced only by index, not by name. -""" \ No newline at end of file +""" diff --git a/lang/de/typeshed/stdlib/time.pyi b/lang/de/typeshed/stdlib/time.pyi index b60805f..598c483 100644 --- a/lang/de/typeshed/stdlib/time.pyi +++ b/lang/de/typeshed/stdlib/time.pyi @@ -1,111 +1,132 @@ -"""Messe Zeit und füge Verzögerung zu Programmen hinzu. (Zeit)""" +"""Measure time and add delays to programs. +""" + from typing import Union def sleep(seconds: Union[int, float]) -> None: - """Warte eine bestimmte Zahl in Sekunden. + """ + Delay a number of seconds. -Example: ``time.sleep(1)`` + Example: ``time.sleep(1)`` -:param seconds: (sekunden) Die Anzahl der Sekunden für die der Ruhezustand angezeigt wird. -Benutze eine Gleitkommazahl für eine Bruchzahl von Sekunden.""" + :param seconds: The number of seconds to sleep for. + Use a floating-point number to sleep for a fractional number of seconds. + """ ... def sleep_ms(ms: int) -> None: - """Verzögerung für die angegebene Anzahl von Millisekunden. (schlafe ms) + """ + Delay for given number of milliseconds. -Example: ``time.sleep_ms(1_000_000)`` + Example: ``time.sleep_ms(1_000_000)`` -:param ms: Die Anzahl der zu wartenden Millisekunden (>= 0).""" + :param ms: The number of milliseconds delay (>= 0). + """ ... def sleep_us(us: int) -> None: - """Verzögerung für die angegebene Anzahl von Mikrosekunden. + """ + Delay for given number of microseconds. -Example: ``time.sleep_us(1000)`` + Example: ``time.sleep_us(1000)`` -:param us: Die Anzahl der zu wartenden Mikrosekunden (>= 0).""" + :param us: The number of microseconds delay (>= 0). + """ ... def ticks_ms() -> int: - """Holt einen ansteigenden Millisekunden-Zähler mit einem beliebigen Referenzpunkt, der nach einem bestimmten Wert weiterläuft. + """ + Get an increasing, millisecond counter with an arbitrary reference point, + that wraps around after some value. -Example: ``time.ticks_ms()`` + Example: ``time.ticks_ms()`` -:return: The counter value in milliseconds.""" + :return: The counter value in milliseconds. + """ ... def ticks_us() -> int: - """Holt einen ansteigenden Mikrosekunden-Zähler mit einem beliebigen Referenzpunkt, der nach einem bestimmten Wert weiterläuft. + """ + Get an increasing, microsecond counter with an arbitrary reference point, + that wraps around after some value. -Example: ``time.ticks_us()`` + Example: ``time.ticks_us()`` -:return: The counter value in microseconds.""" + :return: The counter value in microseconds. + """ ... def ticks_add(ticks: int, delta: int) -> int: - """Versetzt den Tick-Wert um eine bestimmte Zahl, die entweder positiv oder negativ sein kann. + """ + Offset ticks value by a given number, which can be either positive or + negative. -Example: ``time.ticks_add(time.ticks_ms(), 200)`` + Example: ``time.ticks_add(time.ticks_ms(), 200)`` -Given a ticks value, this function allows to calculate ticks -value delta ticks before or after it, following modular-arithmetic -definition of tick values. + Given a ticks value, this function allows to calculate ticks + value delta ticks before or after it, following modular-arithmetic + definition of tick values. -:param ticks: Ein Tick-Wert -:param delta: Ein ganzzahliger Offset + :param ticks: A ticks value + :param delta: An integer offset -Example:: + Example:: - # Find out what ticks value there was 100ms ago - print(ticks_add(time.ticks_ms(), -100)) + # Find out what ticks value there was 100ms ago + print(ticks_add(time.ticks_ms(), -100)) - # Calculate deadline for operation and test for it - deadline = ticks_add(time.ticks_ms(), 200) - while ticks_diff(deadline, time.ticks_ms()) > 0: - do_a_little_of_something() + # Calculate deadline for operation and test for it + deadline = ticks_add(time.ticks_ms(), 200) + while ticks_diff(deadline, time.ticks_ms()) > 0: + do_a_little_of_something() - # Find out TICKS_MAX used by this port - print(ticks_add(0, -1))""" + # Find out TICKS_MAX used by this port + print(ticks_add(0, -1)) + """ ... def ticks_diff(ticks1: int, ticks2: int) -> int: - """Messung der Ticks-Differenz zwischen den Werten, die von ``time.ticks_ms()`` oder ``ticks_us()`` zurückgegeben werden, als vorzeichenbehafteter Wert der umgeschlagen werden kann. - -Example: ``time.ticks_diff(scheduled_time, now)`` - -:param ticks1: Der zu subtrahierende Wert von -:param ticks2: Der zu subtrahierende Wert - -The argument order is the same as for subtraction operator, -``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. - -``ticks_diff()`` is designed to accommodate various usage -patterns, among them: - -Polling with timeout. In this case, the order of events is known, and you -will deal only with positive results of :func:`time.ticks_diff()`:: - - # Wait for GPIO pin to be asserted, but at most 500us - start = time.ticks_us() - while pin.value() == 0: - if time.ticks_diff(time.ticks_us(), start) > 500: - raise TimeoutError - - -Scheduling events. In this case, :func:`time.ticks_diff()` result may be -negative if an event is overdue:: - - # This code snippet is not optimized - now = time.ticks_ms() - scheduled_time = task.scheduled_time() - if ticks_diff(scheduled_time, now) > 0: - print("Too early, let's nap") - sleep_ms(ticks_diff(scheduled_time, now)) - task.run() - elif ticks_diff(scheduled_time, now) == 0: - print("Right at time!") - task.run() - elif ticks_diff(scheduled_time, now) < 0: - print("Oops, running late, tell task to run faster!") - task.run(run_faster=True)""" - ... \ No newline at end of file + """ + Measure ticks difference between values returned from + ``time.ticks_ms()`` or ``ticks_us()``, as a signed value + which may wrap around. + + Example: ``time.ticks_diff(scheduled_time, now)`` + + :param ticks1: The value to subtract from + :param ticks2: The value to subtract + + The argument order is the same as for subtraction operator, + ``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. + + ``ticks_diff()`` is designed to accommodate various usage + patterns, among them: + + Polling with timeout. In this case, the order of events is known, and you + will deal only with positive results of :func:`time.ticks_diff()`:: + + # Wait for GPIO pin to be asserted, but at most 500us + start = time.ticks_us() + while pin.value() == 0: + if time.ticks_diff(time.ticks_us(), start) > 500: + raise TimeoutError + + + Scheduling events. In this case, :func:`time.ticks_diff()` result may be + negative if an event is overdue:: + + # This code snippet is not optimized + now = time.ticks_ms() + scheduled_time = task.scheduled_time() + if ticks_diff(scheduled_time, now) > 0: + print("Too early, let's nap") + sleep_ms(ticks_diff(scheduled_time, now)) + task.run() + elif ticks_diff(scheduled_time, now) == 0: + print("Right at time!") + task.run() + elif ticks_diff(scheduled_time, now) < 0: + print("Oops, running late, tell task to run faster!") + task.run(run_faster=True) + """ + ... diff --git a/lang/es-es/typeshed/stdlib/gc.pyi b/lang/es-es/typeshed/stdlib/gc.pyi index 2eb95df..1370abf 100644 --- a/lang/es-es/typeshed/stdlib/gc.pyi +++ b/lang/es-es/typeshed/stdlib/gc.pyi @@ -1,68 +1,73 @@ -"""Controlar el recolector de basura (rb)""" +"""Control the garbage collector""" + from typing import overload def enable() -> None: - """Activar la recolección automática de basura. (habilitado)""" + """Enable automatic garbage collection.""" ... def disable() -> None: - """Desactiva la recolección automática de basura. (deshabilitar) + """Disable automatic garbage collection. -Heap memory can still be allocated, -and garbage collection can still be initiated manually using ``gc.collect``.""" + Heap memory can still be allocated, + and garbage collection can still be initiated manually using ``gc.collect``.""" def collect() -> None: - """Ejecuta una recolección de basura. (recoger)""" + """Run a garbage collection.""" ... def mem_alloc() -> int: - """Obtiene el número de bytes asignados a la RAM dinámica. (memoria asignada) + """Get the number of bytes of heap RAM that are allocated. -:return: The number of bytes allocated. + :return: The number of bytes allocated. -This function is MicroPython extension.""" + This function is MicroPython extension. + """ ... def mem_free() -> int: - """Obtiene el número de bytes de la RAM dinámica disponible o -1 si se desconoce esta cantidad. (memoria libre) + """Get the number of bytes of available heap RAM, or -1 if this amount is not known. -:return: The number of bytes free. + :return: The number of bytes free. -This function is MicroPython extension.""" + This function is MicroPython extension. + """ ... @overload def threshold() -> int: - """Consulta el umbral de asignación de GC (recolector de basura) adicional. (límite) + """Query the additional GC allocation threshold. -:return: The GC allocation threshold. + :return: The GC allocation threshold. -This function is a MicroPython extension. CPython has a similar -function - ``set_threshold()``, but due to different GC -implementations, its signature and semantics are different.""" + This function is a MicroPython extension. CPython has a similar + function - ``set_threshold()``, but due to different GC + implementations, its signature and semantics are different. + """ ... @overload def threshold(amount: int) -> None: - """Establece el umbral de asignación de GC (recolector de basura) adicional. (límite) - -Normally, a collection is triggered only when a new allocation -cannot be satisfied, i.e. on an out-of-memory (OOM) condition. -If this function is called, in addition to OOM, a collection -will be triggered each time after ``amount`` bytes have been -allocated (in total, since the previous time such an amount of bytes -have been allocated). ``amount`` is usually specified as less than the -full heap size, with the intention to trigger a collection earlier than when the -heap becomes exhausted, and in the hope that an early collection will prevent -excessive memory fragmentation. This is a heuristic measure, the effect -of which will vary from application to application, as well as -the optimal value of the ``amount`` parameter. - -A value of -1 means a disabled allocation threshold. - -This function is a MicroPython extension. CPython has a similar -function - ``set_threshold()``, but due to different GC -implementations, its signature and semantics are different. - -:param amount: (cantidad) Número de bytes después de los cuales se debe activar una recolección de basura.""" - ... \ No newline at end of file + """Set the additional GC allocation threshold. + + Normally, a collection is triggered only when a new allocation + cannot be satisfied, i.e. on an out-of-memory (OOM) condition. + If this function is called, in addition to OOM, a collection + will be triggered each time after ``amount`` bytes have been + allocated (in total, since the previous time such an amount of bytes + have been allocated). ``amount`` is usually specified as less than the + full heap size, with the intention to trigger a collection earlier than when the + heap becomes exhausted, and in the hope that an early collection will prevent + excessive memory fragmentation. This is a heuristic measure, the effect + of which will vary from application to application, as well as + the optimal value of the ``amount`` parameter. + + A value of -1 means a disabled allocation threshold. + + This function is a MicroPython extension. CPython has a similar + function - ``set_threshold()``, but due to different GC + implementations, its signature and semantics are different. + + :param amount: The number of bytes after which a garbage collection should be triggered. + """ + ... diff --git a/lang/es-es/typeshed/stdlib/log.pyi b/lang/es-es/typeshed/stdlib/log.pyi index d416a70..c9870fa 100644 --- a/lang/es-es/typeshed/stdlib/log.pyi +++ b/lang/es-es/typeshed/stdlib/log.pyi @@ -1,89 +1,104 @@ -"""Registra datos en el micro:bit V2. (registrar)""" +"""Log data to your micro:bit V2.""" + from typing import Literal, Mapping, Optional, Union, overload + MILLISECONDS = 1 -"""Formato de marca temporal en milisegundos. (milisegundos)""" +"""Milliseconds timestamp format.""" + SECONDS = 10 -"""Formato de marca temporal en segundos. (segundos)""" +"""Seconds timestamp format.""" + MINUTES = 600 -"""Formato de marca temporal en minutos. (minutos)""" +"""Minutes timestamp format.""" + HOURS = 36000 -"""Formato de marca temporal en horas. (horas)""" +"""Hours timestamp format.""" + DAYS = 864000 -"""Formato de marca temporal en días. (días)""" +"""Days timestamp format.""" -def set_labels(*labels: str, timestamp: Optional[Literal[1, 10, 36000, 864000]]=SECONDS) -> None: - """Configura la cabecera del archivo de registro. (configurar etiquetas) +def set_labels( + *labels: str, timestamp: Optional[Literal[1, 10, 36000, 864000]] = SECONDS +) -> None: + """Set up the log file header. -Example: ``log.set_labels('X', 'Y', 'Z', timestamp=log.MINUTES)`` + Example: ``log.set_labels('X', 'Y', 'Z', timestamp=log.MINUTES)`` -Ideally this function should be called a single time, before any data is -logged, to configure the data table header once. + Ideally this function should be called a single time, before any data is + logged, to configure the data table header once. -If a log file already exists when the program starts, or if this function -is called multiple times, it will check the labels already defined in the -log file. If this function call contains any new labels not already -present, it will generate a new header row with the additional columns. + If a log file already exists when the program starts, or if this function + is called multiple times, it will check the labels already defined in the + log file. If this function call contains any new labels not already + present, it will generate a new header row with the additional columns. -By default the first column contains a timestamp for each row. The time -unit can be selected via the timestamp argument. + By default the first column contains a timestamp for each row. The time + unit can be selected via the timestamp argument. -:param *labels: (*Etiquetas) Cualquier número de argumentos posicionales, cada uno correspondiente a una entrada en el encabezado del registro. -:param timestamp: (marca de tiempo) Selecciona la unidad de marca de tiempo que se añadirá automáticamente como la primera columna de cada fila. Los valores de la marca de tiempo pueden ser ``log.MILLISECONDS``, ``log.SECONDS``, ``log.MINUTES``, ``log.HOURS``, ``log.DAYS`` o ``None`` para desactivar la marca de tiempo. El valor por defecto es ``log.SECONDS``.""" + :param *labels: Any number of positional arguments, each corresponding to an entry in the log header. + :param timestamp: Select the timestamp unit that will be automatically added as the first column in every row. Timestamp values can be one of ``log.MILLISECONDS``, ``log.SECONDS``, ``log.MINUTES``, ``log.HOURS``, ``log.DAYS`` or ``None`` to disable the timestamp. The default value is ``log.SECONDS``. + """ ... @overload -def add(data_dictionary: Optional[Mapping[str, Union[str, int, float]]]) -> None: - """Añade una fila de datos al registro pasando un diccionario de cabeceras y valores. (añadir) +def add( + data_dictionary: Optional[Mapping[str, Union[str, int, float]]], +) -> None: + """Add a data row to the log by passing a dictionary of headers and values. -Example: ``log.add({ 'temp': temperature() })`` + Example: ``log.add({ 'temp': temperature() })`` -Each call to this function adds a row to the log. + Each call to this function adds a row to the log. -New labels not previously specified via the set_labels function, or by a -previous call to this function, will trigger a new header entry to be added -to the log with the extra labels. + New labels not previously specified via the set_labels function, or by a + previous call to this function, will trigger a new header entry to be added + to the log with the extra labels. -Labels previously specified and not present in a call to this function will -be skipped with an empty value in the log row. + Labels previously specified and not present in a call to this function will + be skipped with an empty value in the log row. -:param data_dictionary: (diccionario de datos) Los datos que se registrarán como un diccionario con una clave para cada cabecera.""" + :param data_dictionary: The data to log as a dictionary with a key for each header. + """ ... @overload def add(**kwargs: Union[str, int, float]) -> None: - """Añade una fila de datos al registro usando argumentos de palabra clave. (añadir) + """Add a data row to the log using keyword arguments. -Example: ``log.add(temp=temperature())`` + Example: ``log.add(temp=temperature())`` -Each call to this function adds a row to the log. + Each call to this function adds a row to the log. -New labels not previously specified via the set_labels function, or by a -previous call to this function, will trigger a new header entry to be added -to the log with the extra labels. + New labels not previously specified via the set_labels function, or by a + previous call to this function, will trigger a new header entry to be added + to the log with the extra labels. -Labels previously specified and not present in a call to this function will -be skipped with an empty value in the log row.""" + Labels previously specified and not present in a call to this function will + be skipped with an empty value in the log row. + """ ... def delete(full=False): - """Elimina el contenido del registro, incluyendo las cabeceras. (eliminar) + """Deletes the contents of the log, including headers. -Example: ``log.delete()`` + Example: ``log.delete()`` -To add the log headers again the ``set_labels`` function should to be called after this function. + To add the log headers again the ``set_labels`` function should to be called after this function. -There are two erase modes; “full” completely removes the data from the physical storage, -and “fast” invalidates the data without removing it. + There are two erase modes; “full” completely removes the data from the physical storage, + and “fast” invalidates the data without removing it. -:param full: (completo) ``True`` selecciona un borrador “completo” y ``False`` selecciona el método de borrado “rápido”.""" + :param full: ``True`` selects a “full” erase and ``False`` selects the “fast” erase method. + """ ... def set_mirroring(serial: bool): - """Configura la duplicación de la actividad de registro de datos en la salida serie. (configurar replicación) + """Configure mirroring of the data logging activity to the serial output. -Example: ``log.set_mirroring(True)`` + Example: ``log.set_mirroring(True)`` -Serial mirroring is disabled by default. When enabled, it will print to serial each row logged into the log file. + Serial mirroring is disabled by default. When enabled, it will print to serial each row logged into the log file. -:param serial: (serie) ``True`` habilita la reproducción de datos en la salida de serie.""" - ... \ No newline at end of file + :param serial: ``True`` enables mirroring data to the serial output. + """ + ... diff --git a/lang/es-es/typeshed/stdlib/machine.pyi b/lang/es-es/typeshed/stdlib/machine.pyi index fc0afb9..2e82f5b 100644 --- a/lang/es-es/typeshed/stdlib/machine.pyi +++ b/lang/es-es/typeshed/stdlib/machine.pyi @@ -1,84 +1,97 @@ -"""Utilidades de bajo nivel. (máquina)""" +"""Low-level utilities. +""" from typing import Any from .microbit import MicroBitDigitalPin def unique_id() -> bytes: - """Obtiene una cadena de bytes con un identificador único de una placa. (id único) + """Get a byte string with a unique identifier of a board. -Example: ``machine.unique_id()`` + Example: ``machine.unique_id()`` -:return: An identifier that varies from one board instance to another.""" + :return: An identifier that varies from one board instance to another. + """ ... def reset() -> None: - """Restablece el dispositivo de una forma similar a pulsar el botón externo RESET. (restablecer) + """Reset the device in a manner similar to pushing the external RESET button. -Example: ``machine.reset()``""" + Example: ``machine.reset()`` + """ ... def freq() -> int: - """Obtiene la frecuencia de la CPU en hercios. (frec) + """Get the CPU frequency in hertz. -Example: ``machine.freq()`` + Example: ``machine.freq()`` -:return: The CPU frequency.""" + :return: The CPU frequency. + """ ... def disable_irq() -> Any: - """Desactiva las solicitudes de interrupción. (desactivar irq) + """Disable interrupt requests. -Example: ``interrupt_state = machine.disable_irq()`` + Example: ``interrupt_state = machine.disable_irq()`` -:return: the previous IRQ state which should be considered an opaque value + :return: the previous IRQ state which should be considered an opaque value -The return value should be passed to the ``enable_irq`` function to restore -interrupts to their original state.""" + The return value should be passed to the ``enable_irq`` function to restore + interrupts to their original state. + """ ... def enable_irq(state: Any) -> None: - """Reactiva las solicitudes de interrupción. (activar irq) + """Re-enable interrupt requests. -Example: ``machine.enable_irq(interrupt_state)`` + Example: ``machine.enable_irq(interrupt_state)`` -:param state: (estado) Valor devuelto por la llamada más reciente a la función ``disable_irq``.""" + :param state: The value that was returned from the most recent call to the ``disable_irq`` function. + """ ... -def time_pulse_us(pin: MicroBitDigitalPin, pulse_level: int, timeout_us: int=1000000) -> int: - """Cronometra el estado de un pin. (cronometrar estado us) +def time_pulse_us( + pin: MicroBitDigitalPin, pulse_level: int, timeout_us: int = 1000000 +) -> int: + """Time a pulse on a pin. -Example: ``time_pulse_us(pin0, 1)`` + Example: ``time_pulse_us(pin0, 1)`` -If the current input value of the pin is different to ``pulse_level``, the -function first waits until the pin input becomes equal to -``pulse_level``, then times the duration that the pin is equal to -``pulse_level``. If the pin is already equal to ``pulse_level`` then timing -starts straight away. + If the current input value of the pin is different to ``pulse_level``, the + function first waits until the pin input becomes equal to + ``pulse_level``, then times the duration that the pin is equal to + ``pulse_level``. If the pin is already equal to ``pulse_level`` then timing + starts straight away. -:param pin: Pin a usar -:param pulse_level: (nivel de estado) 0 para cronometrar un estado bajo o 1 para un estado alto -:param timeout_us: (tiempo de espera us) Tiempo de espera en microsegundos -:return: The duration of the pulse in microseconds, or -1 for a timeout waiting for the level to match ``pulse_level``, or -2 on timeout waiting for the pulse to end""" + :param pin: The pin to use + :param pulse_level: 0 to time a low pulse or 1 to time a high pulse + :param timeout_us: A microsecond timeout + :return: The duration of the pulse in microseconds, or -1 for a timeout waiting for the level to match ``pulse_level``, or -2 on timeout waiting for the pulse to end + """ ... class mem: - """Clase para las vistas de memoria ``mem8``, ``mem16`` y ``mem32``.""" + """The class for the ``mem8``, ``mem16`` and ``mem32`` memory views.""" def __getitem__(self, address: int) -> int: - """Accede a un valor de la memoria. (obtener elemento) + """Access a value from memory. -:param address: (dirección) La dirección de memoria. -:return: The value at that address as an integer.""" + :param address: The memory address. + :return: The value at that address as an integer. + """ ... - def __setitem__(self, address: int, value: int) -> None: - """Establece un valor en la dirección dada. (configurar elemento) + """Set a value at the given address. -:param address: (dirección) La dirección de memoria. -:param value: (valor) El valor entero a establecer.""" + :param address: The memory address. + :param value: The integer value to set. + """ ... + mem8: mem -"""Vista de memoria de 8 bits (byte).""" +"""8-bit (byte) view of memory.""" + mem16: mem -"""Vista de memoria de 16 bits.""" +"""16-bit view of memory.""" + mem32: mem -"""Vista de memoria de 32 bits.""" \ No newline at end of file +"""32-bit view of memory.""" diff --git a/lang/es-es/typeshed/stdlib/math.pyi b/lang/es-es/typeshed/stdlib/math.pyi index f76eef8..f82d4de 100644 --- a/lang/es-es/typeshed/stdlib/math.pyi +++ b/lang/es-es/typeshed/stdlib/math.pyi @@ -1,246 +1,273 @@ -"""Funciones matemáticas. (matemáticas)""" +"""Mathematical functions. +""" + from typing import Tuple def acos(x: float) -> float: - """Calcula el inverso del coseno. + """Calculate the inverse cosine. -Example: ``math.acos(1)`` + Example: ``math.acos(1)`` -:param x: Un número -:return: The inverse cosine of ``x``""" + :param x: A number + :return: The inverse cosine of ``x`` + """ ... def asin(x: float) -> float: - """Calcula el inverso del seno. (asen) + """Calculate the inverse sine. -Example: ``math.asin(0)`` + Example: ``math.asin(0)`` -:param x: Un número -:return: The inverse sine of ``x``""" + :param x: A number + :return: The inverse sine of ``x`` + """ ... def atan(x: float) -> float: - """Calcula el inverso de la tangente. + """Calculate the inverse tangent. -Example: ``math.atan(0)`` + Example: ``math.atan(0)`` -:param x: Un número -:return: The inverse tangent of ``x``""" + :param x: A number + :return: The inverse tangent of ``x`` + """ ... def atan2(y: float, x: float) -> float: - """Calcula el valor principal del inverso de la tangente de ``y/x``. + """Calculate the principal value of the inverse tangent of ``y/x``. -Example: ``math.atan2(0, -1)`` + Example: ``math.atan2(0, -1)`` -:param y: Un número -:param x: Un número -:return: The principal value of the inverse tangent of ``y/x``""" + :param y: A number + :param x: A number + :return: The principal value of the inverse tangent of ``y/x`` + """ ... def ceil(x: float) -> float: - """Redondea un número hacia el infinito positivo. (hacia arriba) + """Round a number towards positive infinity. -Example: ``math.ceil(0.1)`` + Example: ``math.ceil(0.1)`` -:param x: Un número -:return: ``x`` rounded towards positive infinity.""" + :param x: A number + :return: ``x`` rounded towards positive infinity. + """ ... def copysign(x: float, y: float) -> float: - """Calcula ``x`` con el signo de ``y``. + """Calculate ``x`` with the sign of ``y``. -Example: ``math.copysign(1, -1)`` + Example: ``math.copysign(1, -1)`` -:param x: Un número -:param y: Procedencia del signo para el valor que devuelve -:return: ``x`` with the sign of ``y``""" + :param x: A number + :param y: The source of the sign for the return value + :return: ``x`` with the sign of ``y`` + """ ... def cos(x: float) -> float: - """Calcula el coseno de ``x``. + """Calculate the cosine of ``x``. -Example: ``math.cos(0)`` + Example: ``math.cos(0)`` -:param x: Un número -:return: The cosine of ``x``""" + :param x: A number + :return: The cosine of ``x`` + """ ... def degrees(x: float) -> float: - """Convierte radianes a grados. (grados) + """Convert radians to degrees. -Example: ``math.degrees(2 * math.pi)`` + Example: ``math.degrees(2 * math.pi)`` -:param x: Un valor en radianes -:return: The value converted to degrees""" + :param x: A value in radians + :return: The value converted to degrees""" ... def exp(x: float) -> float: - """Calcular el exponencial de ``x``. + """Calculate the exponential of ``x``. -Example: ``math.exp(1)`` + Example: ``math.exp(1)`` -:param x: Un número -:return: The exponential of ``x``.""" + :param x: A number + :return: The exponential of ``x``. + """ ... def fabs(x: float) -> float: - """Devuelve el valor absoluto de ``x``. + """Return the absolute value of ``x``. -Example: ``math.fabs(-0.1)`` + Example: ``math.fabs(-0.1)`` -:param x: Un número -:return: The absolute value of ``x``""" + :param x: A number + :return: The absolute value of ``x`` + """ ... def floor(x: float) -> int: - """Redondea un número hacia el infinito negativo. (hacia abajo) + """Round a number towards negative infinity. -Example: ``math.floor(0.9)`` + Example: ``math.floor(0.9)`` -:param x: Un número -:return: ``x`` rounded towards negative infinity.""" + :param x: A number + :return: ``x`` rounded towards negative infinity. + """ ... def fmod(x: float, y: float) -> float: - """Calcula el resto de ``x/y``. + """Calculate the remainder of ``x/y``. -Example: ``math.fmod(10, 3)`` + Example: ``math.fmod(10, 3)`` -:param x: El numerador -:param y: El denominador""" + :param x: The numerator + :param y: The denominator + """ ... def frexp(x: float) -> Tuple[float, int]: - """Descompone un número de coma flotante en su mantisa y exponente. + """Decomposes a floating-point number into its mantissa and exponent. -Example: ``mantissa, exponent = math.frexp(2)`` + Example: ``mantissa, exponent = math.frexp(2)`` -The returned value is the tuple ``(m, e)`` such that ``x == m * 2**e`` -exactly. If ``x == 0`` then the function returns ``(0.0, 0)``, otherwise -the relation ``0.5 <= abs(m) < 1`` holds. + The returned value is the tuple ``(m, e)`` such that ``x == m * 2**e`` + exactly. If ``x == 0`` then the function returns ``(0.0, 0)``, otherwise + the relation ``0.5 <= abs(m) < 1`` holds. -:param x: Un número de coma flotante -:return: A tuple of length two containing its mantissa then exponent""" + :param x: A floating-point number + :return: A tuple of length two containing its mantissa then exponent + """ ... def isfinite(x: float) -> bool: - """Comprueba si un valor es finito. (esfinito) + """Check if a value is finite. -Example: ``math.isfinite(float('inf'))`` + Example: ``math.isfinite(float('inf'))`` -:param x: Un número. -:return: ``True`` if ``x`` is finite, ``False`` otherwise.""" + :param x: A number. + :return: ``True`` if ``x`` is finite, ``False`` otherwise. + """ ... def isinf(x: float) -> bool: - """Compruebe si un valor es infinito. (esinf) + """Check if a value is infinite. -Example: ``math.isinf(float('-inf'))`` + Example: ``math.isinf(float('-inf'))`` -:param x: Un número. -:return: ``True`` if ``x`` is infinite, ``False`` otherwise.""" + :param x: A number. + :return: ``True`` if ``x`` is infinite, ``False`` otherwise. + """ ... def isnan(x: float) -> bool: - """Comprueba si un valor no es un número (NaN, not-a-number en inglés). (esnan) + """Check if a value is not-a-number (NaN). -Example: ``math.isnan(float('nan'))`` + Example: ``math.isnan(float('nan'))`` -:param x: Un número -:return: ``True`` if ``x`` is not-a-number (NaN), ``False`` otherwise.""" + :param x: A number + :return: ``True`` if ``x`` is not-a-number (NaN), ``False`` otherwise.""" ... def ldexp(x: float, exp: int) -> float: - """Calcula ``x * (2**exp)``. + """Calculate ``x * (2**exp)``. -Example: ``math.ldexp(0.5, 2)`` + Example: ``math.ldexp(0.5, 2)`` -:param x: Un número -:param exp: Exponente entero -:return: ``x * (2**exp)``""" + :param x: A number + :param exp: Integer exponent + :return: ``x * (2**exp)`` + """ ... -def log(x: float, base: float=e) -> float: - """Calcula el logaritmo de ``x`` en la base dada (por defecto, el logaritmo natural). (registrar) +def log(x: float, base: float = e) -> float: + """Calculate the logarithm of ``x`` to the given base (defaults to natural logorithm). -Example: ``math.log(math.e)`` + Example: ``math.log(math.e)`` -With one argument, return the natural logarithm of x (to base e). + With one argument, return the natural logarithm of x (to base e). -With two arguments, return the logarithm of x to the given base, calculated as ``log(x)/log(base)``. + With two arguments, return the logarithm of x to the given base, calculated as ``log(x)/log(base)``. -:param x: Un número -:param base: La base a usar -:return: The natural logarithm of ``x``""" + :param x: A number + :param base: The base to use + :return: The natural logarithm of ``x`` + """ ... def modf(x: float) -> Tuple[float, float]: - """Calcula la parte fraccionaria y entera de ``x``. + """Calculate the fractional and integral parts of ``x``. -Example: ``fractional, integral = math.modf(1.5)`` + Example: ``fractional, integral = math.modf(1.5)`` -:param x: Un número -:return: A tuple of two floats representing the fractional then integral parts of ``x``. + :param x: A number + :return: A tuple of two floats representing the fractional then integral parts of ``x``. -Both the fractional and integral values have the same sign as ``x``.""" + Both the fractional and integral values have the same sign as ``x``. + """ ... def pow(x: float, y: float) -> float: - """Devuelve ``x`` elevado a ``y``. + """Returns ``x`` to the power of ``y``. -Example: ``math.pow(4, 0.5)`` + Example: ``math.pow(4, 0.5)`` -:param x: Un número -:param y: El exponente -:return: ``x`` to the power of ``y``""" + :param x: A number + :param y: The exponent + :return: ``x`` to the power of ``y`` + """ ... def radians(x: float) -> float: - """Convierte grados a radianes. (radianes) + """Convert a degrees to radians. -Example: ``math.radians(360)`` + Example: ``math.radians(360)`` -:param x: Un valor en grados -:return: The value converted to radians""" + :param x: A value in degrees + :return: The value converted to radians + """ ... def sin(x: float) -> float: - """Calcula el seno de ``x``. (sen) + """Calculate the sine of ``x``. -Example: ``math.sin(math.pi/2)`` + Example: ``math.sin(math.pi/2)`` -:param x: Un número -:return: The sine of ``x``""" + :param x: A number + :return: The sine of ``x`` + """ ... def sqrt(x: float) -> float: - """Calcula la raíz cuadrada de ``x``. + """Calculate the square root of ``x``. -Example: ``math.sqrt(4)`` + Example: ``math.sqrt(4)`` -:param x: Un número -:return: The square root of ``x``""" + :param x: A number + :return: The square root of ``x`` + """ ... def tan(x: float) -> float: - """Calcula la tangente de ``x``. + """Calculate the tangent of ``x``. -Example: ``math.tan(0)`` + Example: ``math.tan(0)`` -:param x: Un número -:return: The tangent of ``x``.""" + :param x: A number + :return: The tangent of ``x``. + """ ... def trunc(x: float) -> int: - """Redondea un número hacia 0. + """Round a number towards 0. -Example: ``math.trunc(-0.9)`` + Example: ``math.trunc(-0.9)`` -:param x: Un número -:return: ``x`` rounded towards zero.""" + :param x: A number + :return: ``x`` rounded towards zero. + """ ... + e: float -"""Base del logaritmo natural""" +"""Base of the natural logarithm""" + pi: float -"""La relación entre la longitud de una circunferencia y su diámetro""" \ No newline at end of file +"""The ratio of a circle's circumference to its diameter""" diff --git a/lang/es-es/typeshed/stdlib/microbit/__init__.pyi b/lang/es-es/typeshed/stdlib/microbit/__init__.pyi index af9a99d..f12158f 100644 --- a/lang/es-es/typeshed/stdlib/microbit/__init__.pyi +++ b/lang/es-es/typeshed/stdlib/microbit/__init__.pyi @@ -1,6 +1,11 @@ -"""Pines, imágenes, sonidos, temperatura y volumen.""" +"""Pins, images, sounds, temperature and volume. +""" + from typing import Any, Callable, List, Optional, Tuple, Union, overload + from _typeshed import ReadableBuffer + +# V2 only from . import accelerometer as accelerometer from . import audio as audio from . import compass as compass @@ -11,699 +16,831 @@ from . import speaker as speaker from . import spi as spi from . import uart as uart -def run_every(callback: Optional[Callable[[], None]]=None, days: int=0, h: int=0, min: int=0, s: int=0, ms: int=0) -> Callable[[Callable[[], None]], Callable[[], None]]: - """Programa la ejecución de una función en el intervalo especificado por los argumentos de tiempo **Sólo V2**. (ejecutar cada) +def run_every( + callback: Optional[Callable[[], None]] = None, + days: int = 0, + h: int = 0, + min: int = 0, + s: int = 0, + ms: int = 0, +) -> Callable[[Callable[[], None]], Callable[[], None]]: + """Schedule to run a function at the interval specified by the time arguments **V2 only**. -Example: ``run_every(my_logging, min=5)`` + Example: ``run_every(my_logging, min=5)`` -``run_every`` can be used in two ways: + ``run_every`` can be used in two ways: -As a Decorator - placed on top of the function to schedule. For example:: + As a Decorator - placed on top of the function to schedule. For example:: - @run_every(h=1, min=20, s=30, ms=50) - def my_function(): - # Do something here + @run_every(h=1, min=20, s=30, ms=50) + def my_function(): + # Do something here -As a Function - passing the callback as a positional argument. For example:: + As a Function - passing the callback as a positional argument. For example:: - def my_function(): - # Do something here - run_every(my_function, s=30) + def my_function(): + # Do something here + run_every(my_function, s=30) -Each argument corresponds to a different time unit and they are additive. -So ``run_every(min=1, s=30)`` schedules the callback every minute and a half. + Each argument corresponds to a different time unit and they are additive. + So ``run_every(min=1, s=30)`` schedules the callback every minute and a half. -When an exception is thrown inside the callback function it deschedules the -function. To avoid this you can catch exceptions with ``try/except``. + When an exception is thrown inside the callback function it deschedules the + function. To avoid this you can catch exceptions with ``try/except``. -:param callback: Función a llamar en el intervalo proporcionado. Omitir cuando se utiliza como un decorador. -:param days: (días) Configura la marca del día para la programación. -:param h: Configura la marca de la hora para la programación. -:param min: Configura la marca de los minutos para la programación. -:param s: Configura la segunda marca para la programación. -:param ms: Configura la marca de los milisegundos para la programación.""" + :param callback: Function to call at the provided interval. Omit when using as a decorator. + :param days: Sets the day mark for the scheduling. + :param h: Sets the hour mark for the scheduling. + :param min: Sets the minute mark for the scheduling. + :param s: Sets the second mark for the scheduling. + :param ms: Sets the millisecond mark for the scheduling. + """ def panic(n: int) -> None: - """Entra en modo pánico (pánico) + """Enter a panic mode. -Example: ``panic(127)`` + Example: ``panic(127)`` -:param n: Un entero arbitrario <= 255 para indicar un estado. + :param n: An arbitrary integer <= 255 to indicate a status. -Requires restart.""" + Requires restart. + """ def reset() -> None: - """Reiniciar la placa. (restablecer)""" + """Restart the board.""" + @overload def scale(value: float, from_: Tuple[float, float], to: Tuple[int, int]) -> int: - """Convierte un valor de un rango a un rango de números enteros. (escala) + """Converts a value from a range to an integer range. -Example: ``volume = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255))`` + Example: ``volume = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255))`` -For example, to convert an accelerometer X value to a speaker volume. + For example, to convert an accelerometer X value to a speaker volume. -If one of the numbers in the ``to`` parameter is a floating point -(i.e a decimal number like ``10.0``), this function will return a -floating point number. + If one of the numbers in the ``to`` parameter is a floating point + (i.e a decimal number like ``10.0``), this function will return a + floating point number. - temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0)) + temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0)) -:param value: (valor) Un número a convertir. -:param from_: (de) Una tupla para definir el rango desde el que convertir. -:param to: (a) Una tupla para definir el rango al que convertir. -:return: The ``value`` converted to the ``to`` range.""" + :param value: A number to convert. + :param from_: A tuple to define the range to convert from. + :param to: A tuple to define the range to convert to. + :return: The ``value`` converted to the ``to`` range. + """ @overload def scale(value: float, from_: Tuple[float, float], to: Tuple[float, float]) -> float: - """Convierte un valor de un rango a un rango de punto flotante. (escala) + """Converts a value from a range to a floating point range. -Example: ``temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0))`` + Example: ``temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0))`` -For example, to convert temperature from a Celsius scale to Fahrenheit. + For example, to convert temperature from a Celsius scale to Fahrenheit. -If one of the numbers in the ``to`` parameter is a floating point -(i.e a decimal number like ``10.0``), this function will return a -floating point number. -If they are both integers (i.e ``10``), it will return an integer:: + If one of the numbers in the ``to`` parameter is a floating point + (i.e a decimal number like ``10.0``), this function will return a + floating point number. + If they are both integers (i.e ``10``), it will return an integer:: - returns_int = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255)) + returns_int = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255)) -:param value: (valor) Un número a convertir. -:param from_: (de) Una tupla para definir el rango desde el que convertir. -:param to: (a) Una tupla para definir el rango al que convertir. -:return: The ``value`` converted to the ``to`` range.""" + :param value: A number to convert. + :param from_: A tuple to define the range to convert from. + :param to: A tuple to define the range to convert to. + :return: The ``value`` converted to the ``to`` range. + """ def sleep(n: float) -> None: - """Espera ``n`` milisegundos. (dormir) + """Wait for ``n`` milliseconds. -Example: ``sleep(1000)`` + Example: ``sleep(1000)`` -:param n: El número de milisegundos a esperar + :param n: The number of milliseconds to wait -One second is 1000 milliseconds, so:: + One second is 1000 milliseconds, so:: - microbit.sleep(1000) + microbit.sleep(1000) -will pause the execution for one second.""" + will pause the execution for one second. + """ def running_time() -> int: - """Obtiene el tiempo de funcionamiento de la placa. (tiempo de ejecución) + """Get the running time of the board. -:return: The number of milliseconds since the board was switched on or restarted.""" + :return: The number of milliseconds since the board was switched on or restarted. + """ def temperature() -> int: - """Obtiene la temperatura del micro:bit en grados Celsius. (temperatura)""" + """Get the temperature of the micro:bit in degrees Celsius.""" def set_volume(v: int) -> None: - """Establece el volumen. (configurar volumen) + """Sets the volume. -Example: ``set_volume(127)`` + Example: ``set_volume(127)`` -:param v: un valor entre 0 (bajo) y 255 (alto). + :param v: a value between 0 (low) and 255 (high). -Out of range values will be clamped to 0 or 255. + Out of range values will be clamped to 0 or 255. -**V2** only.""" + **V2** only. + """ ... class Button: - """La clase para los botones ``button_a`` y ``button_b``. (botón)""" + """The class for the buttons ``button_a`` and ``button_b``.""" def is_pressed(self) -> bool: - """Comprueba si el botón está pulsado. (está pulsado) + """Check if the button is pressed. -:return: ``True`` if the specified button ``button`` is pressed, and ``False`` otherwise.""" + :return: ``True`` if the specified button ``button`` is pressed, and ``False`` otherwise. + """ ... - def was_pressed(self) -> bool: - """Comprueba si el botón ha sido pulsado desde que se inció el dispositivo o desde la última vez que se llamó a este método. (ha sido pulsado) + """Check if the button was pressed since the device started or the last time this method was called. -Calling this method will clear the press state so -that the button must be pressed again before this method will return -``True`` again. + Calling this method will clear the press state so + that the button must be pressed again before this method will return + ``True`` again. -:return: ``True`` if the specified button ``button`` was pressed, and ``False`` otherwise""" + :return: ``True`` if the specified button ``button`` was pressed, and ``False`` otherwise + """ ... - def get_presses(self) -> int: - """Obtiene el total de pulsaciones sucesivas de un botón y restablece este total -a cero. (total de pulsaciones) + """Get the running total of button presses, and resets this total + to zero before returning. -:return: The number of presses since the device started or the last time this method was called""" + :return: The number of presses since the device started or the last time this method was called + """ ... + button_a: Button -"""Objeto ``Button`` para el botón izquierdo. (botón a)""" +"""The left button ``Button`` object.""" + button_b: Button -"""Objeto ``Button`` para el botón derecho. (botón b)""" +"""The right button ``Button`` object.""" class MicroBitDigitalPin: - """Un pin digital. (pin digital microbit) + """A digital pin. + + Some pins support analog and touch features using the ``MicroBitAnalogDigitalPin`` and ``MicroBitTouchPin`` subclasses. + """ -Some pins support analog and touch features using the ``MicroBitAnalogDigitalPin`` and ``MicroBitTouchPin`` subclasses.""" NO_PULL: int PULL_UP: int PULL_DOWN: int - def read_digital(self) -> int: - """Obtiene el valor digital del pin. (lectura digital) + """Get the digital value of the pin. -Example: ``value = pin0.read_digital()`` + Example: ``value = pin0.read_digital()`` -:return: 1 if the pin is high, and 0 if it's low.""" + :return: 1 if the pin is high, and 0 if it's low. + """ ... - def write_digital(self, value: int) -> None: - """Establece el valor digital del pin. (escritura digital) + """Set the digital value of the pin. -Example: ``pin0.write_digital(1)`` + Example: ``pin0.write_digital(1)`` -:param value: (valor) 1 para establecer valor alto en el pin o 0 para valor bajo""" + :param value: 1 to set the pin high or 0 to set the pin low""" ... - def set_pull(self, value: int) -> None: - """Configura el estado "pull" con uno de los tres valores posibles: ``PULL_UP``, ``PULL_DOWN`` o ``NO_PULL``. (configurar pull) + """Set the pull state to one of three possible values: ``PULL_UP``, ``PULL_DOWN`` or ``NO_PULL``. -Example: ``pin0.set_pull(pin0.PULL_UP)`` + Example: ``pin0.set_pull(pin0.PULL_UP)`` -:param value: (valor) El estado "pull" del pin correspondiente, p. ej., ``pin0.PULL_UP``.""" + :param value: The pull state from the relevant pin, e.g. ``pin0.PULL_UP``. + """ ... - def get_pull(self) -> int: - """Obtiene el estado "pull" de un pin. (obtener pull) + """Get the pull state on a pin. -Example: ``pin0.get_pull()`` + Example: ``pin0.get_pull()`` -:return: ``NO_PULL``, ``PULL_DOWN``, or ``PULL_UP`` + :return: ``NO_PULL``, ``PULL_DOWN``, or ``PULL_UP`` -These are set using the ``set_pull()`` method or automatically configured -when a pin mode requires it.""" + These are set using the ``set_pull()`` method or automatically configured + when a pin mode requires it. + """ ... - def get_mode(self) -> str: - """Devuelve el modo del pin. (obtener modo) + """Returns the pin mode. -Example: ``pin0.get_mode()`` + Example: ``pin0.get_mode()`` -When a pin is used for a specific function, like -writing a digital value, or reading an analog value, the pin mode -changes. + When a pin is used for a specific function, like + writing a digital value, or reading an analog value, the pin mode + changes. -:return: ``"unused"``, ``"analog"``, ``"read_digital"``, ``"write_digital"``, ``"display"``, ``"button"``, ``"music"``, ``"audio"``, ``"touch"``, ``"i2c"``, or ``"spi"``""" + :return: ``"unused"``, ``"analog"``, ``"read_digital"``, ``"write_digital"``, ``"display"``, ``"button"``, ``"music"``, ``"audio"``, ``"touch"``, ``"i2c"``, or ``"spi"`` + """ ... - def write_analog(self, value: int) -> None: - """Envía una señal PWM al pin, con el ciclo de trabajo proporcional a ``value``. (escritura analógica) - -Example: ``pin0.write_analog(254)`` + """Output a PWM signal on the pin, with the duty cycle proportional to ``value``. -:param value: (valor) Un número entero o de coma flotante entre 0 (ciclo de trabajo de 0 %) y 1023 (100 %).""" + Example: ``pin0.write_analog(254)`` + :param value: An integer or a floating point number between 0 (0% duty cycle) and 1023 (100% duty). + """ def set_analog_period(self, period: int) -> None: - """Establece el período de la señal PWM enviada a ``period`` milisegundos. (configurar periodo analógico) + """Set the period of the PWM signal being output to ``period`` in milliseconds. -Example: ``pin0.set_analog_period(10)`` - -:param period: (período) El período en milisegundos con un valor mínimo válido de 1 ms.""" + Example: ``pin0.set_analog_period(10)`` + :param period: The period in milliseconds with a minimum valid value of 1ms. + """ def set_analog_period_microseconds(self, period: int) -> None: - """Establece el período de la señal PWM enviada a ``period`` microsegundos. (configurar periodo analógico en microsegundos) + """Set the period of the PWM signal being output to ``period`` in microseconds. -Example: ``pin0.set_analog_period_microseconds(512)`` + Example: ``pin0.set_analog_period_microseconds(512)`` -:param period: (período) El período en microsegundos con un valor mínimo válido de 256 μs.""" + :param period: The period in microseconds with a minimum valid value of 256µs. + """ class MicroBitAnalogDigitalPin(MicroBitDigitalPin): - """Un pin con características analógicas y digitales. (pin digital y analógico microbit)""" + """A pin with analog and digital features.""" def read_analog(self) -> int: - """Lee el voltaje aplicado al pin. (lectura analógica) + """Read the voltage applied to the pin. -Example: ``pin0.read_analog()`` + Example: ``pin0.read_analog()`` -:return: An integer between 0 (meaning 0V) and 1023 (meaning 3.3V).""" + :return: An integer between 0 (meaning 0V) and 1023 (meaning 3.3V). + """ class MicroBitTouchPin(MicroBitAnalogDigitalPin): - """Un pin con características analógicas, digitales y táctiles. (pin táctil microbit)""" + """A pin with analog, digital and touch features.""" + CAPACITIVE: int RESISTIVE: int - def is_touched(self) -> bool: - """Comprueba si se está tocando el pin. (está tocado) + """Check if the pin is being touched. -Example: ``pin0.is_touched()`` + Example: ``pin0.is_touched()`` -The default touch mode for the pins on the edge connector is ``resistive``. -The default for the logo pin **V2** is ``capacitive``. + The default touch mode for the pins on the edge connector is ``resistive``. + The default for the logo pin **V2** is ``capacitive``. -**Resistive touch** -This test is done by measuring how much resistance there is between the -pin and ground. A low resistance gives a reading of ``True``. To get -a reliable reading using a finger you may need to touch the ground pin -with another part of your body, for example your other hand. + **Resistive touch** + This test is done by measuring how much resistance there is between the + pin and ground. A low resistance gives a reading of ``True``. To get + a reliable reading using a finger you may need to touch the ground pin + with another part of your body, for example your other hand. -**Capacitive touch** -This test is done by interacting with the electric field of a capacitor -using a finger as a conductor. `Capacitive touch -`_ -does not require you to make a ground connection as part of a circuit. + **Capacitive touch** + This test is done by interacting with the electric field of a capacitor + using a finger as a conductor. `Capacitive touch + `_ + does not require you to make a ground connection as part of a circuit. -:return: ``True`` if the pin is being touched with a finger, otherwise return ``False``.""" + :return: ``True`` if the pin is being touched with a finger, otherwise return ``False``. + """ ... - def set_touch_mode(self, value: int) -> None: - """Establece el modo táctil del pin. (configurar modo táctil) + """Set the touch mode for the pin. -Example: ``pin0.set_touch_mode(pin0.CAPACITIVE)`` + Example: ``pin0.set_touch_mode(pin0.CAPACITIVE)`` -The default touch mode for the pins on the edge connector is -``resistive``. The default for the logo pin **V2** is ``capacitive``. + The default touch mode for the pins on the edge connector is + ``resistive``. The default for the logo pin **V2** is ``capacitive``. -:param value: (valor) ``CAPACITIVE`` o ``RESISTIVE`` del pin correspondiente.""" + :param value: ``CAPACITIVE`` or ``RESISTIVE`` from the relevant pin. + """ ... + pin0: MicroBitTouchPin -"""Pin con funciones digitales, analógicas y táctiles.""" +"""Pin with digital, analog and touch features.""" + pin1: MicroBitTouchPin -"""Pin con funciones digitales, analógicas y táctiles.""" +"""Pin with digital, analog and touch features.""" + pin2: MicroBitTouchPin -"""Pin con funciones digitales, analógicas y táctiles.""" +"""Pin with digital, analog and touch features.""" + pin3: MicroBitAnalogDigitalPin -"""Pin con funciones digitales y analógicas.""" +"""Pin with digital and analog features.""" + pin4: MicroBitAnalogDigitalPin -"""Pin con funciones digitales y analógicas.""" +"""Pin with digital and analog features.""" + pin5: MicroBitDigitalPin -"""Pin con funciones digitales.""" +"""Pin with digital features.""" + pin6: MicroBitDigitalPin -"""Pin con funciones digitales.""" +"""Pin with digital features.""" + pin7: MicroBitDigitalPin -"""Pin con funciones digitales.""" +"""Pin with digital features.""" + pin8: MicroBitDigitalPin -"""Pin con funciones digitales.""" +"""Pin with digital features.""" + pin9: MicroBitDigitalPin -"""Pin con funciones digitales.""" +"""Pin with digital features.""" + pin10: MicroBitAnalogDigitalPin -"""Pin con funciones digitales y analógicas.""" +"""Pin with digital and analog features.""" + pin11: MicroBitDigitalPin -"""Pin con funciones digitales.""" +"""Pin with digital features.""" + pin12: MicroBitDigitalPin -"""Pin con funciones digitales.""" +"""Pin with digital features.""" + pin13: MicroBitDigitalPin -"""Pin con funciones digitales.""" +"""Pin with digital features.""" + pin14: MicroBitDigitalPin -"""Pin con funciones digitales.""" +"""Pin with digital features.""" + pin15: MicroBitDigitalPin -"""Pin con funciones digitales.""" +"""Pin with digital features.""" + pin16: MicroBitDigitalPin -"""Pin con funciones digitales.""" +"""Pin with digital features.""" + pin19: MicroBitDigitalPin -"""Pin con funciones digitales.""" +"""Pin with digital features.""" + pin20: MicroBitDigitalPin -"""Pin con funciones digitales.""" +"""Pin with digital features.""" + pin_logo: MicroBitTouchPin -"""Un pin táctil sensible en la parte frontal del micro:bit que por defecto está configurado en modo táctil capacitivo. (pin de logo)""" +"""A touch sensitive logo pin on the front of the micro:bit, which by default is set to capacitive touch mode.""" + pin_speaker: MicroBitAnalogDigitalPin -"""Un pin para dirigirse al altavoz micro:bit. (pin de altavoz) +"""A pin to address the micro:bit speaker. This API is intended only for use in Pulse-Width Modulation pin operations e.g. pin_speaker.write_analog(128). """ class Image: - """Una imagen que se mostrará en la pantalla LED del micro:bit. (imagen) + """An image to show on the micro:bit LED display. -Given an image object it's possible to display it via the ``display`` API:: + Given an image object it's possible to display it via the ``display`` API:: + + display.show(Image.HAPPY) + """ - display.show(Image.HAPPY)""" HEART: Image - """Imagen de un corazón. (corazón)""" + """Heart image.""" + HEART_SMALL: Image - """Imagen de un corazón pequeño. (corazón pequeño)""" + """Small heart image.""" + HAPPY: Image - """Imagen de una cara feliz. (feliz)""" + """Happy face image.""" + SMILE: Image - """Imagen de una cara sonriente. (sonrisa)""" + """Smiling mouth image.""" + SAD: Image - """Imagen de una cara triste. (triste)""" + """Sad face image.""" + CONFUSED: Image - """Imagen de una cara confundida. (confundida)""" + """Confused face image.""" + ANGRY: Image - """Imagen de una cara enfadada. (enfadada)""" + """Angry face image.""" + ASLEEP: Image - """Imagen de una cara durmiendo. (dormida)""" + """Sleeping face image.""" + SURPRISED: Image - """Imagen de una cara sorprendida. (sorprendida)""" + """Surprised face image.""" + SILLY: Image - """Imagen de una cara tonta. (tonta)""" + """Silly face image.""" + FABULOUS: Image - """Imagen de una cara con gafas de sol. (fabulosa)""" + """Sunglasses face image.""" + MEH: Image - """Imagen de una cara indiferente. (indiferente)""" + """Unimpressed face image.""" + YES: Image - """Imagen de verificación. (sí)""" + """Tick image.""" + NO: Image - """Imagen de cruz.""" + """Cross image.""" + CLOCK12: Image - """Imagen de una línea apuntando a las 12:00. (reloj12)""" + """Image with line pointing to 12 o'clock.""" + CLOCK11: Image - """Imagen de una línea apuntando a las 11:00. (reloj11)""" + """Image with line pointing to 11 o'clock.""" + CLOCK10: Image - """Imagen de una línea apuntando a las 10:00. (reloj10)""" + """Image with line pointing to 10 o'clock.""" + CLOCK9: Image - """Imagen de una línea apuntando a las 9:00. (reloj9)""" + """Image with line pointing to 9 o'clock.""" + CLOCK8: Image - """Imagen de una línea apuntando a las 8:00. (reloj8)""" + """Image with line pointing to 8 o'clock.""" + CLOCK7: Image - """Imagen de una línea apuntando a las 7:00. (reloj7)""" + """Image with line pointing to 7 o'clock.""" + CLOCK6: Image - """Imagen de una línea apuntando a las 6:00. (reloj6)""" + """Image with line pointing to 6 o'clock.""" + CLOCK5: Image - """Imagen de una línea apuntando a las 5:00. (reloj5)""" + """Image with line pointing to 5 o'clock.""" + CLOCK4: Image - """Imagen de una línea apuntando a las 4:00. (reloj4)""" + """Image with line pointing to 4 o'clock.""" + CLOCK3: Image - """Imagen de una línea apuntando a las 3:00. (reloj3)""" + """Image with line pointing to 3 o'clock.""" + CLOCK2: Image - """Imagen de una línea apuntando a las 2:00. (reloj2)""" + """Image with line pointing to 2 o'clock.""" + CLOCK1: Image - """Imagen de una línea apuntando a la 1:00. (reloj1)""" + """Image with line pointing to 1 o'clock.""" + ARROW_N: Image - """Imagen de una flecha apuntando hacia el norte. (flecha n)""" + """Image of arrow pointing north.""" + ARROW_NE: Image - """Imagen de una flecha apuntando hacia el nordeste. (flecha ne)""" + """Image of arrow pointing north east.""" + ARROW_E: Image - """Imagen de una flecha apuntando hacia el este. (flecha e)""" + """Image of arrow pointing east.""" + ARROW_SE: Image - """Imagen de una flecha apuntando hacia el sudeste. (flecha se)""" + """Image of arrow pointing south east.""" + ARROW_S: Image - """Imagen de una flecha apuntando hacia el sur. (flecha s)""" + """Image of arrow pointing south.""" + ARROW_SW: Image - """Imagen de una flecha apuntando hacia el sudoeste. (flecha so)""" + """Image of arrow pointing south west.""" + ARROW_W: Image - """Imagen de una flecha apuntando hacia el oeste. (flecha o)""" + """Image of arrow pointing west.""" + ARROW_NW: Image - """Imagen de una flecha apuntando hacia el noroeste. (flecha no)""" + """Image of arrow pointing north west.""" + TRIANGLE: Image - """Imagen de un triángulo apuntando hacia arriba. (triángulo)""" + """Image of a triangle pointing up.""" + TRIANGLE_LEFT: Image - """Imagen de un triángulo en la esquina izquierda. (triángulo izquierda)""" + """Image of a triangle in the left corner.""" + CHESSBOARD: Image - """LED iluminados de forma alterna según un patrón de tablero de ajedrez. (tablero de ajedrez)""" + """Alternate LEDs lit in a chessboard pattern.""" + DIAMOND: Image - """Imagen de un diamante. (diamante)""" + """Diamond image.""" + DIAMOND_SMALL: Image - """Imagen de un diamante pequeño. (diamante pequeño)""" + """Small diamond image.""" + SQUARE: Image - """Imagen de un cuadrado. (cuadrado)""" + """Square image.""" + SQUARE_SMALL: Image - """Imagen de un cuadrado pequeño. (cuadrado pequeño)""" + """Small square image.""" + RABBIT: Image - """Imagen de un conejo. (conejo)""" + """Rabbit image.""" + COW: Image - """Imagen de una vaca. (vaca)""" + """Cow image.""" + MUSIC_CROTCHET: Image - """Imagen de una nota negra. (negra musical)""" + """Crotchet note image.""" + MUSIC_QUAVER: Image - """Imagen de una nota corchea. (corchea musical)""" + """Quaver note image.""" + MUSIC_QUAVERS: Image - """Imagen de un par de notas corcheas. (corcheas musicales)""" + """Pair of quavers note image.""" + PITCHFORK: Image - """Imagen de una horca. (horca)""" + """Pitchfork image.""" + XMAS: Image - """Imagen de un árbol de Navidad. (navidad)""" + """Christmas tree image.""" + PACMAN: Image - """Imagen del personaje de videojuegos Pac-Man.""" + """Pac-Man arcade character image.""" + TARGET: Image - """Imagen de un objetivo. (diana)""" + """Target image.""" + TSHIRT: Image - """Imagen de una camiseta. (camiseta)""" + """T-shirt image.""" + ROLLERSKATE: Image - """Imagen de un patín. (patín)""" + """Rollerskate image.""" + DUCK: Image - """Imagen de un pato. (pato)""" + """Duck image.""" + HOUSE: Image - """Imagen de una casa. (casa)""" + """House image.""" + TORTOISE: Image - """Imagen de una tortuga. (tortuga)""" + """Tortoise image.""" + BUTTERFLY: Image - """Imagen de una mariposa. (mariposa)""" + """Butterfly image.""" + STICKFIGURE: Image - """Imagen de un monigote. (monigote)""" + """Stick figure image.""" + GHOST: Image - """Imagen de un fantasma. (fantasma)""" + """Ghost image.""" + SWORD: Image - """Imagen de una espada. (espada)""" + """Sword image.""" + GIRAFFE: Image - """Imagen de una jirafa. (girafa)""" + """Giraffe image.""" + SKULL: Image - """Imagen de una calavera. (calavera)""" + """Skull image.""" + UMBRELLA: Image - """Imagen de un paraguas. (paraguas)""" + """Umbrella image.""" + SNAKE: Image - """Imagen de una serpiente. (serpiente)""" + """Snake image.""" + SCISSORS: Image - """Imagen de tijeras. (tijeras)""" + """Scissors image.""" + ALL_CLOCKS: List[Image] - """Una lista que contiene todas las imágenes CLOCK_ en secuencia. (todos los relojes)""" - ALL_ARROWS: List[Image] - """Una lista que contiene todas las imágenes ARROW_ en secuencia. (todas las flechas)""" + """A list containing all the CLOCK_ images in sequence.""" + ALL_ARROWS: List[Image] + """A list containing all the ARROW_ images in sequence.""" @overload def __init__(self, string: str) -> None: - """Crea una imagen a partir de una cadena que describe los LED que están encendidos. + """Create an image from a string describing which LEDs are lit. -``string`` has to consist of digits 0-9 arranged into lines, -describing the image, for example:: + ``string`` has to consist of digits 0-9 arranged into lines, + describing the image, for example:: - image = Image("90009:" - "09090:" - "00900:" - "09090:" - "90009") + 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 newlines (\\n) insead of the colons. + 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 newlines (\\n) insead of the colons. -:param string: (cadena) La cadena que describe la imagen.""" + :param string: The string describing the image. + """ ... - @overload - def __init__(self, width: int=5, height: int=5, buffer: ReadableBuffer=None) -> None: - """Crea una imagen vacía con ``width`` columnas y ``height`` filas. + def __init__( + self, width: int = 5, height: int = 5, buffer: ReadableBuffer = None + ) -> None: + """Create an empty image with ``width`` columns and ``height`` rows. -:param width: (ancho) Ancho opcional de la imagen -:param height: (altura) Altura opcional de la imagen -:param buffer: (búfer) Matriz opcional de bytes de ``width`` × ``height`` enteros en el rango 0 - 9 para inicializar la imagen + :param width: Optional width of the image + :param height: Optional height of the image + :param buffer: Optional array or bytes of ``width``×``height`` integers in range 0-9 to initialize the image -Examples:: + Examples:: - Image(2, 2, b'\x08\x08\x08\x08') - Image(2, 2, bytearray([9,9,9,9])) + Image(2, 2, b'\x08\x08\x08\x08') + Image(2, 2, bytearray([9,9,9,9])) -These create 2 x 2 pixel images at full brightness.""" + These create 2 x 2 pixel images at full brightness. + """ ... - def width(self) -> int: - """Obtiene el número de columnas. (ancho) + """Get the number of columns. -:return: The number of columns in the image""" + :return: The number of columns in the image + """ ... - def height(self) -> int: - """Obtiene el número de filas. (altura) + """Get the number of rows. -:return: The number of rows in the image""" + :return: The number of rows in the image + """ ... - def set_pixel(self, x: int, y: int, value: int) -> None: - """Establece el brillo de un píxel. (configurar píxel) + """Set the brightness of a pixel. -Example: ``my_image.set_pixel(0, 0, 9)`` + Example: ``my_image.set_pixel(0, 0, 9)`` -:param x: El número de columna -:param y: El número de fila -:param value: (valor) El brillo expresado como un entero entre 0 (oscuro) y 9 (brillante) + :param x: The column number + :param y: The row number + :param value: The brightness as an integer 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``.""" + 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: - """Obtiene el brillo de un píxel. (obtener píxel) + """Get the brightness of a pixel. -Example: ``my_image.get_pixel(0, 0)`` + Example: ``my_image.get_pixel(0, 0)`` -:param x: El número de columna -:param y: El número de fila -:return: The brightness as an integer between 0 and 9.""" + :param x: The column number + :param y: The row number + :return: The brightness as an integer between 0 and 9. + """ ... - def shift_left(self, n: int) -> Image: - """Crea una nueva imagen desplazando la imagen hacia la izquierda. (desplazamiento a la izquierda) + """Create a new image by shifting the picture left. -Example: ``Image.HEART_SMALL.shift_left(1)`` + Example: ``Image.HEART_SMALL.shift_left(1)`` -:param n: El número de columnas a desplazar -:return: The shifted image""" + :param n: The number of columns to shift by + :return: The shifted image + """ ... - def shift_right(self, n: int) -> Image: - """Crea una nueva imagen desplazando la imagen hacia la derecha. (desplazamiento a la derecha) + """Create a new image by shifting the picture right. -Example: ``Image.HEART_SMALL.shift_right(1)`` + Example: ``Image.HEART_SMALL.shift_right(1)`` -:param n: El número de columnas a desplazar -:return: The shifted image""" + :param n: The number of columns to shift by + :return: The shifted image + """ ... - def shift_up(self, n: int) -> Image: - """Crea una nueva imagen desplazando la imagen hacia arriba. (desplazamiento hacia arriba) + """Create a new image by shifting the picture up. -Example: ``Image.HEART_SMALL.shift_up(1)`` + Example: ``Image.HEART_SMALL.shift_up(1)`` -:param n: El número de filas a desplazar -:return: The shifted image""" + :param n: The number of rows to shift by + :return: The shifted image + """ ... - def shift_down(self, n: int) -> Image: - """Crea una nueva imagen desplazando la imagen hacia abajo. (desplazamiento hacia abajo) + """Create a new image by shifting the picture down. -Example: ``Image.HEART_SMALL.shift_down(1)`` + Example: ``Image.HEART_SMALL.shift_down(1)`` -:param n: El número de filas a desplazar -:return: The shifted image""" + :param n: The number of rows to shift by + :return: The shifted image + """ ... - def crop(self, x: int, y: int, w: int, h: int) -> Image: - """Crear una nueva imagen recortando la imagen. (recortar) + """Create a new image by cropping the picture. -Example: ``Image.HEART.crop(1, 1, 3, 3)`` + Example: ``Image.HEART.crop(1, 1, 3, 3)`` -:param x: La columna de desplazamiento del recorte -:param y: La fila de desplazamiento del recorte -:param w: (a) El ancho del recorte -:param h: La altura del recorte -:return: The new image""" + :param x: The crop offset column + :param y: The crop offset row + :param w: The crop width + :param h: The crop height + :return: The new image + """ ... - def copy(self) -> Image: - """Crea una copia exacta de la imagen. (copiar) + """Create an exact copy of the image. -Example: ``Image.HEART.copy()`` + Example: ``Image.HEART.copy()`` -:return: The new image""" + :return: The new image + """ ... - def invert(self) -> Image: - """Crea una nueva imagen invirtiendo el brillo de los píxeles de la -imagen de origen. (invertir) + """Create a new image by inverting the brightness of the pixels in the + source image. -Example: ``Image.SMALL_HEART.invert()`` + Example: ``Image.SMALL_HEART.invert()`` -:return: The new image.""" + :return: The new image. + """ ... - def fill(self, value: int) -> None: - """Establece el brillo de todos los píxeles de la imagen. (llenar) + """Set the brightness of all the pixels in the image. -Example: ``my_image.fill(5)`` + Example: ``my_image.fill(5)`` -:param value: (valor) El nuevo brillo expresado como un número entre 0 (oscuro) y 9 (brillante). + :param value: The new brightness as a number 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``.""" + 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: - """Copia un área de otra imagen en esta imagen. - -Example: ``my_image.blit(Image.HEART, 1, 1, 3, 3, 1, 1)`` - -:param src: (org) La imagen de origen -:param x: El desplazamiento de columna inicial en la imagen de origen -:param y: El desplazamiento de fila inicial en la imagen de origen -:param w: (a) El número de columnas a copiar -:param h: El número de filas a copiar -:param xdest: El desplazamiento de columna a modificar en esta imagen -:param ydest: El desplazamiento de fila a modificar en esta imagen - -Pixels outside the source image are treated as having a brightness 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 blit( + self, + src: Image, + x: int, + y: int, + w: int, + h: int, + xdest: int = 0, + ydest: int = 0, + ) -> None: + """Copy an area from another image into this image. + + Example: ``my_image.blit(Image.HEART, 1, 1, 3, 3, 1, 1)`` + + :param src: The source image + :param x: The starting column offset in the source image + :param y: The starting row offset in the source image + :param w: The number of columns to copy + :param h: The number of rows to copy + :param xdest: The column offset to modify in this image + :param ydest: The row offset to modify in this image + + Pixels outside the source image are treated as having a brightness 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: - """Obtiene una representación en cadena compacta de la imagen.""" + """Get a compact string representation of the image.""" ... - def __str__(self) -> str: - """Obtiene una representación en cadena legible de la imagen. (cad)""" + """Get a readable string representation of the image.""" ... - def __add__(self, other: Image) -> Image: - """Crea una nueva imagen sumando los valores de brillo de las dos imágenes -para cada píxel. (añadir) + """Create a new image by adding the brightness values from the two + images for each pixel. -Example: ``Image.HEART + Image.HAPPY`` + Example: ``Image.HEART + Image.HAPPY`` -:param other: (otro) La imagen a añadir.""" + :param other: The image to add. + """ ... - def __sub__(self, other: Image) -> Image: - """Crea una nueva imagen restando los valores de brillo de la otra imagen a los de esta imagen. (rest) + """Create a new image by subtracting the brightness values of the + other image from this image. -Example: ``Image.HEART - Image.HEART_SMALL`` + Example: ``Image.HEART - Image.HEART_SMALL`` -:param other: (otro) La imagen a restar.""" + :param other: The image to subtract. + """ ... - def __mul__(self, n: float) -> Image: - """Crea una nueva imagen multiplicando el brillo de cada píxel por ``n``. + """Create a new image by multiplying the brightness of each pixel by + ``n``. -Example: ``Image.HEART * 0.5`` + Example: ``Image.HEART * 0.5`` -:param n: El valor por el que multiplicar.""" + :param n: The value to multiply by. + """ ... - def __truediv__(self, n: float) -> Image: - """Crea una nueva imagen dividiendo el brillo de cada píxel entre ``n``. + """Create a new image by dividing the brightness of each pixel by + ``n``. -Example: ``Image.HEART / 2`` + Example: ``Image.HEART / 2`` -:param n: El valor entre el que dividir.""" + :param n: The value to divide by. + """ ... class SoundEvent: LOUD: SoundEvent - """Representa la transición de eventos de sonido, desde ``quiet`` a ``loud``, como aplaudir o gritar. (alto)""" + """Represents the transition of sound events, from ``quiet`` to ``loud`` like clapping or shouting.""" + QUIET: SoundEvent - """Representa la transición de eventos de sonido, desde ``loud`` hasta ``quiet``, como hablar o una música de fondo. (silencioso)""" + """Represents the transition of sound events, from ``loud`` to ``quiet`` like speaking or background music.""" class Sound: - """Los sonidos predefinidos pueden llamarse usando ``audio.play(Sound.NAME)``. (sonido)""" + """The built-in sounds can be called using ``audio.play(Sound.NAME)``.""" + GIGGLE: Sound - """Sonido de risita. (risita)""" + """Giggling sound.""" + HAPPY: Sound - """Sonido alegre. (feliz)""" + """Happy sound.""" + HELLO: Sound - """Sonido de saludo. (hola)""" + """Greeting sound.""" + MYSTERIOUS: Sound - """Sonido misterioso. (misterioso)""" + """Mysterious sound.""" + SAD: Sound - """Sonido triste. (triste)""" + """Sad sound.""" + SLIDE: Sound - """Sonido deslizante. (deslizante)""" + """Sliding sound.""" + SOARING: Sound - """Sonido creciente. (creciente)""" + """Soaring sound.""" + SPRING: Sound - """Sonido de muelle. (muelle)""" + """Spring sound.""" + TWINKLE: Sound - """Sonido parpadeante. (parpadeante)""" + """Twinkling sound.""" + YAWN: Sound - """Sonido de bostezo. (bostezo)""" \ No newline at end of file + """Yawning sound.""" diff --git a/lang/es-es/typeshed/stdlib/microbit/accelerometer.pyi b/lang/es-es/typeshed/stdlib/microbit/accelerometer.pyi index 3d591b4..bac82c0 100644 --- a/lang/es-es/typeshed/stdlib/microbit/accelerometer.pyi +++ b/lang/es-es/typeshed/stdlib/microbit/accelerometer.pyi @@ -1,103 +1,115 @@ -"""Mide la aceleración del micro:bit y reconoce gestos. (acelerómetro)""" +"""Measure the acceleration of the micro:bit and recognise gestures. +""" + from typing import Tuple def get_x() -> int: - """Obtiene la medición de la aceleración en el eje ``x`` en mili-g. (obtener x) + """Get the acceleration measurement in the ``x`` axis in milli-g. -Example: ``accelerometer.get_x()`` + Example: ``accelerometer.get_x()`` -:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" + :return: A positive or negative integer depending on direction in the range +/- 2000mg. + """ ... def get_y() -> int: - """Obtiene la medición de la aceleración en el eje ``y`` en mili-g. (obtener y) + """Get the acceleration measurement in the ``y`` axis in milli-g. -Example: ``accelerometer.get_y()`` + Example: ``accelerometer.get_y()`` -:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" + :return: A positive or negative integer depending on direction in the range +/- 2000mg. + """ ... def get_z() -> int: - """Obtiene la medición de la aceleración en el eje ``z`` en mili-g. (obtener z) + """Get the acceleration measurement in the ``z`` axis in milli-g. -Example: ``accelerometer.get_z()`` + Example: ``accelerometer.get_z()`` -:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" + :return: A positive or negative integer depending on direction in the range +/- 2000mg. + """ ... def get_values() -> Tuple[int, int, int]: - """Obtiene las mediciones de las aceleraciones en todos los ejes como una tupla. (obtener valores) + """Get the acceleration measurements in all axes at once as a tuple. -Example: ``x, y, z = accelerometer.get_values()`` + Example: ``x, y, z = accelerometer.get_values()`` -:return: a three-element tuple of integers ordered as X, Y, Z, each value a positive or negative integer depending on direction in the range +/- 2000mg""" + :return: a three-element tuple of integers ordered as X, Y, Z, each value a positive or negative integer depending on direction in the range +/- 2000mg + """ ... def get_strength() -> int: - """Obtiene la medida de la aceleración de todos los ejes combinados, como un entero positivo. Es la suma Pitagórica de los ejes X, Y y Z. (obtener fuerza) + """Get the acceleration measurement of all axes combined, as a positive integer. This is the Pythagorean sum of the X, Y and Z axes. -Example: ``accelerometer.get_strength()`` + Example: ``accelerometer.get_strength()`` -:return: The combined acceleration strength of all the axes, in milli-g.""" + :return: The combined acceleration strength of all the axes, in milli-g. + """ ... def current_gesture() -> str: - """Obtiene el nombre del gesto actual. (gesto actual) + """Get the name of the current gesture. -Example: ``accelerometer.current_gesture()`` + Example: ``accelerometer.current_gesture()`` -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. + 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. -:return: The current gesture""" + :return: The current gesture + """ ... def is_gesture(name: str) -> bool: - """Comprueba si el gesto está actualmente activo. (gesto activo) + """Check if the named gesture is currently active. -Example: ``accelerometer.is_gesture('shake')`` + Example: ``accelerometer.is_gesture('shake')`` -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. + 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. -:param name: (nombre) El nombre del gesto. -:return: ``True`` if the gesture is active, ``False`` otherwise.""" + :param name: The gesture name. + :return: ``True`` if the gesture is active, ``False`` otherwise. + """ ... def was_gesture(name: str) -> bool: - """Comprueba si el gesto estuvo activo desde la última llamada. (gesto anterior) + """Check if the named gesture was active since the last call. -Example: ``accelerometer.was_gesture('shake')`` + Example: ``accelerometer.was_gesture('shake')`` -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. + 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. -:param name: (nombre) El nombre del gesto. -:return: ``True`` if the gesture was active since the last call, ``False`` otherwise.""" + :param name: The gesture name. + :return: ``True`` if the gesture was active since the last call, ``False`` otherwise. + """ def get_gestures() -> Tuple[str, ...]: - """Devuelve una tupla con el historial de gestos. (obtener gestos) + """Return a tuple of the gesture history. -Example: ``accelerometer.get_gestures()`` + Example: ``accelerometer.get_gestures()`` -Clears the gesture history before returning. + Clears the gesture history before returning. -Gestures are not updated in the background so there needs to be constant -calls to some accelerometer method to do the gesture detection. Usually -gestures can be detected using a loop with a small :func:`microbit.sleep` delay. + Gestures are not updated in the background so there needs to be constant + calls to some accelerometer method to do the gesture detection. Usually + gestures can be detected using a loop with a small :func:`microbit.sleep` delay. -:return: The history as a tuple, most recent last.""" + :return: The history as a tuple, most recent last. + """ ... def set_range(value: int) -> None: - """Configura el rango de sensibilidad del acelerómetro, en g (gravedad estándar), a los valores más cercanos soportados por el hardware, por lo que redondea a ``2``, ``4``, u ``8`` g. (configurar rango) + """Set the accelerometer sensitivity range, in g (standard gravity), to the closest values supported by the hardware, so it rounds to either ``2``, ``4``, or ``8`` g. -Example: ``accelerometer.set_range(8)`` + Example: ``accelerometer.set_range(8)`` -:param value: (valor) Nuevo rango para el acelerómetro, un entero en ``g``.""" \ No newline at end of file + :param value: New range for the accelerometer, an integer in ``g``. + """ diff --git a/lang/es-es/typeshed/stdlib/microbit/audio.pyi b/lang/es-es/typeshed/stdlib/microbit/audio.pyi index 90bc14f..3b1e327 100644 --- a/lang/es-es/typeshed/stdlib/microbit/audio.pyi +++ b/lang/es-es/typeshed/stdlib/microbit/audio.pyi @@ -1,124 +1,160 @@ -"""Reproducir sonidos usando el micro:bit (importar ``audio`` para compatibilidad con V1).""" +"""Play sounds using the micro:bit (import ``audio`` for V1 compatibility). +""" + from ..microbit import MicroBitDigitalPin, Sound, pin0 from typing import ClassVar, Iterable, Union -def play(source: Union[Iterable[AudioFrame], Sound, SoundEffect], wait: bool=True, pin: MicroBitDigitalPin=pin0, return_pin: Union[MicroBitDigitalPin, None]=None) -> None: - """Reproduce un sonido integrado, un efecto de sonido o marcos de audio personalizados. (reproducir) +def play( + source: Union[Iterable[AudioFrame], Sound, SoundEffect], + wait: bool = True, + pin: MicroBitDigitalPin = pin0, + return_pin: Union[MicroBitDigitalPin, None] = None, +) -> None: + """Play a built-in sound, sound effect or custom audio frames. -Example: ``audio.play(Sound.GIGGLE)`` + Example: ``audio.play(Sound.GIGGLE)`` -:param source: (origen) Un ``Sound`` integrado como ``Sound.GIGGLE``, un ``SoundEffect`` o datos de muestra como un iterable de objetos ``AudioFrame``. -:param wait: (esperar) Si ``wait`` es ``True`` (verdadero), la función se bloqueará hasta que el sonido finalice. -:param pin: Se puede usar un argumento opcional para especificar el pin de salida, reemplazando el valor predeterminado de ``pin0``. Si no queremos que se reproduzca ningún sonido, podemos usar ``pin=None``. -:param return_pin: (devolver pin) Especifica un pin de conector de borde diferencial para conectarse a un altavoz externo en lugar de tierra. Esto se ignora para la revisión **V2**.""" + :param source: A built-in ``Sound`` such as ``Sound.GIGGLE``, a ``SoundEffect`` or sample data as an iterable of ``AudioFrame`` objects. + :param wait: If ``wait`` is ``True``, this function will block until the sound is complete. + :param pin: An optional argument to specify the output pin can be used to override the default of ``pin0``. If we do not want any sound to play we can use ``pin=None``. + :param return_pin: Specifies a differential edge connector pin to connect to an external speaker instead of ground. This is ignored for the **V2** revision. + """ def is_playing() -> bool: - """Comprueba si se está reproduciendo un sonido. (reproduciendo) + """Check whether a sound is playing. -Example: ``audio.is_playing()`` + Example: ``audio.is_playing()`` -:return: ``True`` if audio is playing, otherwise ``False``.""" + :return: ``True`` if audio is playing, otherwise ``False``.""" ... def stop() -> None: - """Detiene la reproducción de audio. (detener) + """Stop all audio playback. -Example: ``audio.stop()``""" + Example: ``audio.stop()`` + """ ... class SoundEffect: - """Un efecto de sonido, compuesto por un conjunto de parámetros configurados a través del constructor o atributos. (efectosonido)""" + """A sound effect, composed by a set of parameters configured via the constructor or attributes.""" + WAVEFORM_SINE: ClassVar[int] - """Opción de onda senoidal utilizada para el parámetro ``waveform``. (forma de onda senoidal)""" + """Sine wave option used for the ``waveform`` parameter.""" + WAVEFORM_SAWTOOTH: ClassVar[int] - """Opción de onda con diente de sierra usada para el parámetro ``waveform``. (forma de onda diente de sierra)""" + """Sawtooth wave option used for the ``waveform`` parameter.""" + WAVEFORM_TRIANGLE: ClassVar[int] - """Opción de onda triangular usada para el parámetro ``waveform``. (forma de onda triangular)""" + """Triangle wave option used for the ``waveform`` parameter.""" + WAVEFORM_SQUARE: ClassVar[int] - """Opción de onda cuadrada usada para el parámetro ``waveform``. (forma de onda cuadrada)""" + """Square wave option used for the ``waveform`` parameter.""" + WAVEFORM_NOISE: ClassVar[int] - """Opción de ruido usada para el parámetro ``waveform``. (forma de onda de ruido)""" + """Noise option used for the ``waveform`` parameter.""" + SHAPE_LINEAR: ClassVar[int] - """Opción de interpolación lineal usada para el parámetro ``shape``. (forma lineal)""" + """Linear interpolation option used for the ``shape`` parameter.""" + SHAPE_CURVE: ClassVar[int] - """Opción de interpolación de curva usada para el parámetro ``shape``. (forma curva)""" + """Curve interpolation option used for the ``shape`` parameter.""" + SHAPE_LOG: ClassVar[int] - """Opción de interpolación logarítmica usada para el parámetro ``shape``. (registro de forma)""" + """Logarithmic interpolation option used for the ``shape`` parameter.""" + FX_NONE: ClassVar[int] - """Ninguna opción de efecto usada para el parámetro ``fx``. (fx ninguno)""" + """No effect option used for the ``fx`` parameter.""" + FX_TREMOLO: ClassVar[int] - """Opción de efecto Trémolo usada para el parámetro ``fx``. (fx trémolo)""" + """Tremolo effect option used for the ``fx`` parameter.""" + FX_VIBRATO: ClassVar[int] - """Opción de efecto vibrato utilizada para el parámetro ``fx``.""" + """Vibrato effect option used for the ``fx`` parameter.""" + FX_WARBLE: ClassVar[int] - """Opción de efecto gorjeo utilizada para el parámetro ``fx``. (fx gorjeo)""" + """Warble effect option used for the ``fx`` parameter.""" + freq_start: int - """Frecuencia de inicio en Hertz (Hz), un número entre ``0`` y ``9999`` (frecuencia de inicio)""" + """Start frequency in Hertz (Hz), a number between ``0`` and ``9999``""" + freq_end: int - """Frecuencia final en Hertz (Hz), un número entre ``0`` y ``9999`` (frecuencia final)""" + """End frequency in Hertz (Hz), a number between ``0`` and ``9999``""" + duration: int - """Duración del sonido en milisegundos, un número entre ``0`` y ``9999`` (duración)""" - vol_start: int - """Valor de volumen inicial, un número entre ``0`` y ``255`` (volumen de inicio)""" - vol_end: int - """Valor final del volumen, un número entre ``0`` y ``255`` (volumen final)""" - waveform: int - """Tipo de forma ondulada, uno de estos valores: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (ruido generado aleatoriamente) (forma de onda)""" - fx: int - """Efecto para añadir en el sonido, uno de los siguientes valores: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``o ``FX_NONE``""" - shape: int - """El tipo de curva de interpolación entre las frecuencias de inicio y final, diferentes formas de onda tienen diferentes tasas de cambio en la frecuencia. Uno de los siguientes valores: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG`` (forma)""" + """Duration of the sound in milliseconds, a number between ``0`` and ``9999``""" - def __init__(self, freq_start: int=500, freq_end: int=2500, duration: int=500, vol_start: int=255, vol_end: int=0, waveform: int=WAVEFORM_SQUARE, fx: int=FX_NONE, shape: int=SHAPE_LOG): - """Crea un nuevo efecto de sonido. + vol_start: int + """Start volume value, a number between ``0`` and ``255``""" -Example: ``my_effect = SoundEffect(duration=1000)`` + vol_end: int + """End volume value, a number between ``0`` and ``255``""" -All the parameters are optional, with default values as shown above, and -they can all be modified via attributes of the same name. For example, we -can first create an effect ``my_effect = SoundEffect(duration=1000)``, -and then change its attributes ``my_effect.duration = 500``. + waveform: int + """Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise)""" -:param freq_start: (frecuencia de inicio) Frecuencia de inicio en Hertz (Hz), un número entre ``0`` y ``9999``. -:param freq_end: (frecuencia final) Frecuencia final en Hertz (Hz), un número entre ``0`` y ``9999``. -:param duration: (duración) Duración del sonido en milisegundos, un número entre ``0`` y ``9999``. -:param vol_start: (volumen inicial) Valor de volumen inicial, un número entre ``0`` y ``255``. -:param vol_end: (volumen final) Valor de volumen final, un número entre ``0`` y ``255``. -:param waveform: (forma de onda) Tipo de forma de onda, uno de estos valores: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (ruido generado aleatoriamente). -:param fx: Efecto para añadir en el sonido, uno de los siguientes valores: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``o ``FX_NONE``. -:param shape: (forma) El tipo de curva de interpolación entre las frecuencias de inicio y final, diferentes formas de onda tienen diferentes tasas de cambio en la frecuencia. Uno de los siguientes valores: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``.""" + fx: int + """Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``""" + shape: int + """The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``""" + + def __init__( + self, + freq_start: int = 500, + freq_end: int = 2500, + duration: int = 500, + vol_start: int = 255, + vol_end: int = 0, + waveform: int = WAVEFORM_SQUARE, + fx: int = FX_NONE, + shape: int = SHAPE_LOG, + ): + """Create a new sound effect. + + Example: ``my_effect = SoundEffect(duration=1000)`` + + All the parameters are optional, with default values as shown above, and + they can all be modified via attributes of the same name. For example, we + can first create an effect ``my_effect = SoundEffect(duration=1000)``, + and then change its attributes ``my_effect.duration = 500``. + + :param freq_start: Start frequency in Hertz (Hz), a number between ``0`` and ``9999``. + :param freq_end: End frequency in Hertz (Hz), a number between ``0`` and ``9999``. + :param duration: Duration of the sound in milliseconds, a number between ``0`` and ``9999``. + :param vol_start: Start volume value, a number between ``0`` and ``255``. + :param vol_end: End volume value, a number between ``0`` and ``255``. + :param waveform: Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise). + :param fx: Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``. + :param shape: The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``. + """ def copy(self) -> SoundEffect: - """Crea una copia de este ``SoundEffect``. (copiar) + """Create a copy of this ``SoundEffect``. -Example: ``sound_2 = sound_1.copy()`` + Example: ``sound_2 = sound_1.copy()`` -:return: A copy of the SoundEffect.""" + :return: A copy of the SoundEffect. + """ class AudioFrame: - """Un objeto ``AudioFrame`` es una lista de 32 muestras, cada una de las cuales es un byte -sin signo (número entero entre 0 y 255). + """An ``AudioFrame`` object is a list of 32 samples each of which is a unsigned byte + (whole number between 0 and 255). -It takes just over 4 ms to play a single frame. + It takes just over 4 ms to play a single frame. -Example:: + Example:: - frame = AudioFrame() - for i in range(len(frame)): - frame[i] = 252 - i * 8""" + frame = AudioFrame() + for i in range(len(frame)): + frame[i] = 252 - i * 8 + """ def copyfrom(self, other: AudioFrame) -> None: - """Sobrescribe los datos de este ``AudioFrame`` con los datos de otra instancia ``AudioFrame``. (copiadesde) - -Example: ``my_frame.copyfrom(source_frame)`` - -:param other: (otro) Instancia ``AudioFrame`` desde la que copiar los datos.""" - - def __len__(self) -> int: - ... + """Overwrite the data in this ``AudioFrame`` with the data from another ``AudioFrame`` instance. - def __setitem__(self, key: int, value: int) -> None: - ... + Example: ``my_frame.copyfrom(source_frame)`` - def __getitem__(self, key: int) -> int: - ... \ No newline at end of file + :param other: ``AudioFrame`` instance from which to copy the data. + """ + def __len__(self) -> int: ... + def __setitem__(self, key: int, value: int) -> None: ... + def __getitem__(self, key: int) -> int: ... diff --git a/lang/es-es/typeshed/stdlib/microbit/compass.pyi b/lang/es-es/typeshed/stdlib/microbit/compass.pyi index d6777af..c74a47b 100644 --- a/lang/es-es/typeshed/stdlib/microbit/compass.pyi +++ b/lang/es-es/typeshed/stdlib/microbit/compass.pyi @@ -1,70 +1,78 @@ -"""Usar la brújula incorporada. (brújula)""" +"""Use the built-in compass. +""" def calibrate() -> None: - """Inicia el proceso de calibración. (calibrar) + """Starts the calibration process. -Example: ``compass.calibrate()`` + Example: ``compass.calibrate()`` -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.""" + 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: - """Comprueba si la brújula está calibrada. (está calibrado) + """Check is the compass is calibrated. -Example: ``compass.is_calibrated()`` + Example: ``compass.is_calibrated()`` -:return: ``True`` if the compass has been successfully calibrated, ``False`` otherwise.""" + :return: ``True`` if the compass has been successfully calibrated, ``False`` otherwise. + """ ... def clear_calibration() -> None: - """Deshace la calibración, haciendo que la brújula esté otra vez sin calibrar. (eliminar calibración) + """Undoes the calibration, making the compass uncalibrated again. -Example: ``compass.clear_calibration()``""" + Example: ``compass.clear_calibration()`` + """ ... def get_x() -> int: - """Obtiene la fuerza del campo magnético en el eje ``x``. (obtener x) + """Get the magnetic field strength on the ``x`` axis. -Example: ``compass.get_x()`` + Example: ``compass.get_x()`` -Call ``calibrate`` first or the results will be inaccurate. + Call ``calibrate`` first or the results will be inaccurate. -:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" + :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. + """ ... def get_y() -> int: - """Obtiene la fuerza del campo magnético en el eje ``y``. (obtener y) + """Get the magnetic field strength on the ``y`` axis. -Example: ``compass.get_y()`` + Example: ``compass.get_y()`` -Call ``calibrate`` first or the results will be inaccurate. + Call ``calibrate`` first or the results will be inaccurate. -:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" + :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. + """ ... def get_z() -> int: - """Obtiene la fuerza del campo magnético en el eje ``z``. (obtener z) + """Get the magnetic field strength on the ``z`` axis. -Example: ``compass.get_z()`` + Example: ``compass.get_z()`` -Call ``calibrate`` first or the results will be inaccurate. + Call ``calibrate`` first or the results will be inaccurate. -:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" + :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. + """ ... def heading() -> int: - """Obtiene el rumbo de la brújula. (rumbo) + """Get the compass heading. -Example: ``compass.heading()`` + Example: ``compass.heading()`` -:return: An integer in the range from 0 to 360, representing the angle in degrees, clockwise, with north as 0.""" + :return: An integer in the range from 0 to 360, representing the angle in degrees, clockwise, with north as 0. + """ ... def get_field_strength() -> int: - """Obtiene la magnitud del campo magnético alrededor del dispositivo. (obtener fuerza del campo) + """Get the magnitude of the magnetic field around the device. -Example: ``compass.get_field_strength()`` + Example: ``compass.get_field_strength()`` -:return: An integer indication of the magnitude of the magnetic field in nano tesla.""" - ... \ No newline at end of file + :return: An integer indication of the magnitude of the magnetic field in nano tesla.""" + ... diff --git a/lang/es-es/typeshed/stdlib/microbit/display.pyi b/lang/es-es/typeshed/stdlib/microbit/display.pyi index 63db48b..aa4013e 100644 --- a/lang/es-es/typeshed/stdlib/microbit/display.pyi +++ b/lang/es-es/typeshed/stdlib/microbit/display.pyi @@ -1,92 +1,115 @@ -"""Mostrar texto, imágenes y animaciones en la pantalla LED de 5 × 5. (pantalla)""" +"""Show text, images and animations on the 5×5 LED display. +""" + from ..microbit import Image from typing import Union, overload, Iterable def get_pixel(x: int, y: int) -> int: - """Obtiene el brillo del LED que hay en la columna ``x`` y fila ``y``. (obtener píxel) + """Get the brightness of the LED at column ``x`` and row ``y``. -Example: ``display.get_pixel(0, 0)`` + Example: ``display.get_pixel(0, 0)`` -:param x: La columna de la pantalla (0..4) -:param y: La fila de la pantalla (0..4) -:return: A number between 0 (off) and 9 (bright)""" + :param x: The display column (0..4) + :param y: The display row (0..4) + :return: A number between 0 (off) and 9 (bright) + """ ... def set_pixel(x: int, y: int, value: int) -> None: - """Establece el brillo del LED que hay en la columna ``x`` y fila ``y``. (configurar píxel) + """Set the brightness of the LED at column ``x`` and row ``y``. -Example: ``display.set_pixel(0, 0, 9)`` + Example: ``display.set_pixel(0, 0, 9)`` -:param x: La columna de la pantalla (0..4) -:param y: La fila de la pantalla (0..4) -:param value: (valor) El brillo entre 0 (apagado) y 9 (brillante)""" + :param x: The display column (0..4) + :param y: The display row (0..4) + :param value: The brightness between 0 (off) and 9 (bright) + """ ... def clear() -> None: - """Ajusta el brillo de todos los LED a 0 (apagado). (borrar) + """Set the brightness of all LEDs to 0 (off). -Example: ``display.clear()``""" + Example: ``display.clear()`` + """ ... -def show(image: Union[str, float, int, Image, Iterable[Image]], delay: int=400, wait: bool=True, loop: bool=False, clear: bool=False) -> None: - """Muestra imágenes, letras o dígitos en la pantalla LED. (mostrar) +def show( + image: Union[str, float, int, Image, Iterable[Image]], + delay: int = 400, + wait: bool = True, + loop: bool = False, + clear: bool = False, +) -> None: + """Shows images, letters or digits on the LED display. -Example: ``display.show(Image.HEART)`` + Example: ``display.show(Image.HEART)`` -When ``image`` is an image or a list of images then each image is displayed in turn. -If ``image`` is a string or number, each letter or digit is displayed in turn. + When ``image`` is an image or a list of images then each image is displayed in turn. + If ``image`` is a string or number, each letter or digit is displayed in turn. -:param image: (imagen) Una cadena, número, imagen o lista de imágenes para mostrar. -:param delay: (retardo) Cada letra, dígito o imagen se muestra con ``delay`` milisegundos de retardo entre ellos. -:param wait: (esperar) Si ``wait`` es ``True`` (verdadero), la función se bloqueará hasta que finalice la animación; de lo contrario, la animación se ejecutará en segundo plano. -:param loop: (bucle) Si ``loop`` es ``True`` (verdadero), la animación se repetirá para siempre. -:param clear: (borrar) Si ``clear`` es ``True`` (verdadero), la pantalla se borrará una vez que la secuencia haya terminado. + :param image: A string, number, image or list of images to show. + :param delay: Each letter, digit or image is shown with ``delay`` milliseconds between them. + :param wait: If ``wait`` is ``True``, this function will block until the animation is finished, otherwise the animation will happen in the background. + :param loop: If ``loop`` is ``True``, the animation will repeat forever. + :param clear: If ``clear`` is ``True``, the display will be cleared after the sequence has finished. -The ``wait``, ``loop`` and ``clear`` arguments must be specified using their keyword.""" + The ``wait``, ``loop`` and ``clear`` arguments must be specified using their keyword. + """ ... -def scroll(text: Union[str, float, int], delay: int=150, wait: bool=True, loop: bool=False, monospace: bool=False) -> None: - """Desplaza un número o texto por la pantalla LED. (desplazar) - -Example: ``display.scroll('micro:bit')`` - -:param text: (texto) La cadena a desplazar. Si ``text`` es un entero o de coma flotante, primero se convertirá a cadena usando ``str()``. -:param delay: (retardo) El parámetro ``delay`` controla la velocidad de desplazamiento del texto. -:param wait: (esperar) Si ``wait`` es ``True`` (verdadero), la función se bloqueará hasta que finalice la animación; de lo contrario, la animación se ejecutará en segundo plano. -:param loop: (bucle) Si ``loop`` es ``True`` (verdadero), la animación se repetirá para siempre. -:param monospace: Si ``monospace`` es ``True`` (verdadero), todos los caracteres ocuparán columnas de 5 píxeles de ancho; de lo contrario, habrá exactamente 1 columna de píxeles vacíos entre cada carácter a medida que se desplazan. - -The ``wait``, ``loop`` and ``monospace`` arguments must be specified -using their keyword.""" +def scroll( + text: Union[str, float, int], + delay: int = 150, + wait: bool = True, + loop: bool = False, + monospace: bool = False, +) -> None: + """Scrolls a number or text on the LED display. + + Example: ``display.scroll('micro:bit')`` + + :param text: The string to scroll. If ``text`` is an integer or float it is first converted to a string using ``str()``. + :param delay: The ``delay`` parameter controls how fast the text is scrolling. + :param wait: If ``wait`` is ``True``, this function will block until the animation is finished, otherwise the animation will happen in the background. + :param loop: If ``loop`` is ``True``, the animation will repeat forever. + :param monospace: 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. + + The ``wait``, ``loop`` and ``monospace`` arguments must be specified + using their keyword. + """ ... def on() -> None: - """Enciende la pantalla LED. (encendido) + """Turn on the LED display. -Example: ``display.on()``""" + Example: ``display.on()`` + """ ... def off() -> None: - """Apaga la pantalla LED (desactivar la pantalla te permite reutilizar los pines GPIO para otros fines). (apagado) + """Turn off the LED display (disabling the display allows you to re-use the GPIO pins for other purposes). -Example: ``display.off()``""" + Example: ``display.off()`` + """ ... def is_on() -> bool: - """Comprueba si la pantalla LED está activada. (está encendido) + """Check whether the LED display is enabled. -Example: ``display.is_on()`` + Example: ``display.is_on()`` -:return: ``True`` if the display is on, otherwise returns ``False``.""" + :return: ``True`` if the display is on, otherwise returns ``False``. + """ ... def read_light_level() -> int: - """Lee el nivel de luz. (leer nivel de luz) + """Read the light level. -Example: ``display.read_light_level()`` + Example: ``display.read_light_level()`` -Uses the display's LEDs in reverse-bias mode to sense the amount of light -falling on the display. + Uses the display's LEDs in reverse-bias mode to sense the amount of light + falling on the display. -:return: An integer between 0 and 255 representing the light level, with larger meaning more light.""" - ... \ No newline at end of file + :return: An integer between 0 and 255 representing the light level, with larger meaning more light. + """ + ... diff --git a/lang/es-es/typeshed/stdlib/microbit/i2c.pyi b/lang/es-es/typeshed/stdlib/microbit/i2c.pyi index d126acb..df26efa 100644 --- a/lang/es-es/typeshed/stdlib/microbit/i2c.pyi +++ b/lang/es-es/typeshed/stdlib/microbit/i2c.pyi @@ -1,49 +1,57 @@ -"""Comunicarse con dispositivos que usan el protocolo de bus I²C.""" +"""Communicate with devices using the I²C bus protocol. +""" + from _typeshed import ReadableBuffer from ..microbit import MicroBitDigitalPin, pin19, pin20 from typing import List -def init(freq: int=100000, sda: MicroBitDigitalPin=pin20, scl: MicroBitDigitalPin=pin19) -> None: - """Reinicia un periférico. (inic) +def init( + freq: int = 100000, sda: MicroBitDigitalPin = pin20, scl: MicroBitDigitalPin = pin19 +) -> None: + """Re-initialize a peripheral. -Example: ``i2c.init()`` + Example: ``i2c.init()`` -:param freq: (frec) frecuencia del reloj -:param sda: pin ``sda`` (por defecto, 20) -:param scl: pin ``scl`` (por defecto, 19) + :param freq: clock frequency + :param sda: ``sda`` pin (default 20) + :param scl: ``scl`` pin (default 19) -On a micro:bit V1 board, changing the I²C pins from defaults will make -the accelerometer and compass stop working, as they are connected -internally to those pins. This warning does not apply to the **V2** -revision of the micro:bit as this has `separate I²C lines `_ -for the motion sensors and the edge connector.""" + On a micro:bit V1 board, changing the I²C pins from defaults will make + the accelerometer and compass stop working, as they are connected + internally to those pins. This warning does not apply to the **V2** + revision of the micro:bit as this has `separate I²C lines `_ + for the motion sensors and the edge connector. + """ ... def scan() -> List[int]: - """Escanea el bus para buscar dispositivos. (escanear) + """Scan the bus for devices. -Example: ``i2c.scan()`` + Example: ``i2c.scan()`` -:return: A list of 7-bit addresses corresponding to those devices that responded to the scan.""" + :return: A list of 7-bit addresses corresponding to those devices that responded to the scan. + """ ... -def read(addr: int, n: int, repeat: bool=False) -> bytes: - """Lee bytes de un dispositivo. (leer) +def read(addr: int, n: int, repeat: bool = False) -> bytes: + """Read bytes from a device. -Example: ``i2c.read(0x50, 64)`` + Example: ``i2c.read(0x50, 64)`` -:param addr: (dir) La dirección de 7 bits del dispositivo -:param n: El número de bytes a leer -:param repeat: (repetir) Si es ``True`` (verdadero), no se enviará ningún bit de parada -:return: The bytes read""" + :param addr: The 7-bit address of the device + :param n: The number of bytes to read + :param repeat: If ``True``, no stop bit will be sent + :return: The bytes read + """ ... -def write(addr: int, buf: ReadableBuffer, repeat: bool=False) -> None: - """Escribe bytes en un dispositivo. (escribir) +def write(addr: int, buf: ReadableBuffer, repeat: bool = False) -> None: + """Write bytes to a device. -Example: ``i2c.write(0x50, bytes([1, 2, 3]))`` + Example: ``i2c.write(0x50, bytes([1, 2, 3]))`` -:param addr: (dir) La dirección de 7 bits del dispositivo -:param buf: (búf) Un búfer que contiene los bytes a escribir -:param repeat: (repetir) Si es ``True`` (verdadero), no se enviará ningún bit de parada""" - ... \ No newline at end of file + :param addr: The 7-bit address of the device + :param buf: A buffer containing the bytes to write + :param repeat: If ``True``, no stop bit will be sent + """ + ... diff --git a/lang/es-es/typeshed/stdlib/microbit/microphone.pyi b/lang/es-es/typeshed/stdlib/microbit/microphone.pyi index 4033fa3..68e8f3a 100644 --- a/lang/es-es/typeshed/stdlib/microbit/microphone.pyi +++ b/lang/es-es/typeshed/stdlib/microbit/microphone.pyi @@ -1,62 +1,70 @@ -"""Responde al sonido usando el micrófono integrado (solo V2). (micrófono)""" +"""Respond to sound using the built-in microphone (V2 only). +""" + from typing import Optional, Tuple from ..microbit import SoundEvent def current_event() -> Optional[SoundEvent]: - """Obtiene el último evento de sonido grabado (evento actual) + """Get the last recorded sound event -Example: ``microphone.current_event()`` + Example: ``microphone.current_event()`` -:return: The event, ``SoundEvent('loud')`` or ``SoundEvent('quiet')``.""" + :return: The event, ``SoundEvent('loud')`` or ``SoundEvent('quiet')``. + """ ... def was_event(event: SoundEvent) -> bool: - """Comprueba si se ha escuchado un sonido al menos una vez desde la última llamada. (evento anterior) + """Check if a sound was heard at least once since the last call. -Example: ``microphone.was_event(SoundEvent.LOUD)`` + Example: ``microphone.was_event(SoundEvent.LOUD)`` -This call clears the sound history before returning. + This call clears the sound history before returning. -:param event: (evento) El evento a comprobar, como ``SoundEvent.LOUD`` o ``SoundEvent.QUIET`` -:return: ``True`` if sound was heard at least once since the last call, otherwise ``False``.""" + :param event: The event to check for, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET`` + :return: ``True`` if sound was heard at least once since the last call, otherwise ``False``. + """ ... def is_event(event: SoundEvent) -> bool: - """Comprueba el evento de sonido más reciente detectado. (evento reciente) + """Check the most recent sound event detected. -Example: ``microphone.is_event(SoundEvent.LOUD)`` + Example: ``microphone.is_event(SoundEvent.LOUD)`` -This call does not clear the sound event history. + This call does not clear the sound event history. -:param event: (evento) El evento a comprobar, como ``SoundEvent.LOUD`` o ``SoundEvent.QUIET`` -:return: ``True`` if sound was the most recent heard, ``False`` otherwise.""" + :param event: The event to check for, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET`` + :return: ``True`` if sound was the most recent heard, ``False`` otherwise. + """ ... def get_events() -> Tuple[SoundEvent, ...]: - """Obtiene el historial de eventos de sonido como una tupla. (obtener eventos) + """Get the sound event history as a tuple. -Example: ``microphone.get_events()`` + Example: ``microphone.get_events()`` -This call clears the sound history before returning. + This call clears the sound history before returning. -:return: A tuple of the event history with the most recent event last.""" + :return: A tuple of the event history with the most recent event last. + """ ... def set_threshold(event: SoundEvent, value: int) -> None: - """Establece el umbral para un evento de sonido. (configurar límite) + """Set the threshold for a sound event. -Example: ``microphone.set_threshold(SoundEvent.LOUD, 250)`` + Example: ``microphone.set_threshold(SoundEvent.LOUD, 250)`` -A high threshold means the event will only trigger if the sound is very loud (>= 250 in the example). + A high threshold means the event will only trigger if the sound is very loud (>= 250 in the example). -:param event: (evento) Un evento de sonido, como ``SoundEvent.LOUD`` o ``SoundEvent.QUIET``. -:param value: (valor) El nivel de umbral en el rango 0 - 255.""" + :param event: A sound event, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET``. + :param value: The threshold level in the range 0-255. + """ ... def sound_level() -> int: - """Obtiene el nivel de presión sonora. (nivel de sonido) + """Get the sound pressure level. -Example: ``microphone.sound_level()`` + Example: ``microphone.sound_level()`` -:return: A representation of the sound pressure level in the range 0 to 255.""" - ... \ No newline at end of file + :return: A representation of the sound pressure level in the range 0 to 255. + """ + ... diff --git a/lang/es-es/typeshed/stdlib/microbit/speaker.pyi b/lang/es-es/typeshed/stdlib/microbit/speaker.pyi index 0a63d09..5a74a4d 100644 --- a/lang/es-es/typeshed/stdlib/microbit/speaker.pyi +++ b/lang/es-es/typeshed/stdlib/microbit/speaker.pyi @@ -1,15 +1,18 @@ -"""Controlar el altavoz integrado (solo V2). (altavoz)""" +"""Control the built-in speaker (V2 only). +""" def off() -> None: - """Apaga el altavoz. (apagado) + """Turn the speaker off. -Example: ``speaker.off()`` + Example: ``speaker.off()`` -This does not disable sound output to an edge connector pin.""" + This does not disable sound output to an edge connector pin. + """ ... def on() -> None: - """Enciende el altavoz. (encendido) + """Turn the speaker on. -Example: ``speaker.on()``""" - ... \ No newline at end of file + Example: ``speaker.on()`` + """ + ... diff --git a/lang/es-es/typeshed/stdlib/microbit/spi.pyi b/lang/es-es/typeshed/stdlib/microbit/spi.pyi index 2c9582d..09c4046 100644 --- a/lang/es-es/typeshed/stdlib/microbit/spi.pyi +++ b/lang/es-es/typeshed/stdlib/microbit/spi.pyi @@ -1,47 +1,60 @@ -"""Comunicarse con dispositivos que usan el bus de interfaz de periféricos serie (SPI, por sus siglas en inglés).""" +"""Communicate with devices using the serial peripheral interface (SPI) bus. +""" + from _typeshed import ReadableBuffer, WriteableBuffer from ..microbit import pin13, pin14, pin15, MicroBitDigitalPin -def init(baudrate: int=1000000, bits: int=8, mode: int=0, sclk: MicroBitDigitalPin=pin13, mosi: MicroBitDigitalPin=pin15, miso: MicroBitDigitalPin=pin14) -> None: - """Inicializa la comunicación SPI. - -Example: ``spi.init()`` - -For correct communication, the parameters have to be the same on both communicating devices. - -:param baudrate: (tasa de baudios) La velocidad de comunicación. -:param bits: El ancho en bits de cada transferencia. Actualmente solo se admite ``bits=8}, pero esto puede cambiar en el futuro. -:param mode: (modo) Determina la combinación de fase y polaridad del reloj - `ver tabla en línea `_. -:param sclk: pin SCLK (por defecto, 13) -:param mosi: pin MOSI (por defecto, 15) -:param miso: pin MISO (por defecto, 14)""" +def init( + baudrate: int = 1000000, + bits: int = 8, + mode: int = 0, + sclk: MicroBitDigitalPin = pin13, + mosi: MicroBitDigitalPin = pin15, + miso: MicroBitDigitalPin = pin14, +) -> None: + """Initialize SPI communication. + + Example: ``spi.init()`` + + For correct communication, the parameters have to be the same on both communicating devices. + + :param baudrate: The speed of communication. + :param bits: The width in bits of each transfer. Currently only ``bits=8`` is supported. However, this may change in the future. + :param mode: Determines the combination of clock polarity and phase - `see online table `_. + :param sclk: sclk pin (default 13) + :param mosi: mosi pin (default 15) + :param miso: miso pin (default 14) + """ ... -def read(nbytes: int, out: int=0) -> bytes: - """Lee bytes. (leer) +def read(nbytes: int, out: int = 0) -> bytes: + """Read at most ``nbytes`` while continuously writing the single byte given by ``out``. -Example: ``spi.read(64)`` + Example: ``spi.read(64)`` -:param nbytes: Número máximo de bytes a leer. -:param out: (a) The byte value to write (default 0). -:return: The bytes read.""" + :param nbytes: Maximum number of bytes to read. + :param out: The byte value to write (default 0). + :return: The bytes read. + """ ... def write(buffer: ReadableBuffer) -> None: - """Escribe bytes en el bus. (escribir) + """Write bytes to the bus. -Example: ``spi.write(bytes([1, 2, 3]))`` + Example: ``spi.write(bytes([1, 2, 3]))`` -:param buffer: (búfer) Un búfer del que leer datos.""" + :param buffer: A buffer to read data from. + """ ... def write_readinto(out: WriteableBuffer, in_: ReadableBuffer) -> None: - """Escribe el búfer ``out`` en el bus y lee cualquier respuesta en el búfer ``in_``. (escritura leeren) + """Write the ``out`` buffer to the bus and read any response into the ``in_`` buffer. -Example: ``spi.write_readinto(out_buffer, in_buffer)`` + Example: ``spi.write_readinto(out_buffer, in_buffer)`` -The length of the buffers should be the same. The buffers can be the same object. + The length of the buffers should be the same. The buffers can be the same object. -:param out: (a) El búfer en el que escribe una respuesta. -:param in_: (de) El búfer del que leer datos.""" - ... \ No newline at end of file + :param out: The buffer to write any response to. + :param in_: The buffer to read data from. + """ + ... diff --git a/lang/es-es/typeshed/stdlib/microbit/uart.pyi b/lang/es-es/typeshed/stdlib/microbit/uart.pyi index fc9bd04..2ab650f 100644 --- a/lang/es-es/typeshed/stdlib/microbit/uart.pyi +++ b/lang/es-es/typeshed/stdlib/microbit/uart.pyi @@ -1,79 +1,96 @@ -"""Comunicarse con un dispositivo usando una interfaz serie.""" +"""Communicate with a device using a serial interface. +""" + from _typeshed import WriteableBuffer from ..microbit import MicroBitDigitalPin from typing import Optional, Union -ODD: int -"""Paridad impar (impar)""" -EVEN: int -"""Paridad par (par)""" - -def init(baudrate: int=9600, bits: int=8, parity: Optional[int]=None, stop: int=1, tx: Optional[MicroBitDigitalPin]=None, rx: Optional[MicroBitDigitalPin]=None) -> None: - """Inicializa la comunicación serie. - -Example: ``uart.init(115200, tx=pin0, rx=pin1)`` -:param baudrate: (tasa de baudios) La velocidad de comunicación. -:param bits: El tamaño de bytes transmitidos; micro:bit solo admite 8. -:param parity: (paridad) Cómo se comprueba la paridad: ``None``, ``uart.ODD`` o ``uart.EVEN``. -:param stop: (detener) El número de bits de parada; tiene que ser 1 para el micro:bit. -:param tx: Pin transmisor. -:param rx: Pin receptor. - -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. +ODD: int +"""Odd parity""" -For more details see `the online documentation `_.""" +EVEN: int +"""Even parity""" + +def init( + baudrate: int = 9600, + bits: int = 8, + parity: Optional[int] = None, + stop: int = 1, + tx: Optional[MicroBitDigitalPin] = None, + rx: Optional[MicroBitDigitalPin] = None, +) -> None: + """Initialize serial communication. + + Example: ``uart.init(115200, tx=pin0, rx=pin1)`` + + :param baudrate: The speed of communication. + :param bits: The size of bytes being transmitted. micro:bit only supports 8. + :param parity: How parity is checked, ``None``, ``uart.ODD`` or ``uart.EVEN``. + :param stop: The number of stop bits, has to be 1 for micro:bit. + :param tx: Transmitting pin. + :param rx: Receiving pin. + + 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. + + For more details see `the online documentation `_. + """ ... def any() -> bool: - """Comprueba si hay datos en espera. (algún) + """Check if any data is waiting. -Example: ``uart.any()`` + Example: ``uart.any()`` -:return: ``True`` if any data is waiting, else ``False``.""" + :return: ``True`` if any data is waiting, else ``False``. + """ ... -def read(nbytes: Optional[int]=None) -> Optional[bytes]: - """Lee bytes. (leer) +def read(nbytes: Optional[int] = None) -> Optional[bytes]: + """Read bytes. -Example: ``uart.read()`` + Example: ``uart.read()`` -:param nbytes: Si se especifica ``nbytes``, lee como máximo ese número de bytes; si no, lee tantos bytes como sea posible -:return: A bytes object or ``None`` on timeout""" + :param nbytes: If ``nbytes`` is specified then read at most that many bytes, otherwise read as many bytes as possible + :return: A bytes object or ``None`` on timeout + """ ... -def readinto(buf: WriteableBuffer, nbytes: Optional[int]=None) -> Optional[int]: - """Lee bytes en el ``buf``. (leeren) +def readinto(buf: WriteableBuffer, nbytes: Optional[int] = None) -> Optional[int]: + """Read bytes into the ``buf``. -Example: ``uart.readinto(input_buffer)`` + Example: ``uart.readinto(input_buffer)`` -:param buf: (búf) El búfer en el que escribir. -:param nbytes: Si se especifica ``nbytes``, lee como máximo ese número de bytes; si no, lee ``len(buf)`` bytes. -:return: number of bytes read and stored into ``buf`` or ``None`` on timeout.""" + :param buf: The buffer to write to. + :param nbytes: If ``nbytes`` is specified then read at most that many bytes, otherwise read ``len(buf)`` bytes. + :return: number of bytes read and stored into ``buf`` or ``None`` on timeout. + """ ... def readline() -> Optional[bytes]: - """Lee una línea, terminando en un carácter de nueva línea. (leerlínea) + """Read a line, ending in a newline character. -Example: ``uart.readline()`` + Example: ``uart.readline()`` -:return: The line read or ``None`` on timeout. The newline character is included in the returned bytes.""" + :return: The line read or ``None`` on timeout. The newline character is included in the returned bytes. + """ ... def write(buf: Union[bytes, str]) -> Optional[int]: - """Escribe un búfer en el bus. (escribir) + """Write a buffer to the bus. -Example: ``uart.write('hello world')`` + Example: ``uart.write('hello world')`` -:param buf: (búf) Un objeto de bytes o una cadena. -:return: The number of bytes written, or ``None`` on timeout. + :param buf: A bytes object or a string. + :return: The number of bytes written, or ``None`` on timeout. -Examples:: + Examples:: - uart.write('hello world') - uart.write(b'hello world') - uart.write(bytes([1, 2, 3]))""" - ... \ No newline at end of file + uart.write('hello world') + uart.write(b'hello world') + uart.write(bytes([1, 2, 3])) + """ + ... diff --git a/lang/es-es/typeshed/stdlib/micropython.pyi b/lang/es-es/typeshed/stdlib/micropython.pyi index 21db84c..7a6079f 100644 --- a/lang/es-es/typeshed/stdlib/micropython.pyi +++ b/lang/es-es/typeshed/stdlib/micropython.pyi @@ -1,132 +1,144 @@ -"""Componentes internos de MicroPython.""" +"""MicroPython internals.""" + from typing import Any, TypeVar, overload -_T = TypeVar('_T') + +_T = TypeVar("_T") def const(expr: _T) -> _T: - """Se usa para declarar que la expresión es una constante para que el compilador pueda -optimizarla. + """Used to declare that the expression is a constant so that the compiler can + optimise it. -The use of this function should be as follows:: + The use of this function should be as follows:: - from micropython import const - CONST_X = const(123) - CONST_Y = const(2 * CONST_X + 1) + from micropython import const + CONST_X = const(123) + CONST_Y = const(2 * CONST_X + 1) -Constants declared this way are still accessible as global variables from -outside the module they are declared in. On the other hand, if a constant -begins with an underscore then it is hidden, it is not available as a -global variable, and does not take up any memory during execution. + Constants declared this way are still accessible as global variables from + outside the module they are declared in. On the other hand, if a constant + begins with an underscore then it is hidden, it is not available as a + global variable, and does not take up any memory during execution. -:param expr: Una expresión constante.""" + :param expr: A constant expression. + """ ... @overload def opt_level() -> int: - """Obtiene el nivel actual de optimización para la compilación de scripts. (nivel de opt) + """Get the current optimisation level for the compilation of scripts. -Example: ``micropython.opt_level()`` + Example: ``micropython.opt_level()`` -The optimisation level controls the following compilation features: + The optimisation level controls the following compilation features: -- Assertions: at level 0 assertion statements are enabled and compiled - into the bytecode; at levels 1 and higher assertions are not compiled. + - Assertions: at level 0 assertion statements are enabled and compiled + into the bytecode; at levels 1 and higher assertions are not compiled. -- Built-in ``__debug__`` variable: at level 0 this variable expands to - True; at levels 1 and higher it expands to False. + - Built-in ``__debug__`` variable: at level 0 this variable expands to + True; at levels 1 and higher it expands to False. -- Source-code line numbers: at levels 0, 1 and 2 source-code line number - are stored along with the bytecode so that exceptions can report the - line number they occurred at; at levels 3 and higher line numbers are - not stored. + - Source-code line numbers: at levels 0, 1 and 2 source-code line number + are stored along with the bytecode so that exceptions can report the + line number they occurred at; at levels 3 and higher line numbers are + not stored. -:return: An integer representing the current level.""" + :return: An integer representing the current level. + """ ... @overload def opt_level(level: int) -> None: - """Establece el nivel de optimización para la posterior compilación de scripts. (nivel de opt) + """Sets the optimisation level for subsequent compilation of scripts. -Example: ``micropython.opt_level(1)`` + Example: ``micropython.opt_level(1)`` -The optimisation level controls the following compilation features: + The optimisation level controls the following compilation features: -- Assertions: at level 0 assertion statements are enabled and compiled - into the bytecode; at levels 1 and higher assertions are not compiled. + - Assertions: at level 0 assertion statements are enabled and compiled + into the bytecode; at levels 1 and higher assertions are not compiled. -- Built-in ``__debug__`` variable: at level 0 this variable expands to - True; at levels 1 and higher it expands to False. + - Built-in ``__debug__`` variable: at level 0 this variable expands to + True; at levels 1 and higher it expands to False. -- Source-code line numbers: at levels 0, 1 and 2 source-code line number - are stored along with the bytecode so that exceptions can report the - line number they occurred at; at levels 3 and higher line numbers are - not stored. + - Source-code line numbers: at levels 0, 1 and 2 source-code line number + are stored along with the bytecode so that exceptions can report the + line number they occurred at; at levels 3 and higher line numbers are + not stored. -The default optimisation level is usually level 0. + The default optimisation level is usually level 0. -:param level: (nivel) Un entero que representa el nivel de optimización.""" + :param level: An integer optimisation level. + """ ... -def mem_info(verbose: Any=None) -> None: - """Imprime información sobre la memoria usada en este momento. (info de mem) +def mem_info(verbose: Any = None) -> None: + """Print information about currently used memory. -Example: ``micropython.mem_info()`` + Example: ``micropython.mem_info()`` -:param verbose: Si se pasa el argumento ``verbose``, se imprime información adicional.""" + :param verbose: If the ``verbose`` argument is given then extra information is printed. + """ ... -def qstr_info(verbose: Any=None) -> None: - """Imprime información sobre las cadenas internadas en este momento. (info de cad actual) +def qstr_info(verbose: Any = None) -> None: + """Print information about currently interned strings. -Example: ``micropython.qstr_info()`` + Example: ``micropython.qstr_info()`` -:param verbose: Si se pasa el argumento ``verbose``, se imprime información adicional. + :param verbose: If the ``verbose`` argument is given then extra information is printed. -The information that is printed is implementation dependent, but currently -includes the number of interned strings and the amount of RAM they use. In -verbose mode it prints out the names of all RAM-interned strings.""" + The information that is printed is implementation dependent, but currently + includes the number of interned strings and the amount of RAM they use. In + verbose mode it prints out the names of all RAM-interned strings. + """ ... def stack_use() -> int: - """Devuelve un entero que representa la cantidad de pila que se está usando en este momento. (pila usada) + """Return an integer representing the current amount of stack that is being + used. -Example: ``micropython.stack_use()`` + Example: ``micropython.stack_use()`` -The absolute value of this is not particularly useful, rather it -should be used to compute differences in stack usage at different points. + The absolute value of this is not particularly useful, rather it + should be used to compute differences in stack usage at different points. -:return: An integer representing current stack use.""" + :return: An integer representing current stack use. + """ ... def heap_lock() -> None: - """Bloquea el montón. (bloquear montón) + """Lock the heap. -Example: ``micropython.heap_lock()`` + Example: ``micropython.heap_lock()`` -When locked no memory allocation can occur and a ``MemoryError`` will be -raised if any heap allocation is attempted.""" + When locked no memory allocation can occur and a ``MemoryError`` will be + raised if any heap allocation is attempted. + """ ... def heap_unlock() -> None: - """Desbloquea el montón. (desbloquear el montón) + """Unlock the heap. -Example: ``micropython.heap_unlock()`` + Example: ``micropython.heap_unlock()`` -When locked no memory allocation can occur and a ``MemoryError`` will be -raised if any heap allocation is attempted.""" + When locked no memory allocation can occur and a ``MemoryError`` will be + raised if any heap allocation is attempted. + """ ... def kbd_intr(chr: int) -> None: - """Establece qué carácter lanzará una excepción ``KeyboardInterrupt``. (intr tecl) + """Set the character that will raise a ``KeyboardInterrupt`` exception. -Example: ``micropython.kbd_intr(-1)`` + Example: ``micropython.kbd_intr(-1)`` -:param chr: (car) Código de carácter que lanzará la interrupción o -1 para desactivar la captura de Ctrl + C. + :param chr: Character code to raise the interrupt or -1 to disable capture of Ctrl-C. -By default this is set to 3 during script execution, corresponding to Ctrl-C. -Passing -1 to this function will disable capture of Ctrl-C, and passing 3 -will restore it. + By default this is set to 3 during script execution, corresponding to Ctrl-C. + Passing -1 to this function will disable capture of Ctrl-C, and passing 3 + will restore it. -This function can be used to prevent the capturing of Ctrl-C on the -incoming stream of characters that is usually used for the REPL, in case -that stream is used for other purposes.""" - ... \ No newline at end of file + This function can be used to prevent the capturing of Ctrl-C on the + incoming stream of characters that is usually used for the REPL, in case + that stream is used for other purposes. + """ + ... diff --git a/lang/es-es/typeshed/stdlib/music.pyi b/lang/es-es/typeshed/stdlib/music.pyi index 9483beb..5f4778b 100644 --- a/lang/es-es/typeshed/stdlib/music.pyi +++ b/lang/es-es/typeshed/stdlib/music.pyi @@ -1,128 +1,167 @@ -"""Crear y reproducir melodías. (música)""" +"""Create and play melodies. +""" from typing import Optional, Tuple, Union, List + from .microbit import MicroBitDigitalPin, pin0 + DADADADUM: Tuple[str, ...] -"""Melodía: apertura de la "Sinfonía n.º 5 en do menor" de Beethoven.""" +"""Melody: the opening to Beethoven’s 5th Symphony in C minor.""" + ENTERTAINER: Tuple[str, ...] -"""Melodía: fragmento inicial del clásico Ragtime de Scott Joplin “The Entertainer”.""" +"""Melody: the opening fragment of Scott Joplin’s Ragtime classic “The Entertainer”.""" + PRELUDE: Tuple[str, ...] -"""Melodía: apertura del primer "Preludio en do mayor" de los 48 Preludios y Fugas de J. S. Bach. (preludio)""" +"""Melody: the opening of the first Prelude in C Major of J.S.Bach’s 48 Preludes and Fugues.""" + ODE: Tuple[str, ...] -"""Melodía: tema “Oda a la alegría” de la "Sinfonía n.º 9 en re menor" de Beethoven. (oda)""" +"""Melody: the “Ode to Joy” theme from Beethoven’s 9th Symphony in D minor.""" + NYAN: Tuple[str, ...] -"""Melodía: el tema de Nyan Cat (http://www.nyan.cat/). +"""Melody: the Nyan Cat theme (http://www.nyan.cat/). The composer is unknown. This is fair use for educational porpoises (as they say in New York).""" + RINGTONE: Tuple[str, ...] -"""Melodía: algo que suena como un tono de llamada de un teléfono móvil. (tono de llamada) +"""Melody: something that sounds like a mobile phone ringtone. To be used to indicate an incoming message. """ + FUNK: Tuple[str, ...] -"""Melodía: una línea de bajo funky para agentes secretos y maestros criminales.""" +"""Melody: a funky bass line for secret agents and criminal masterminds.""" + BLUES: Tuple[str, ...] -"""Melodía: "walking bass" con un blues boogie-woogie de 12 compases.""" +"""Melody: a boogie-woogie 12-bar blues walking bass.""" + BIRTHDAY: Tuple[str, ...] -"""Melodía: “Cumpleaños feliz” (cumpleaños) +"""Melody: “Happy Birthday to You…” For copyright status see: http://www.bbc.co.uk/news/world-us-canada-34332853 """ + WEDDING: Tuple[str, ...] -"""Melodía: coro nupcial de la ópera de Wagner "Lohengrin". (boda)""" +"""Melody: the bridal chorus from Wagner’s opera “Lohengrin”.""" + FUNERAL: Tuple[str, ...] -"""Melodía: “Marcha fúnebre”, conocida también como "Sonata para piano n.º 2 en si bemol menor, Op. 35" de Frédéric Chopin.""" +"""Melody: the “funeral march” otherwise known as Frédéric Chopin’s Piano Sonata No. 2 in B♭ minor, Op. 35.""" + PUNCHLINE: Tuple[str, ...] -"""Melodía: un fragmento divertido que representa que se ha hecho un chiste. (remate)""" +"""Melody: a fun fragment that signifies a joke has been made.""" + PYTHON: Tuple[str, ...] -"""Melodía: la marcha de John Philip Sousa “Liberty Bell”, también conocida por ser el tema del “Monty Python Flying Circus” (de donde obtiene su nombre el lenguaje de programación Python).""" +"""Melody: John Philip Sousa’s march “Liberty Bell” aka, the theme for “Monty Python’s Flying Circus” (after which the Python programming language is named).""" + BADDY: Tuple[str, ...] -"""Melodía: entrada de un malote en la época del cine mudo. (malote)""" +"""Melody: silent movie era entrance of a baddy.""" + CHASE: Tuple[str, ...] -"""Melodía: escena de persecución en la época del cine mudo. (persecución)""" +"""Melody: silent movie era chase scene.""" + BA_DING: Tuple[str, ...] -"""Melodía: una señal corta para indicar que algo ha pasado.""" +"""Melody: a short signal to indicate something has happened.""" + WAWAWAWAA: Tuple[str, ...] -"""Melodía: un trombón muy triste.""" +"""Melody: a very sad trombone.""" + JUMP_UP: Tuple[str, ...] -"""Melodía: para usar en un juego, indicando un movimiento ascendente. (saltar arriba)""" +"""Melody: for use in a game, indicating upward movement.""" + JUMP_DOWN: Tuple[str, ...] -"""Melodía: para usar en un juego, indicando un movimiento descendente. (saltar abajo)""" +"""Melody: for use in a game, indicating downward movement.""" + POWER_UP: Tuple[str, ...] -"""Melodía: una fanfarria para indicar un logro desbloqueado. (subida de potencia)""" +"""Melody: a fanfare to indicate an achievement unlocked.""" + POWER_DOWN: Tuple[str, ...] -"""Melodía: una fanfarria triste para indicar un logro perdido. (bajada de potencia)""" +"""Melody: a sad fanfare to indicate an achievement lost.""" -def set_tempo(ticks: int=4, bpm: int=120) -> None: - """Establece el ritmo aproximado de la reproducción. (configurar tempo) +def set_tempo(ticks: int = 4, bpm: int = 120) -> None: + """Sets the approximate tempo for playback. -Example: ``music.set_tempo(bpm=120)`` + Example: ``music.set_tempo(bpm=120)`` -:param ticks: (tics) El número de tics que constituyen un ritmo. -:param bpm: Un entero que determina el número de compases por minuto. + :param ticks: The number of ticks constituting a beat. + :param bpm: An integer determining how many beats per minute. -Suggested default values allow the following useful behaviour: + Suggested default values allow the following useful behaviour: -- music.set_tempo() – reset the tempo to default of ticks = 4, bpm = 120 -- music.set_tempo(ticks=8) – change the “definition” of a beat -- music.set_tempo(bpm=180) – just change the tempo + - music.set_tempo() – reset the tempo to default of ticks = 4, bpm = 120 + - music.set_tempo(ticks=8) – change the “definition” of a beat + - music.set_tempo(bpm=180) – just change the tempo -To work out the length of a tick in milliseconds is very simple arithmetic: -60000/bpm/ticks_per_beat. For the default values that’s -60000/120/4 = 125 milliseconds or 1 beat = 500 milliseconds.""" + To work out the length of a tick in milliseconds is very simple arithmetic: + 60000/bpm/ticks_per_beat. For the default values that’s + 60000/120/4 = 125 milliseconds or 1 beat = 500 milliseconds. + """ ... def get_tempo() -> Tuple[int, int]: - """Obtiene el ritmo actual como una tupla de enteros: ``(ticks, bpm)``. (obtener tempo) + """Gets the current tempo as a tuple of integers: ``(ticks, bpm)``. -Example: ``ticks, beats = music.get_tempo()`` + Example: ``ticks, beats = music.get_tempo()`` -:return: The temp as a tuple with two integer values, the ticks then the beats per minute.""" + :return: The temp as a tuple with two integer values, the ticks then the beats per minute. + """ ... -def play(music: Union[str, List[str], Tuple[str, ...]], pin: Optional[MicroBitDigitalPin]=pin0, wait: bool=True, loop: bool=False) -> None: - """Reproduce música. (reproducir) +def play( + music: Union[str, List[str], Tuple[str, ...]], + pin: Optional[MicroBitDigitalPin] = pin0, + wait: bool = True, + loop: bool = False, +) -> None: + """Plays music. -Example: ``music.play(music.NYAN)`` + Example: ``music.play(music.NYAN)`` -:param music: (música) música especificada en `una notación especial `_ -:param pin: pin de salida para usar con un altavoz externo (por defecto ``pin0``), ``None`` para que no haya sonido. -:param wait: (esperar) Si ``wait`` se configura como ``True`` (verdadero), esta función estará bloqueando. -:param loop: (bucle) Si ``loop`` se configura como ``True`` (verdadero), la melodía se repite hasta que se llama a ``stop`` o se interrumpe la llamada de bloqueo. + :param music: music specified in `a special notation `_ + :param pin: the output pin for use with an external speaker (default ``pin0``), ``None`` for no sound. + :param wait: If ``wait`` is set to ``True``, this function is blocking. + :param loop: If ``loop`` is set to ``True``, the tune repeats until ``stop`` is called or the blocking call is interrupted. -Many built-in melodies are defined in this module.""" + Many built-in melodies are defined in this module. + """ ... -def pitch(frequency: int, duration: int=-1, pin: Optional[MicroBitDigitalPin]=pin0, wait: bool=True) -> None: - """Reproduce una nota. (tono) +def pitch( + frequency: int, + duration: int = -1, + pin: Optional[MicroBitDigitalPin] = pin0, + wait: bool = True, +) -> None: + """Play a note. -Example: ``music.pitch(185, 1000)`` + Example: ``music.pitch(185, 1000)`` -:param frequency: (frecuencia) Una frecuencia entera -:param duration: (duración) La duración en milisegundos. Si es negativa, el sonido continuará hasta la siguiente llamada o una llamada a ``stop``. -:param pin: Pin de salida opcional (por defecto, ``pin0``). -:param wait: (esperar) Si ``wait`` se configura como ``True`` (verdadero), esta función estará bloqueando. + :param frequency: An integer frequency + :param duration: A millisecond duration. If negative then sound is continuous until the next call or a call to ``stop``. + :param pin: Optional output pin (default ``pin0``). + :param wait: If ``wait`` is set to ``True``, this function is blocking. -For example, if the frequency is set to 440 and the length to -1000 then we hear a standard concert A for one second. + For example, if the frequency is set to 440 and the length to + 1000 then we hear a standard concert A for one second. -You can only play one pitch on one pin at any one time.""" + You can only play one pitch on one pin at any one time. + """ ... -def stop(pin: Optional[MicroBitDigitalPin]=pin0) -> None: - """Detiene la reproducción de toda la música en el altavoz integrado y en cualquier pin que esté emitiendo sonido. (detener) +def stop(pin: Optional[MicroBitDigitalPin] = pin0) -> None: + """Stops all music playback on the built-in speaker and any pin outputting sound. -Example: ``music.stop()`` + Example: ``music.stop()`` -:param pin: Se puede proporcionar un argumento opcional para especificar un pin; por ejemplo, ``music.stop(pin1)``.""" + :param pin: An optional argument can be provided to specify a pin, e.g. ``music.stop(pin1)``. + """ def reset() -> None: - """Restablece los valores de "ticks", "bpm", "duration" y "octave" a sus valores por defecto. (restablecer) + """Resets ticks, bpm, duration and octave to their default values. -Example: ``music.reset()`` + Example: ``music.reset()`` -Values: -- ``ticks = 4`` -- ``bpm = 120`` -- ``duration = 4`` -- ``octave = 4``""" - ... \ No newline at end of file + Values: + - ``ticks = 4`` + - ``bpm = 120`` + - ``duration = 4`` + - ``octave = 4`` + """ + ... diff --git a/lang/es-es/typeshed/stdlib/neopixel.pyi b/lang/es-es/typeshed/stdlib/neopixel.pyi index 03d4025..2d5a749 100644 --- a/lang/es-es/typeshed/stdlib/neopixel.pyi +++ b/lang/es-es/typeshed/stdlib/neopixel.pyi @@ -1,81 +1,82 @@ -"""Tiras de LED RGB y RGBW accesibles individualmente.""" +"""Individually addressable RGB and RGBW LED strips. +""" from .microbit import MicroBitDigitalPin from typing import Tuple class NeoPixel: + def __init__(self, pin: MicroBitDigitalPin, n: int, bpp: int = 3) -> None: + """Initialise a new strip of neopixel LEDs controlled via a pin. - def __init__(self, pin: MicroBitDigitalPin, n: int, bpp: int=3) -> None: - """Inicializa una nueva tira de LED NeoPixel controlada a través de un pin. + Example: ``np = neopixel.NeoPixel(pin0, 8)`` -Example: ``np = neopixel.NeoPixel(pin0, 8)`` + To support RGBW neopixels, a third argument can be passed to + ``NeoPixel`` to indicate the number of bytes per pixel (``bpp``). + For RGBW, this is is 4 rather than the default of 3 for RGB and GRB. -To support RGBW neopixels, a third argument can be passed to -``NeoPixel`` to indicate the number of bytes per pixel (``bpp``). -For RGBW, this is is 4 rather than the default of 3 for RGB and GRB. + Each pixel is addressed by a position (starting from 0). Neopixels are + given RGB (red, green, blue) / RGBW (red, green, blue, white) values + between 0-255 as a tuple. For example, in RGB, ``(255,255,255)`` is + white. In RGBW, ``(255,255,255,0)`` or ``(0,0,0,255)`` is white. -Each pixel is addressed by a position (starting from 0). Neopixels are -given RGB (red, green, blue) / RGBW (red, green, blue, white) values -between 0-255 as a tuple. For example, in RGB, ``(255,255,255)`` is -white. In RGBW, ``(255,255,255,0)`` or ``(0,0,0,255)`` is white. + See `the online docs `_ for warnings and other advice. -See `the online docs `_ for warnings and other advice. - -:param pin: El pin que controla la tira NeoPixel. -:param n: El número de LED NeoPixel de la tira. -:param bpp: Bytes por píxel. Para compatibilidad de neopíxeles RGBW, pasa 4 en lugar del valor predeterminado de 3 para RGB y GRB.""" + :param pin: The pin controlling the neopixel strip. + :param n: The number of neopixels in the strip. + :param bpp: Bytes per pixel. For RGBW neopixel support, pass 4 rather than the default of 3 for RGB and GRB. + """ ... - def clear(self) -> None: - """Borrar todos los píxeles. (borrar) + """Clear all the pixels. -Example: ``np.clear()``""" + Example: ``np.clear()`` + """ ... - def show(self) -> None: - """Muestra los píxeles. (mostrar) + """Show the pixels. -Example: ``np.show()`` + Example: ``np.show()`` -Must be called for any updates to become visible.""" + Must be called for any updates to become visible. + """ ... - def write(self) -> None: - """Muestra los píxeles (solo micro:bit V2). (escribir) + """Show the pixels (micro:bit V2 only). -Example: ``np.write()`` + Example: ``np.write()`` -Must be called for any updates to become visible. + Must be called for any updates to become visible. -Equivalent to ``show``.""" + Equivalent to ``show``. + """ ... - def fill(self, colour: Tuple[int, ...]) -> None: - """Colorea todos los píxeles con un valor RGB/RGBW dado (solo micro:bit V2). (llenar) + """Colour all pixels a given RGB/RGBW value (micro:bit V2 only). -Example: ``np.fill((0, 0, 255))`` + Example: ``np.fill((0, 0, 255))`` -:param colour: (color) Una tupla de la misma longitud que el número de bytes por píxel (bpp). + :param colour: A tuple of the same length as the number of bytes per pixel (bpp). -Use in conjunction with ``show()`` to update the neopixels.""" + Use in conjunction with ``show()`` to update the neopixels. + """ ... - def __setitem__(self, key: int, value: Tuple[int, ...]) -> None: - """Establece el color de un píxel. (configurar elemento) + """Set a pixel colour. -Example: ``np[0] = (255, 0, 0)`` - -:param key: (clave) El número de píxel. -:param value: (valor) El color.""" + Example: ``np[0] = (255, 0, 0)`` + :param key: The pixel number. + :param value: The colour. + """ def __getitem__(self, key: int) -> Tuple[int, ...]: - """Obtiene el color de un píxel. (obtener elemento) - -Example: ``r, g, b = np[0]`` + """Get a pixel colour. -:param key: (clave) El número de píxel. -:return: The colour tuple.""" + Example: ``r, g, b = np[0]`` + :param key: The pixel number. + :return: The colour tuple. + """ def __len__(self) -> int: - """Obtiene la longitud de esta tira de píxeles. (lon) + """Get length of this pixel strip. -Example: ``len(np)``""" \ No newline at end of file + Example: ``len(np)`` + """ diff --git a/lang/es-es/typeshed/stdlib/os.pyi b/lang/es-es/typeshed/stdlib/os.pyi index ac41541..2f2db77 100644 --- a/lang/es-es/typeshed/stdlib/os.pyi +++ b/lang/es-es/typeshed/stdlib/os.pyi @@ -1,63 +1,73 @@ -"""Acceder al sistema de archivos. (so)""" +"""Access the file system. +""" + from typing import Tuple from typing import List def listdir() -> List[str]: - """Lista los archivos. + """List files. -Example: ``os.listdir()`` + Example: ``os.listdir()`` -:return: A list of the names of all the files contained within the local -persistent on-device file system.""" + :return: A list of the names of all the files contained within the local + persistent on-device file system. + """ ... def remove(filename: str) -> None: - """Elimina un archivo. (eliminar) + """Remove (delete) a file. -Example: ``os.remove('data.txt')`` + Example: ``os.remove('data.txt')`` -:param filename: (nombre del archivo) El archivo a eliminar. + :param filename: The file to delete. -If the file does not exist an ``OSError`` exception will occur.""" + If the file does not exist an ``OSError`` exception will occur. + """ ... def size(filename: str) -> int: - """Devuelve el tamaño de un archivo. (tamaño) + """Returns the size of a file. -Example: ``os.size('data.txt')`` + Example: ``os.size('data.txt')`` -:param filename: (nombre del archivo) El archivo -:return: The size in bytes. + :param filename: The file + :return: The size in bytes. -If the file does not exist an ``OSError`` exception will occur.""" + If the file does not exist an ``OSError`` exception will occur. + """ class uname_result(Tuple[str, str, str, str, str]): - """Resultado de ``os.uname()`` (resultado de nombreu)""" + """Result of ``os.uname()``""" sysname: str - """Nombre del sistema operativo. (nombre del sistema)""" + """Operating system name.""" + nodename: str - """Nombre de la máquina en la red (definida por la implementación). (nombre del nodo)""" + """Name of machine on network (implementation-defined).""" + release: str - """Versión de lanzamiento del sistema operativo. (lanzamiento)""" + """Operating system release.""" + version: str - """Versión del sistema operativo. (versión)""" + """Operating system version.""" + machine: str - """Identificador de hardware. (máquina)""" + """Hardware identifier.""" def uname() -> uname_result: - """Devuelve información que identifica el sistema operativo actual. (nombreu) + """Returns information identifying the current operating system. -Example: ``os.uname()`` + Example: ``os.uname()`` -The return value is an object with five attributes: + The return value is an object with five attributes: -- ``sysname`` - operating system name -- ``nodename`` - name of machine on network (implementation-defined) -- ``release`` - operating system release -- ``version`` - operating system version -- ``machine`` - hardware identifier + - ``sysname`` - operating system name + - ``nodename`` - name of machine on network (implementation-defined) + - ``release`` - operating system release + - ``version`` - operating system version + - ``machine`` - hardware identifier -There is no underlying operating system in MicroPython. As a result the -information returned by the ``uname`` function is mostly useful for -versioning details.""" - ... \ No newline at end of file + There is no underlying operating system in MicroPython. As a result the + information returned by the ``uname`` function is mostly useful for + versioning details. + """ + ... diff --git a/lang/es-es/typeshed/stdlib/radio.pyi b/lang/es-es/typeshed/stdlib/radio.pyi index dfb8031..8dd0267 100644 --- a/lang/es-es/typeshed/stdlib/radio.pyi +++ b/lang/es-es/typeshed/stdlib/radio.pyi @@ -1,130 +1,152 @@ -"""Comunicarse entre micro:bits con la radio incorporada.""" +"""Communicate between micro:bits with the built-in radio. +""" + from _typeshed import WriteableBuffer from typing import Optional, Tuple + RATE_1MBIT: int -"""Constante utilizada para indicar un rendimiento de 1 Mb por segundo. (tasa de 1 mbit)""" +"""Constant used to indicate a throughput of 1 MBit a second.""" + RATE_2MBIT: int -"""Constante utilizada para indicar un rendimiento de 2 Mb por segundo. (tasa de 2 mbit)""" +"""Constant used to indicate a throughput of 2 MBit a second.""" def on() -> None: - """Enciende la radio. (encender) + """Turns the radio on. -Example: ``radio.on()`` + Example: ``radio.on()`` -This needs to be explicitly called since the radio draws power and takes -up memory that you may otherwise need.""" + This needs to be explicitly called since the radio draws power and takes + up memory that you may otherwise need. + """ ... def off() -> None: - """Apaga la radio, ahorrando energía y memoria. (apagado) + """Turns off the radio, saving power and memory. -Example: ``radio.off()``""" + Example: ``radio.off()`` + """ ... -def config(length: int=32, queue: int=3, channel: int=7, power: int=6, address: int=1969383796, group: int=0, data_rate: int=RATE_1MBIT) -> None: - """Configura la radio. - -Example: ``radio.config(group=42)`` - -The default configuration is suitable for most use. - -:param length: (longitud) (valor predeterminado = 32) define la longitud máxima, en bytes, de un mensaje enviado a través de la radio. -Puede tener hasta 251 bytes de largo (254 - 3 bytes para preámbulos S0, LENGTH y S1). -:param queue: (cola) (valor predeterminado = 3) especifica el número de mensajes que pueden almacenarse en la cola de mensajes entrantes. -Si no quedan espacios en la cola para los mensajes entrantes, el mensaje entrante será eliminado. -:param channel: (canal) (valor predeterminado = 7) un valor entero de 0 a 83 (inclusive) que define un "canal" arbitrario en el cual la radio está sintonizada. -Los mensajes se enviarán a través de este canal y solo los mensajes recibidos a través de este canal se pondrán en la cola de mensajes entrantes. Cada paso es de 1 MHz de ancho, basado en 2400 MHz. -:param power: (potencia) (valor predeterminado = 6) es un valor entero de 0 a 7 (inclusive) para indicar la fuerza de la señal usada al transmitir un mensaje. -Cuanto más alto sea el valor, más fuerte es la señal, pero más energía consume el dispositivo. La numeración se traduce a posiciones en la siguiente lista de valores de dBm (decibelio-milivatio): -30, -20, -16, -12, -8, -4, 0, 4. -:param address: (dirección) (valor predeterminado = 0x75626974) un nombre arbitrario, expresado como una dirección de 32 bits, que se usa para filtrar los paquetes entrantes a nivel de hardware, manteniendo solo aquellos que coincidan con la dirección que has establecido. -El valor predeterminado utilizado por otras plataformas relacionadas con el micro:bit es la configuración predeterminada utilizada aquí. -:param group: (grupo) (valor predeterminado = 0) un valor de 8 bits (0 - 255) usado con el valor de ``address`` al filtrar mensajes. -Conceptualmente, "address" (dirección) es como una dirección de casa u oficina y "group" (grupo) es la persona que está en esa dirección y a la que quieres enviar un mensaje. -:param data_rate: (tasa de datos) (valor predeterminado = ``radio.RATE_1MBIT``) indica la velocidad a la que se lleva a cabo el procesamiento de datos. -Puede ser una de las siguientes constantes definidas en el módulo ``radio``: ``RATE_250KBIT``, ``RATE_1MBIT`` o ``RATE_2MBIT``. - -If ``config`` is not called then the defaults described above are assumed.""" +def config( + length: int = 32, + queue: int = 3, + channel: int = 7, + power: int = 6, + address: int = 0x75626974, + group: int = 0, + data_rate: int = RATE_1MBIT, +) -> None: + """Configures the radio. + + Example: ``radio.config(group=42)`` + + The default configuration is suitable for most use. + + :param length: (default=32) defines the maximum length, in bytes, of a message sent via the radio. + It can be up to 251 bytes long (254 - 3 bytes for S0, LENGTH and S1 preamble). + :param queue: (default=3) specifies the number of messages that can be stored on the incoming message queue. + If there are no spaces left on the queue for incoming messages, then the incoming message is dropped. + :param channel: (default=7) an integer value from 0 to 83 (inclusive) that defines an arbitrary "channel" to which the radio is tuned. + Messages will be sent via this channel and only messages received via this channel will be put onto the incoming message queue. Each step is 1MHz wide, based at 2400MHz. + :param power: (default=6) is an integer value from 0 to 7 (inclusive) to indicate the strength of signal used when broadcasting a message. + The higher the value the stronger the signal, but the more power is consumed by the device. The numbering translates to positions in the following list of dBm (decibel milliwatt) values: -30, -20, -16, -12, -8, -4, 0, 4. + :param address: (default=0x75626974) an arbitrary name, expressed as a 32-bit address, that's used to filter incoming packets at the hardware level, keeping only those that match the address you set. + The default used by other micro:bit related platforms is the default setting used here. + :param group: (default=0) an 8-bit value (0-255) used with the ``address`` when filtering messages. + Conceptually, "address" is like a house/office address and "group" is like the person at that address to which you want to send your message. + :param data_rate: (default=``radio.RATE_1MBIT``) indicates the speed at which data throughput takes place. + Can be one of the following constants defined in the ``radio`` module: ``RATE_250KBIT``, ``RATE_1MBIT`` or ``RATE_2MBIT``. + + If ``config`` is not called then the defaults described above are assumed. + """ ... def reset() -> None: - """Restablece la configuración a sus valores predeterminados. (restablecer) + """Reset the settings to their default values. -Example: ``radio.reset()`` + Example: ``radio.reset()`` -The defaults as as per the ``config`` function above.""" + The defaults as as per the ``config`` function above. + """ ... def send_bytes(message: bytes) -> None: - """Envía un mensaje que contiene bytes. (enviar bytes) + """Sends a message containing bytes. -Example: ``radio.send_bytes(b'hello')`` + Example: ``radio.send_bytes(b'hello')`` -:param message: (mensaje) Los bytes a enviar.""" + :param message: The bytes to send. + """ ... def receive_bytes() -> Optional[bytes]: - """Recibe el siguiente mensaje entrante en la cola de mensajes. (recibir bytes) + """Receive the next incoming message on the message queue. -Example: ``radio.receive_bytes()`` + Example: ``radio.receive_bytes()`` -:return: The message bytes if any, otherwise ``None``.""" + :return: The message bytes if any, otherwise ``None``. + """ ... def receive_bytes_into(buffer: WriteableBuffer) -> Optional[int]: - """Copia el siguiente mensaje entrante de la cola de mensajes en un búfer. (recibir bytes en) + """Copy the next incoming message on the message queue into a buffer. -Example: ``radio.receive_bytes_info(buffer)`` + Example: ``radio.receive_bytes_info(buffer)`` -:param buffer: (búfer) El búfer de destino. El mensaje se trunca si es más grande que el búfer. -:return: ``None`` if there are no pending messages, otherwise it returns the length of the message (which might be more than the length of the buffer).""" + :param buffer: The target buffer. The message is truncated if larger than the buffer. + :return: ``None`` if there are no pending messages, otherwise it returns the length of the message (which might be more than the length of the buffer). + """ ... def send(message: str) -> None: - """Envía una cadena de mensaje. (enviar) + """Sends a message string. -Example: ``radio.send('hello')`` + Example: ``radio.send('hello')`` -This is the equivalent of ``radio.send_bytes(bytes(message, 'utf8'))`` but with ``b'\x01\x00\x01'`` -prepended to the front (to make it compatible with other platforms that target the micro:bit). + This is the equivalent of ``radio.send_bytes(bytes(message, 'utf8'))`` but with ``b'\x01\x00\x01'`` + prepended to the front (to make it compatible with other platforms that target the micro:bit). -:param message: (mensaje) La cadena a enviar.""" + :param message: The string to send. + """ ... def receive() -> Optional[str]: - """Funciona exactamente del mismo modo que ``receive_bytes``, pero devuelve lo que se envió. (recibir) + """Works in exactly the same way as ``receive_bytes`` but returns whatever was sent. -Example: ``radio.receive()`` + Example: ``radio.receive()`` -Equivalent to ``str(receive_bytes(), 'utf8')`` but with a check that the the first -three bytes are ``b'\x01\x00\x01'`` (to make it compatible with other platforms that -may target the micro:bit). + Equivalent to ``str(receive_bytes(), 'utf8')`` but with a check that the the first + three bytes are ``b'\x01\x00\x01'`` (to make it compatible with other platforms that + may target the micro:bit). -:return: The message with the prepended bytes stripped and converted to a string. + :return: The message with the prepended bytes stripped and converted to a string. -A ``ValueError`` exception is raised if conversion to string fails.""" + A ``ValueError`` exception is raised if conversion to string fails. + """ ... def receive_full() -> Optional[Tuple[bytes, int, int]]: - """Devuelve una tupla de tres valores que representan el siguiente mensaje entrante de la cola de mensajes. (recibir completo) + """Returns a tuple containing three values representing the next incoming message on the message queue. -Example: ``radio.receive_full()`` + Example: ``radio.receive_full()`` -If there are no pending messages then ``None`` is returned. + If there are no pending messages then ``None`` is returned. -The three values in the tuple represent: + The three values in the tuple represent: -- the next incoming message on the message queue as bytes. -- the RSSI (signal strength): a value between 0 (strongest) and -255 (weakest) as measured in dBm. -- a microsecond timestamp: the value returned by ``time.ticks_us()`` when the message was received. + - the next incoming message on the message queue as bytes. + - the RSSI (signal strength): a value between 0 (strongest) and -255 (weakest) as measured in dBm. + - a microsecond timestamp: the value returned by ``time.ticks_us()`` when the message was received. -For example:: + For example:: - details = radio.receive_full() - if details: - msg, rssi, timestamp = details + details = radio.receive_full() + if details: + msg, rssi, timestamp = details -This function is useful for providing information needed for triangulation -and/or trilateration with other micro:bit devices. + This function is useful for providing information needed for triangulation + and/or trilateration with other micro:bit devices. -:return: ``None`` if there is no message, otherwise a tuple of length three with the bytes, strength and timestamp values.""" - ... \ No newline at end of file + :return: ``None`` if there is no message, otherwise a tuple of length three with the bytes, strength and timestamp values. + """ + ... diff --git a/lang/es-es/typeshed/stdlib/random.pyi b/lang/es-es/typeshed/stdlib/random.pyi index a1e6d13..a2c2ef3 100644 --- a/lang/es-es/typeshed/stdlib/random.pyi +++ b/lang/es-es/typeshed/stdlib/random.pyi @@ -1,80 +1,93 @@ -"""Generar números aleatorios. (aleatorio)""" +"""Generate random numbers. +""" from typing import TypeVar, Sequence, Union, overload def getrandbits(n: int) -> int: - """Genera un entero con ``n`` bits aleatorios. + """Generate an integer with ``n`` random bits. -Example: ``random.getrandbits(1)`` + Example: ``random.getrandbits(1)`` -:param n: Un valor entre 1 - 30 (inclusive).""" + :param n: A value between 1-30 (inclusive). + """ ... def seed(n: int) -> None: - """Inicializa el generador de números aleatorios. (semilla) + """Initialize the random number generator. -Example: ``random.seed(0)`` + Example: ``random.seed(0)`` -:param n: La semilla como un número entero + :param n: The integer seed -This will give you reproducibly deterministic randomness from a given starting -state (``n``).""" + This will give you reproducibly deterministic randomness from a given starting + state (``n``). + """ ... def randint(a: int, b: int) -> int: - """Elige un entero aleatorio entre ``a`` y ``b`` inclusive. (entero aleatorio) + """Choose a random integer between ``a`` and ``b`` inclusive. -Example: ``random.randint(0, 9)`` + Example: ``random.randint(0, 9)`` -:param a: Valor inicial para el rango (inclusive) -:param b: Valor final para el rango (inclusive) + :param a: Start value for the range (inclusive) + :param b: End value for the range (inclusive) -Alias for ``randrange(a, b + 1)``.""" + Alias for ``randrange(a, b + 1)``. + """ ... @overload def randrange(stop: int) -> int: - """Elige un entero seleccionado aleatoriamente desde cero hasta (pero sin incluir) ``stop``. (rango aleatorio) + """Choose a randomly selected integer between zero and up to (but not + including) ``stop``. -Example: ``random.randrange(10)`` + Example: ``random.randrange(10)`` -:param stop: (detener) Valor final para el rango (exclusivo)""" + :param stop: End value for the range (exclusive) + """ ... @overload -def randrange(start: int, stop: int, step: int=1) -> int: - """Elige un elemento seleccionado aleatoriamente de ``range(start, stop, step)``. (rango aleatorio) +def randrange(start: int, stop: int, step: int = 1) -> int: + """ + Choose a randomly selected element from ``range(start, stop, step)``. -Example: ``random.randrange(0, 10)`` + Example: ``random.randrange(0, 10)`` -:param start: (comenzar) El inicio del rango (inclusive) -:param stop: (detener) El final del rango (exclusivo) -:param step: (paso) El paso.""" + :param start: The start of the range (inclusive) + :param stop: The end of the range (exclusive) + :param step: The step. + """ ... -_T = TypeVar('_T') + +_T = TypeVar("_T") def choice(seq: Sequence[_T]) -> _T: - """Elige un elemento aleatorio de la secuencia no vacía ``seq``. (elección) + """Choose a random element from the non-empty sequence ``seq``. -Example: ``random.choice([Image.HAPPY, Image.SAD])`` + Example: ``random.choice([Image.HAPPY, Image.SAD])`` -:param seq: (sec) Una secuencia. + :param seq: A sequence. -If ``seq`` is empty, raises ``IndexError``.""" + If ``seq`` is empty, raises ``IndexError``. + """ ... def random() -> float: - """Genera un número de coma flotante aleatorio en el rango [0.0, 1.0). (aleatorio) + """Generate a random floating point number in the range [0.0, 1.0). -Example: ``random.random()`` + Example: ``random.random()`` -:return: The random floating point number""" + :return: The random floating point number + """ ... def uniform(a: float, b: float) -> float: - """Devuelve un número de coma flotante aleatorio entre ``a`` y ``b`` inclusive. (uniforme) + """ + Return a random floating point number between ``a`` and ``b`` inclusive. -Example: ``random.uniform(0, 9)`` + Example: ``random.uniform(0, 9)`` -:param a: Valor inicial para el rango (inclusive) -:param b: Valor final para el rango (inclusive)""" - ... \ No newline at end of file + :param a: Start value for the range (inclusive) + :param b: End value for the range (inclusive) + """ + ... diff --git a/lang/es-es/typeshed/stdlib/speech.pyi b/lang/es-es/typeshed/stdlib/speech.pyi index 7494036..349d188 100644 --- a/lang/es-es/typeshed/stdlib/speech.pyi +++ b/lang/es-es/typeshed/stdlib/speech.pyi @@ -1,79 +1,106 @@ -"""Hacer que el micro:bit hable, cante y haga otros sonidos parecidos a la voz. (habla)""" +"""Make the micro:bit talk, sing and make other speech like sounds. +""" + from typing import Optional from .microbit import MicroBitDigitalPin, pin0 def translate(words: str) -> str: - """Traducir palabras en inglés a fonemas. (traducir) + """Translate English words to phonemes. -Example: ``speech.translate('hello world')`` + Example: ``speech.translate('hello world')`` -:param words: (palabras) Una cadena de palabras en inglés. -:return: A string containing a best guess at the appropriate phonemes to pronounce. -The output is generated from this `text to phoneme translation table `_. + :param words: A string of English words. + :return: A string containing a best guess at the appropriate phonemes to pronounce. + The output is generated from this `text to phoneme translation table `_. -This function should be used to generate a first approximation of phonemes -that can be further hand-edited to improve accuracy, inflection and -emphasis. + This function should be used to generate a first approximation of phonemes + that can be further hand-edited to improve accuracy, inflection and + emphasis. -See `the online documentation `_ for detailed information.""" + See `the online documentation `_ for detailed information. + """ ... -def pronounce(phonemes: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: Optional[MicroBitDigitalPin]=pin0) -> None: - """Pronunciar fonemas. (pronunciar) - -Example: ``speech.pronounce(' /HEHLOW WERLD')`` - -:param phonemes: (fonemas) La cadena de fonemas a pronunciar -:param pitch: (tono) Un número que representa el tono de la voz -:param speed: (velocidad) Un número que representa la velocidad de la voz -:param mouth: (boca) Un número que representa la boca de la voz -:param throat: (garganta) Un número que representa la garganta de la voz -:param pin: Se puede usar un argumento opcional para especificar el pin de salida, reemplazando el valor predeterminado de ``pin0``. -Si no queremos que se reproduzca ningún sonido, podemos usar ``pin=None``. Solo para el micro:bit V2. - -Override the optional pitch, speed, mouth and throat settings to change the -timbre (quality) of the voice. - -See `the online documentation `_ for detailed information.""" +def pronounce( + phonemes: str, + pitch: int = 64, + speed: int = 72, + mouth: int = 128, + throat: int = 128, + pin: Optional[MicroBitDigitalPin] = pin0, +) -> None: + """Pronounce phonemes. + + Example: ``speech.pronounce(' /HEHLOW WERLD')`` + + :param phonemes: The string of phonemes to pronounce + :param pitch: A number representing the pitch of the voice + :param speed: A number representing the speed of the voice + :param mouth: A number representing the mouth of the voice + :param throat: A number representing the throat of the voice + :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. + If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. + + Override the optional pitch, speed, mouth and throat settings to change the + timbre (quality) of the voice. + + See `the online documentation `_ for detailed information. + """ ... -def say(words: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: MicroBitDigitalPin=pin0) -> None: - """Dice palabras en inglés. (decir) - -Example: ``speech.say('hello world')`` - -:param words: (palabras) La cadena de palabras a decir. -:param pitch: (tono) Un número que representa el tono de la voz -:param speed: (velocidad) Un número que representa la velocidad de la voz -:param mouth: (boca) Un número que representa la boca de la voz -:param throat: (garganta) Un número que representa la garganta de la voz -:param pin: Se puede usar un argumento opcional para especificar el pin de salida, reemplazando el valor predeterminado de ``pin0``. -Si no queremos que se reproduzca ningún sonido, podemos usar ``pin=None``. Solo para el micro:bit V2. - -The result is semi-accurate for English. Override the optional pitch, speed, -mouth and throat settings to change the timbre (quality) of the voice. - -This is a short-hand equivalent of: -``speech.pronounce(speech.translate(words))`` - -See `the online documentation `_ for detailed information.""" +def say( + words: str, + pitch: int = 64, + speed: int = 72, + mouth: int = 128, + throat: int = 128, + pin: MicroBitDigitalPin = pin0, +) -> None: + """Say English words. + + Example: ``speech.say('hello world')`` + + :param words: The string of words to say. + :param pitch: A number representing the pitch of the voice + :param speed: A number representing the speed of the voice + :param mouth: A number representing the mouth of the voice + :param throat: A number representing the throat of the voice + :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. + If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. + + The result is semi-accurate for English. Override the optional pitch, speed, + mouth and throat settings to change the timbre (quality) of the voice. + + This is a short-hand equivalent of: + ``speech.pronounce(speech.translate(words))`` + + See `the online documentation `_ for detailed information. + """ ... -def sing(phonemes: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: MicroBitDigitalPin=pin0) -> None: - """Canta fonemas. (cantar) - -Example: ``speech.sing(' /HEHLOW WERLD')`` - -:param phonemes: (fonemas) La cadena de palabras a cantar. -:param pitch: (tono) Un número que representa el tono de la voz -:param speed: (velocidad) Un número que representa la velocidad de la voz -:param mouth: (boca) Un número que representa la boca de la voz -:param throat: (garganta) Un número que representa la garganta de la voz -:param pin: Se puede usar un argumento opcional para especificar el pin de salida, reemplazando el valor predeterminado de ``pin0``. -Si no queremos que se reproduzca ningún sonido, podemos usar ``pin=None``. Solo para el micro:bit V2. - -Override the optional pitch, speed, mouth and throat settings to change -the timbre (quality) of the voice. - -See `the online documentation `_ for detailed information.""" - ... \ No newline at end of file +def sing( + phonemes: str, + pitch: int = 64, + speed: int = 72, + mouth: int = 128, + throat: int = 128, + pin: MicroBitDigitalPin = pin0, +) -> None: + """Sing phonemes. + + Example: ``speech.sing(' /HEHLOW WERLD')`` + + :param phonemes: The string of words to sing. + :param pitch: A number representing the pitch of the voice + :param speed: A number representing the speed of the voice + :param mouth: A number representing the mouth of the voice + :param throat: A number representing the throat of the voice + :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. + If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. + + Override the optional pitch, speed, mouth and throat settings to change + the timbre (quality) of the voice. + + See `the online documentation `_ for detailed information. + """ + ... diff --git a/lang/es-es/typeshed/stdlib/struct.pyi b/lang/es-es/typeshed/stdlib/struct.pyi index 9d0a36d..53b3e0b 100644 --- a/lang/es-es/typeshed/stdlib/struct.pyi +++ b/lang/es-es/typeshed/stdlib/struct.pyi @@ -1,56 +1,65 @@ -"""Empaquetar y desempaquetar tipos de dato primitivos. (estruc)""" +"""Pack and unpack primitive data types. +""" + from _typeshed import ReadableBuffer, WriteableBuffer from typing import Any, Tuple, Union def calcsize(fmt: str) -> int: - """Obtiene el número de bytes necesarios para almacenar el ``fmt`` dado. (calctamaño) + """Get the number of bytes needed to store the given ``fmt``. -Example: ``struct.calcsize('hf')`` + Example: ``struct.calcsize('hf')`` -:param fmt: Una cadena de formato. -:return The number of bytes needed to store such a value.""" + :param fmt: A format string. + :return The number of bytes needed to store such a value. + """ ... def pack(fmt: str, v1: Any, *vn: Any) -> bytes: - """Empaqueta valores según una cadena de formato. (empaquetar) + """Pack values according to a format string. -Example: ``struct.pack('hf', 1, 3.1415)`` + Example: ``struct.pack('hf', 1, 3.1415)`` -:param fmt: La cadena de formato. -:param v1: El primer valor. -:param *vn: Los valores restantes. -:return A bytes object encoding the values.""" + :param fmt: The format string. + :param v1: The first value. + :param *vn: The remaining values. + :return A bytes object encoding the values. + """ ... -def pack_into(fmt: str, buffer: WriteableBuffer, offset: int, v1: Any, *vn: Any) -> None: - """Empaqueta valores según una cadena de formato. (empaquetar en) +def pack_into( + fmt: str, buffer: WriteableBuffer, offset: int, v1: Any, *vn: Any +) -> None: + """Pack values according to a format string. -Example: ``struct.pack_info('hf', buffer, 1, 3.1415)`` + Example: ``struct.pack_info('hf', buffer, 1, 3.1415)`` -:param fmt: La cadena de formato. -:param buffer: (búfer) El búfer de destino en el que se va a escribir. -:param offset: (desplazamiento) El desplazamiento en el búfer. Puede ser negativo para contar desde el final del búfer. -:param v1: El primer valor. -:param *vn: Los valores restantes.""" + :param fmt: The format string. + :param buffer: The target buffer to write into. + :param offset: The offset into the buffer. May be negative to count from the end of the buffer. + :param v1: The first value. + :param *vn: The remaining values. + """ ... def unpack(fmt: str, data: ReadableBuffer) -> Tuple[Any, ...]: - """Desempaqueta datos según una cadena de formato. (desempaquetar) + """Unpack data according to a format string. -Example: ``v1, v2 = struct.unpack('hf', buffer)`` + Example: ``v1, v2 = struct.unpack('hf', buffer)`` -:param fmt: La cadena de formato. -:param data: (datos) Los datos. -:return: A tuple of the unpacked values.""" + :param fmt: The format string. + :param data: The data. + :return: A tuple of the unpacked values. + """ ... -def unpack_from(fmt: str, buffer: ReadableBuffer, offset: int=0) -> Tuple: - """Desempaqueta datos de un búfer según una cadena de formato. (desempaquetar de) +def unpack_from(fmt: str, buffer: ReadableBuffer, offset: int = 0) -> Tuple: + """Unpack data from a buffer according to a format string. -Example: ``v1, v2 = struct.unpack_from('hf', buffer)`` + Example: ``v1, v2 = struct.unpack_from('hf', buffer)`` -:param fmt: La cadena de formato. -:param buffer: (búfer) El búfer de origen del que leer. -:param offset: (desplazamiento) El desplazamiento en el búfer. Puede ser negativo para contar desde el final del búfer. -:return: A tuple of the unpacked values.""" - ... \ No newline at end of file + :param fmt: The format string. + :param buffer: The source buffer to read from. + :param offset: The offset into the buffer. May be negative to count from the end of the buffer. + :return: A tuple of the unpacked values. + """ + ... diff --git a/lang/es-es/typeshed/stdlib/sys.pyi b/lang/es-es/typeshed/stdlib/sys.pyi index 7f93873..320bac9 100644 --- a/lang/es-es/typeshed/stdlib/sys.pyi +++ b/lang/es-es/typeshed/stdlib/sys.pyi @@ -1,36 +1,43 @@ -"""Funciones específicas del sistema""" +"""System specific functions""" + from typing import Any, Dict, List, NoReturn, TextIO, Tuple -def exit(retval: object=...) -> NoReturn: - """Termina el programa actual con un código de salida determinado. (salir) +def exit(retval: object = ...) -> NoReturn: + """Terminate current program with a given exit code. -Example: ``sys.exit(1)`` + Example: ``sys.exit(1)`` -This function raises a ``SystemExit`` exception. If an argument is given, its -value given as an argument to ``SystemExit``. + This function raises a ``SystemExit`` exception. If an argument is given, its + value given as an argument to ``SystemExit``. -:param retval: El mensaje o código de salida.""" + :param retval: The exit code or message. + """ ... def print_exception(exc: Exception) -> None: - """Imprime una excepción con un seguimiento. (imprimir excepción) + """ + Print an exception with a traceback. + + Example: ``sys.print_exception(e)`` -Example: ``sys.print_exception(e)`` + :param exc: The exception to print -:param exc: La excepción a imprimir + This is simplified version of a function which appears in the + ``traceback`` module in CPython. + """ -This is simplified version of a function which appears in the -``traceback`` module in CPython.""" argv: List[str] -"""Una lista mutable de argumentos con los que se inició el programa actual.""" +"""A mutable list of arguments the current program was started with.""" + byteorder: str -"""El orden de bytes del sistema (``"little"`` o ``"big"``). (ordenbytes)""" +"""The byte order of the system (``"little"`` or ``"big"``).""" class _implementation: name: str version: Tuple[int, int, int] + implementation: _implementation -"""Objeto con información sobre la implementación actual de Python. (implementación) +"""Object with information about the current Python implementation. For MicroPython, it has following attributes: @@ -44,12 +51,13 @@ minimal ports). CPython mandates more attributes for this object, but the actual useful bare minimum is implemented in MicroPython. """ + maxsize: int """ -Valor máximo que un tipo entero nativo puede contener en la plataforma actual -o valor máximo representable por el tipo entero de MicroPython, en el caso de que sea más pequeño -que el valor máximo de la plataforma (que es el caso de los puertos de MicroPython incompatibles con el -tipo entero largo). (tamañomáx) +Maximum value which a native integer type can hold on the current platform, +or maximum value representable by MicroPython integer type, if it's smaller +than platform max value (that is the case for MicroPython ports without +long int support). This attribute is useful for detecting "bitness" of a platform (32-bit vs 64-bit, etc.). It's recommended to not compare this attribute to some @@ -69,14 +77,17 @@ value directly, but instead count number of bits in it:: # (e.g. 31) due to peculiarities described above, so use "> 16", # "> 32", "> 64" style of comparisons. """ + modules: Dict[str, Any] -"""Diccionario de módulos cargados. (módulos) +"""Dictionary of loaded modules. On some ports, it may not include builtin modules.""" + path: List[str] -"""Una lista mutable de directorios para buscar módulos importados. (ruta)""" +"""A mutable list of directories to search for imported modules.""" + platform: str -"""La plataforma en la que se está ejecutando MicroPython. (plataforma) +"""The platform that MicroPython is running on. For OS/RTOS ports, this is usually an identifier of the OS, e.g. ``"linux"``. For baremetal ports it is an identifier of a board, e.g. ``"pyboard"`` for @@ -86,11 +97,13 @@ distinguish one board from another. If you need to check whether your program runs on MicroPython (vs other Python implementation), use ``sys.implementation`` instead. """ + version: str -"""Versión del lenguaje Python a la que se ajusta esta implementación, en forma de cadena. (versión)""" +"""Python language version that this implementation conforms to, as a string.""" + version_info: Tuple[int, int, int] -"""Versión del lenguaje Python a la que se ajusta esta implementación, en forma de tupla de enteros. (info de versión) +"""Python language version that this implementation conforms to, as a tuple of ints. Only the first three version numbers (major, minor, micro) are supported and they can be referenced only by index, not by name. -""" \ No newline at end of file +""" diff --git a/lang/es-es/typeshed/stdlib/time.pyi b/lang/es-es/typeshed/stdlib/time.pyi index 6dd4bb3..598c483 100644 --- a/lang/es-es/typeshed/stdlib/time.pyi +++ b/lang/es-es/typeshed/stdlib/time.pyi @@ -1,112 +1,132 @@ -"""Mide el tiempo y añade retardos a los programas. (tiempo)""" +"""Measure time and add delays to programs. +""" + from typing import Union def sleep(seconds: Union[int, float]) -> None: - """Retarda varios segundos. (dormir) + """ + Delay a number of seconds. -Example: ``time.sleep(1)`` + Example: ``time.sleep(1)`` -:param seconds: (segundos) El número de segundos de retardo. -Usa un número de coma flotante para generar un retardo durante un número fraccional de segundos.""" + :param seconds: The number of seconds to sleep for. + Use a floating-point number to sleep for a fractional number of seconds. + """ ... def sleep_ms(ms: int) -> None: - """Genera un retardo para el número dado de milisegundos. (dormir ms) + """ + Delay for given number of milliseconds. -Example: ``time.sleep_ms(1_000_000)`` + Example: ``time.sleep_ms(1_000_000)`` -:param ms: El número de milisegundos de retardo (>= 0).""" + :param ms: The number of milliseconds delay (>= 0). + """ ... def sleep_us(us: int) -> None: - """Genera un retardo para el número dado de microsegundos. (dormir us) + """ + Delay for given number of microseconds. -Example: ``time.sleep_us(1000)`` + Example: ``time.sleep_us(1000)`` -:param us: El número de microsegundos de retardo (>= 0).""" + :param us: The number of microseconds delay (>= 0). + """ ... def ticks_ms() -> int: - """Obtiene un contador en milisegundos creciente con un punto de referencia arbitrario que se reinicia después de algún valor. (tics ms) + """ + Get an increasing, millisecond counter with an arbitrary reference point, + that wraps around after some value. -Example: ``time.ticks_ms()`` + Example: ``time.ticks_ms()`` -:return: The counter value in milliseconds.""" + :return: The counter value in milliseconds. + """ ... def ticks_us() -> int: - """Obtiene un contador en microsegundos creciente con un punto de referencia arbitrario que se reinicia después de algún valor. (tics us) + """ + Get an increasing, microsecond counter with an arbitrary reference point, + that wraps around after some value. -Example: ``time.ticks_us()`` + Example: ``time.ticks_us()`` -:return: The counter value in microseconds.""" + :return: The counter value in microseconds. + """ ... def ticks_add(ticks: int, delta: int) -> int: - """Valor de desplazamiento de tics por un número determinado, el cual puede ser positivo o -negativo. (añadir tics) + """ + Offset ticks value by a given number, which can be either positive or + negative. -Example: ``time.ticks_add(time.ticks_ms(), 200)`` + Example: ``time.ticks_add(time.ticks_ms(), 200)`` -Given a ticks value, this function allows to calculate ticks -value delta ticks before or after it, following modular-arithmetic -definition of tick values. + Given a ticks value, this function allows to calculate ticks + value delta ticks before or after it, following modular-arithmetic + definition of tick values. -:param ticks: (tics) Un valor de tics -:param delta: Un desplazamiento entero + :param ticks: A ticks value + :param delta: An integer offset -Example:: + Example:: - # Find out what ticks value there was 100ms ago - print(ticks_add(time.ticks_ms(), -100)) + # Find out what ticks value there was 100ms ago + print(ticks_add(time.ticks_ms(), -100)) - # Calculate deadline for operation and test for it - deadline = ticks_add(time.ticks_ms(), 200) - while ticks_diff(deadline, time.ticks_ms()) > 0: - do_a_little_of_something() + # Calculate deadline for operation and test for it + deadline = ticks_add(time.ticks_ms(), 200) + while ticks_diff(deadline, time.ticks_ms()) > 0: + do_a_little_of_something() - # Find out TICKS_MAX used by this port - print(ticks_add(0, -1))""" + # Find out TICKS_MAX used by this port + print(ticks_add(0, -1)) + """ ... def ticks_diff(ticks1: int, ticks2: int) -> int: - """Mide la diferencia de tics entre los valores devueltos por ``time.ticks_ms()`` o ``ticks_us()`` como un valor con signo que se puede reiniciar. (diferencia de tics) - -Example: ``time.ticks_diff(scheduled_time, now)`` - -:param ticks1: (tics1) El valor del que restar -:param ticks2: (tics2) El valor a restar - -The argument order is the same as for subtraction operator, -``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. - -``ticks_diff()`` is designed to accommodate various usage -patterns, among them: - -Polling with timeout. In this case, the order of events is known, and you -will deal only with positive results of :func:`time.ticks_diff()`:: - - # Wait for GPIO pin to be asserted, but at most 500us - start = time.ticks_us() - while pin.value() == 0: - if time.ticks_diff(time.ticks_us(), start) > 500: - raise TimeoutError - - -Scheduling events. In this case, :func:`time.ticks_diff()` result may be -negative if an event is overdue:: - - # This code snippet is not optimized - now = time.ticks_ms() - scheduled_time = task.scheduled_time() - if ticks_diff(scheduled_time, now) > 0: - print("Too early, let's nap") - sleep_ms(ticks_diff(scheduled_time, now)) - task.run() - elif ticks_diff(scheduled_time, now) == 0: - print("Right at time!") - task.run() - elif ticks_diff(scheduled_time, now) < 0: - print("Oops, running late, tell task to run faster!") - task.run(run_faster=True)""" - ... \ No newline at end of file + """ + Measure ticks difference between values returned from + ``time.ticks_ms()`` or ``ticks_us()``, as a signed value + which may wrap around. + + Example: ``time.ticks_diff(scheduled_time, now)`` + + :param ticks1: The value to subtract from + :param ticks2: The value to subtract + + The argument order is the same as for subtraction operator, + ``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. + + ``ticks_diff()`` is designed to accommodate various usage + patterns, among them: + + Polling with timeout. In this case, the order of events is known, and you + will deal only with positive results of :func:`time.ticks_diff()`:: + + # Wait for GPIO pin to be asserted, but at most 500us + start = time.ticks_us() + while pin.value() == 0: + if time.ticks_diff(time.ticks_us(), start) > 500: + raise TimeoutError + + + Scheduling events. In this case, :func:`time.ticks_diff()` result may be + negative if an event is overdue:: + + # This code snippet is not optimized + now = time.ticks_ms() + scheduled_time = task.scheduled_time() + if ticks_diff(scheduled_time, now) > 0: + print("Too early, let's nap") + sleep_ms(ticks_diff(scheduled_time, now)) + task.run() + elif ticks_diff(scheduled_time, now) == 0: + print("Right at time!") + task.run() + elif ticks_diff(scheduled_time, now) < 0: + print("Oops, running late, tell task to run faster!") + task.run(run_faster=True) + """ + ... diff --git a/lang/fr/typeshed/stdlib/gc.pyi b/lang/fr/typeshed/stdlib/gc.pyi index f74d65f..1370abf 100644 --- a/lang/fr/typeshed/stdlib/gc.pyi +++ b/lang/fr/typeshed/stdlib/gc.pyi @@ -1,68 +1,73 @@ -"""Contrôler le ramasse-miettes""" +"""Control the garbage collector""" + from typing import overload def enable() -> None: - """Active la collecte automatique du ramasse-miettes.""" + """Enable automatic garbage collection.""" ... def disable() -> None: - """Désactive la collecte automatique du ramasse-miettes. + """Disable automatic garbage collection. -Heap memory can still be allocated, -and garbage collection can still be initiated manually using ``gc.collect``.""" + Heap memory can still be allocated, + and garbage collection can still be initiated manually using ``gc.collect``.""" def collect() -> None: - """Exécute une collecte avec le ramasse-miettes""" + """Run a garbage collection.""" ... def mem_alloc() -> int: - """Obtenir le nombre d'octets alloués pour le tas en RAM + """Get the number of bytes of heap RAM that are allocated. -:return: The number of bytes allocated. + :return: The number of bytes allocated. -This function is MicroPython extension.""" + This function is MicroPython extension. + """ ... def mem_free() -> int: - """Obtenir le nombre d'octets disponibles pour le tas en RAM, ou -1 si ce nombre est inconnu. + """Get the number of bytes of available heap RAM, or -1 if this amount is not known. -:return: The number of bytes free. + :return: The number of bytes free. -This function is MicroPython extension.""" + This function is MicroPython extension. + """ ... @overload def threshold() -> int: - """Demander le seuil d'allocation supplémentaire GC. + """Query the additional GC allocation threshold. -:return: The GC allocation threshold. + :return: The GC allocation threshold. -This function is a MicroPython extension. CPython has a similar -function - ``set_threshold()``, but due to different GC -implementations, its signature and semantics are different.""" + This function is a MicroPython extension. CPython has a similar + function - ``set_threshold()``, but due to different GC + implementations, its signature and semantics are different. + """ ... @overload def threshold(amount: int) -> None: - """Fixer le seuil d'allocation supplémentaire GC. - -Normally, a collection is triggered only when a new allocation -cannot be satisfied, i.e. on an out-of-memory (OOM) condition. -If this function is called, in addition to OOM, a collection -will be triggered each time after ``amount`` bytes have been -allocated (in total, since the previous time such an amount of bytes -have been allocated). ``amount`` is usually specified as less than the -full heap size, with the intention to trigger a collection earlier than when the -heap becomes exhausted, and in the hope that an early collection will prevent -excessive memory fragmentation. This is a heuristic measure, the effect -of which will vary from application to application, as well as -the optimal value of the ``amount`` parameter. - -A value of -1 means a disabled allocation threshold. - -This function is a MicroPython extension. CPython has a similar -function - ``set_threshold()``, but due to different GC -implementations, its signature and semantics are different. - -:param amount: Le nombre d'octets après lequel un passage du ramasse-miettes doit être déclenché.""" - ... \ No newline at end of file + """Set the additional GC allocation threshold. + + Normally, a collection is triggered only when a new allocation + cannot be satisfied, i.e. on an out-of-memory (OOM) condition. + If this function is called, in addition to OOM, a collection + will be triggered each time after ``amount`` bytes have been + allocated (in total, since the previous time such an amount of bytes + have been allocated). ``amount`` is usually specified as less than the + full heap size, with the intention to trigger a collection earlier than when the + heap becomes exhausted, and in the hope that an early collection will prevent + excessive memory fragmentation. This is a heuristic measure, the effect + of which will vary from application to application, as well as + the optimal value of the ``amount`` parameter. + + A value of -1 means a disabled allocation threshold. + + This function is a MicroPython extension. CPython has a similar + function - ``set_threshold()``, but due to different GC + implementations, its signature and semantics are different. + + :param amount: The number of bytes after which a garbage collection should be triggered. + """ + ... diff --git a/lang/fr/typeshed/stdlib/log.pyi b/lang/fr/typeshed/stdlib/log.pyi index 2a33dad..c9870fa 100644 --- a/lang/fr/typeshed/stdlib/log.pyi +++ b/lang/fr/typeshed/stdlib/log.pyi @@ -1,89 +1,104 @@ -"""Journalisez des données sur votre micro:bit V2.""" +"""Log data to your micro:bit V2.""" + from typing import Literal, Mapping, Optional, Union, overload + MILLISECONDS = 1 -"""Format d'horodatage en millisecondes.""" +"""Milliseconds timestamp format.""" + SECONDS = 10 -"""Format d'horodatage en secondes.""" +"""Seconds timestamp format.""" + MINUTES = 600 -"""Format d'horodatage en minutes.""" +"""Minutes timestamp format.""" + HOURS = 36000 -"""Format d'horodatage en heures.""" +"""Hours timestamp format.""" + DAYS = 864000 -"""Format d'horodatage en jours.""" +"""Days timestamp format.""" -def set_labels(*labels: str, timestamp: Optional[Literal[1, 10, 36000, 864000]]=SECONDS) -> None: - """Définir l'en-tête du fichier journal +def set_labels( + *labels: str, timestamp: Optional[Literal[1, 10, 36000, 864000]] = SECONDS +) -> None: + """Set up the log file header. -Example: ``log.set_labels('X', 'Y', 'Z', timestamp=log.MINUTES)`` + Example: ``log.set_labels('X', 'Y', 'Z', timestamp=log.MINUTES)`` -Ideally this function should be called a single time, before any data is -logged, to configure the data table header once. + Ideally this function should be called a single time, before any data is + logged, to configure the data table header once. -If a log file already exists when the program starts, or if this function -is called multiple times, it will check the labels already defined in the -log file. If this function call contains any new labels not already -present, it will generate a new header row with the additional columns. + If a log file already exists when the program starts, or if this function + is called multiple times, it will check the labels already defined in the + log file. If this function call contains any new labels not already + present, it will generate a new header row with the additional columns. -By default the first column contains a timestamp for each row. The time -unit can be selected via the timestamp argument. + By default the first column contains a timestamp for each row. The time + unit can be selected via the timestamp argument. -:param *labels: Un nombre quelconque d'arguments positionnels, chacun correspondant à une entrée dans l'en-tête du journal. -:param timestamp: (horodatage) Sélectionnez l'unité d'horodatage qui sera automatiquement ajoutée comme première colonne de chaque ligne. Les valeurs d'horodatage peuvent être l'une des suivantes ``log.MILLISECONDS``, ``log.SECONDS``, ``log.MINUTES``, ``log.HOURS``, ``log.DAYS`` ou ``None`` pour désactiver l'horodatage. La valeur par défaut est ``log.SECONDS``.""" + :param *labels: Any number of positional arguments, each corresponding to an entry in the log header. + :param timestamp: Select the timestamp unit that will be automatically added as the first column in every row. Timestamp values can be one of ``log.MILLISECONDS``, ``log.SECONDS``, ``log.MINUTES``, ``log.HOURS``, ``log.DAYS`` or ``None`` to disable the timestamp. The default value is ``log.SECONDS``. + """ ... @overload -def add(data_dictionary: Optional[Mapping[str, Union[str, int, float]]]) -> None: - """Ajoute une ligne de données au journal en passant un dictionnaire d'en-têtes et de valeurs. +def add( + data_dictionary: Optional[Mapping[str, Union[str, int, float]]], +) -> None: + """Add a data row to the log by passing a dictionary of headers and values. -Example: ``log.add({ 'temp': temperature() })`` + Example: ``log.add({ 'temp': temperature() })`` -Each call to this function adds a row to the log. + Each call to this function adds a row to the log. -New labels not previously specified via the set_labels function, or by a -previous call to this function, will trigger a new header entry to be added -to the log with the extra labels. + New labels not previously specified via the set_labels function, or by a + previous call to this function, will trigger a new header entry to be added + to the log with the extra labels. -Labels previously specified and not present in a call to this function will -be skipped with an empty value in the log row. + Labels previously specified and not present in a call to this function will + be skipped with an empty value in the log row. -:param data_dictionary: Les données à enregistrer sous forme de dictionnaire avec une clé pour chaque en-tête.""" + :param data_dictionary: The data to log as a dictionary with a key for each header. + """ ... @overload def add(**kwargs: Union[str, int, float]) -> None: - """Ajoute une ligne de données au journal en utilisant des arguments nommés. + """Add a data row to the log using keyword arguments. -Example: ``log.add(temp=temperature())`` + Example: ``log.add(temp=temperature())`` -Each call to this function adds a row to the log. + Each call to this function adds a row to the log. -New labels not previously specified via the set_labels function, or by a -previous call to this function, will trigger a new header entry to be added -to the log with the extra labels. + New labels not previously specified via the set_labels function, or by a + previous call to this function, will trigger a new header entry to be added + to the log with the extra labels. -Labels previously specified and not present in a call to this function will -be skipped with an empty value in the log row.""" + Labels previously specified and not present in a call to this function will + be skipped with an empty value in the log row. + """ ... def delete(full=False): - """Supprime le contenu du journal, y compris les en-têtes. + """Deletes the contents of the log, including headers. -Example: ``log.delete()`` + Example: ``log.delete()`` -To add the log headers again the ``set_labels`` function should to be called after this function. + To add the log headers again the ``set_labels`` function should to be called after this function. -There are two erase modes; “full” completely removes the data from the physical storage, -and “fast” invalidates the data without removing it. + There are two erase modes; “full” completely removes the data from the physical storage, + and “fast” invalidates the data without removing it. -:param full: ``True`` sélectionne un effacement "complet" et ``False`` sélectionne la méthode d'effacement "rapide".""" + :param full: ``True`` selects a “full” erase and ``False`` selects the “fast” erase method. + """ ... def set_mirroring(serial: bool): - """Configurez la mise en miroir de l'activité d'enregistrement des données sur la sortie série. + """Configure mirroring of the data logging activity to the serial output. -Example: ``log.set_mirroring(True)`` + Example: ``log.set_mirroring(True)`` -Serial mirroring is disabled by default. When enabled, it will print to serial each row logged into the log file. + Serial mirroring is disabled by default. When enabled, it will print to serial each row logged into the log file. -:param serial: ``True`` active la mise en miroir des données sur la sortie série.""" - ... \ No newline at end of file + :param serial: ``True`` enables mirroring data to the serial output. + """ + ... diff --git a/lang/fr/typeshed/stdlib/machine.pyi b/lang/fr/typeshed/stdlib/machine.pyi index fbb2e40..2e82f5b 100644 --- a/lang/fr/typeshed/stdlib/machine.pyi +++ b/lang/fr/typeshed/stdlib/machine.pyi @@ -1,84 +1,97 @@ -"""Utilitaires bas niveau""" +"""Low-level utilities. +""" from typing import Any from .microbit import MicroBitDigitalPin def unique_id() -> bytes: - """Récupère une chaîne d'octets représentant un identifiant unique d'une carte. + """Get a byte string with a unique identifier of a board. -Example: ``machine.unique_id()`` + Example: ``machine.unique_id()`` -:return: An identifier that varies from one board instance to another.""" + :return: An identifier that varies from one board instance to another. + """ ... def reset() -> None: - """Réinitialise l'appareil d'une manière similaire à la pression sur le bouton RESET externe. + """Reset the device in a manner similar to pushing the external RESET button. -Example: ``machine.reset()``""" + Example: ``machine.reset()`` + """ ... def freq() -> int: - """Récupère la fréquence du CPU en hertz. + """Get the CPU frequency in hertz. -Example: ``machine.freq()`` + Example: ``machine.freq()`` -:return: The CPU frequency.""" + :return: The CPU frequency. + """ ... def disable_irq() -> Any: - """Désactiver les demandes d'interruption. + """Disable interrupt requests. -Example: ``interrupt_state = machine.disable_irq()`` + Example: ``interrupt_state = machine.disable_irq()`` -:return: the previous IRQ state which should be considered an opaque value + :return: the previous IRQ state which should be considered an opaque value -The return value should be passed to the ``enable_irq`` function to restore -interrupts to their original state.""" + The return value should be passed to the ``enable_irq`` function to restore + interrupts to their original state. + """ ... def enable_irq(state: Any) -> None: - """Réactiver les demandes d'interruption. + """Re-enable interrupt requests. -Example: ``machine.enable_irq(interrupt_state)`` + Example: ``machine.enable_irq(interrupt_state)`` -:param state: La valeur qui a été renvoyée par l'appel le plus récent à la fonction ``disable_irq``.""" + :param state: The value that was returned from the most recent call to the ``disable_irq`` function. + """ ... -def time_pulse_us(pin: MicroBitDigitalPin, pulse_level: int, timeout_us: int=1000000) -> int: - """Chronométrer une impulsion sur une broche. +def time_pulse_us( + pin: MicroBitDigitalPin, pulse_level: int, timeout_us: int = 1000000 +) -> int: + """Time a pulse on a pin. -Example: ``time_pulse_us(pin0, 1)`` + Example: ``time_pulse_us(pin0, 1)`` -If the current input value of the pin is different to ``pulse_level``, the -function first waits until the pin input becomes equal to -``pulse_level``, then times the duration that the pin is equal to -``pulse_level``. If the pin is already equal to ``pulse_level`` then timing -starts straight away. + If the current input value of the pin is different to ``pulse_level``, the + function first waits until the pin input becomes equal to + ``pulse_level``, then times the duration that the pin is equal to + ``pulse_level``. If the pin is already equal to ``pulse_level`` then timing + starts straight away. -:param pin: (broche) La broche à utiliser -:param pulse_level: 0 pour chronométrer une impulsion basse ou 1 pour chronométrer une impulsion haute. -:param timeout_us: Un délai d'attente en microseconde -:return: The duration of the pulse in microseconds, or -1 for a timeout waiting for the level to match ``pulse_level``, or -2 on timeout waiting for the pulse to end""" + :param pin: The pin to use + :param pulse_level: 0 to time a low pulse or 1 to time a high pulse + :param timeout_us: A microsecond timeout + :return: The duration of the pulse in microseconds, or -1 for a timeout waiting for the level to match ``pulse_level``, or -2 on timeout waiting for the pulse to end + """ ... class mem: - """La classe pour les vues mémoire ``mem8``, ``mem16`` et ``mem32``.""" + """The class for the ``mem8``, ``mem16`` and ``mem32`` memory views.""" def __getitem__(self, address: int) -> int: - """Accéder à une valeur dans la mémoire. + """Access a value from memory. -:param address: L'adresse en mémoire. -:return: The value at that address as an integer.""" + :param address: The memory address. + :return: The value at that address as an integer. + """ ... - def __setitem__(self, address: int, value: int) -> None: - """Écrire une valeur à une adresse donnée. + """Set a value at the given address. -:param address: L'adresse en mémoire. -:param value: La valeur entière à écrire.""" + :param address: The memory address. + :param value: The integer value to set. + """ ... + mem8: mem -"""Vue de la mémoire au format 8-bit (octet).""" +"""8-bit (byte) view of memory.""" + mem16: mem -"""Vue de la mémoire au format 16-bit.""" +"""16-bit view of memory.""" + mem32: mem -"""Vue de la mémoire au format 32-bit.""" \ No newline at end of file +"""32-bit view of memory.""" diff --git a/lang/fr/typeshed/stdlib/math.pyi b/lang/fr/typeshed/stdlib/math.pyi index 3dc7d6c..f82d4de 100644 --- a/lang/fr/typeshed/stdlib/math.pyi +++ b/lang/fr/typeshed/stdlib/math.pyi @@ -1,246 +1,273 @@ -"""Fonctions mathématiques.""" +"""Mathematical functions. +""" + from typing import Tuple def acos(x: float) -> float: - """Calculer le cosinus inversé. + """Calculate the inverse cosine. -Example: ``math.acos(1)`` + Example: ``math.acos(1)`` -:param x: Un nombre -:return: The inverse cosine of ``x``""" + :param x: A number + :return: The inverse cosine of ``x`` + """ ... def asin(x: float) -> float: - """Calculer le sinus inversé. + """Calculate the inverse sine. -Example: ``math.asin(0)`` + Example: ``math.asin(0)`` -:param x: Un nombre -:return: The inverse sine of ``x``""" + :param x: A number + :return: The inverse sine of ``x`` + """ ... def atan(x: float) -> float: - """Calculer la tangente inverse. + """Calculate the inverse tangent. -Example: ``math.atan(0)`` + Example: ``math.atan(0)`` -:param x: Un nombre -:return: The inverse tangent of ``x``""" + :param x: A number + :return: The inverse tangent of ``x`` + """ ... def atan2(y: float, x: float) -> float: - """Calculer la valeur principale de la tangente inverse de ``y/x``. + """Calculate the principal value of the inverse tangent of ``y/x``. -Example: ``math.atan2(0, -1)`` + Example: ``math.atan2(0, -1)`` -:param y: Un nombre -:param x: Un nombre -:return: The principal value of the inverse tangent of ``y/x``""" + :param y: A number + :param x: A number + :return: The principal value of the inverse tangent of ``y/x`` + """ ... def ceil(x: float) -> float: - """Arrondir un nombre vers l'infini positif. + """Round a number towards positive infinity. -Example: ``math.ceil(0.1)`` + Example: ``math.ceil(0.1)`` -:param x: Un nombre -:return: ``x`` rounded towards positive infinity.""" + :param x: A number + :return: ``x`` rounded towards positive infinity. + """ ... def copysign(x: float, y: float) -> float: - """Calculer ``x`` avec le signe de ``y``. + """Calculate ``x`` with the sign of ``y``. -Example: ``math.copysign(1, -1)`` + Example: ``math.copysign(1, -1)`` -:param x: Un nombre -:param y: La source du signe pour la valeur de retour -:return: ``x`` with the sign of ``y``""" + :param x: A number + :param y: The source of the sign for the return value + :return: ``x`` with the sign of ``y`` + """ ... def cos(x: float) -> float: - """Calculer le cosinus de ``x``. + """Calculate the cosine of ``x``. -Example: ``math.cos(0)`` + Example: ``math.cos(0)`` -:param x: Un nombre -:return: The cosine of ``x``""" + :param x: A number + :return: The cosine of ``x`` + """ ... def degrees(x: float) -> float: - """Convertir les radians en degrés. (degrés) + """Convert radians to degrees. -Example: ``math.degrees(2 * math.pi)`` + Example: ``math.degrees(2 * math.pi)`` -:param x: Une valeur en radians -:return: The value converted to degrees""" + :param x: A value in radians + :return: The value converted to degrees""" ... def exp(x: float) -> float: - """Calculer l'exponentiel de ``x``. + """Calculate the exponential of ``x``. -Example: ``math.exp(1)`` + Example: ``math.exp(1)`` -:param x: Un nombre -:return: The exponential of ``x``.""" + :param x: A number + :return: The exponential of ``x``. + """ ... def fabs(x: float) -> float: - """Renvoie la valeur absolue de ``x``. + """Return the absolute value of ``x``. -Example: ``math.fabs(-0.1)`` + Example: ``math.fabs(-0.1)`` -:param x: Un nombre -:return: The absolute value of ``x``""" + :param x: A number + :return: The absolute value of ``x`` + """ ... def floor(x: float) -> int: - """Arrondir un nombre vers l'infini négatif. + """Round a number towards negative infinity. -Example: ``math.floor(0.9)`` + Example: ``math.floor(0.9)`` -:param x: Un nombre -:return: ``x`` rounded towards negative infinity.""" + :param x: A number + :return: ``x`` rounded towards negative infinity. + """ ... def fmod(x: float, y: float) -> float: - """Calculer le reste de ``x/y``. + """Calculate the remainder of ``x/y``. -Example: ``math.fmod(10, 3)`` + Example: ``math.fmod(10, 3)`` -:param x: Le numérateur -:param y: Le dénominateur""" + :param x: The numerator + :param y: The denominator + """ ... def frexp(x: float) -> Tuple[float, int]: - """Décompose un nombre à virgule flottante en sa mantisse et son exposant. + """Decomposes a floating-point number into its mantissa and exponent. -Example: ``mantissa, exponent = math.frexp(2)`` + Example: ``mantissa, exponent = math.frexp(2)`` -The returned value is the tuple ``(m, e)`` such that ``x == m * 2**e`` -exactly. If ``x == 0`` then the function returns ``(0.0, 0)``, otherwise -the relation ``0.5 <= abs(m) < 1`` holds. + The returned value is the tuple ``(m, e)`` such that ``x == m * 2**e`` + exactly. If ``x == 0`` then the function returns ``(0.0, 0)``, otherwise + the relation ``0.5 <= abs(m) < 1`` holds. -:param x: Un nombre à virgule flottante -:return: A tuple of length two containing its mantissa then exponent""" + :param x: A floating-point number + :return: A tuple of length two containing its mantissa then exponent + """ ... def isfinite(x: float) -> bool: - """Vérifier si une valeur est finie. + """Check if a value is finite. -Example: ``math.isfinite(float('inf'))`` + Example: ``math.isfinite(float('inf'))`` -:param x: Un nombre. -:return: ``True`` if ``x`` is finite, ``False`` otherwise.""" + :param x: A number. + :return: ``True`` if ``x`` is finite, ``False`` otherwise. + """ ... def isinf(x: float) -> bool: - """Vérifie si une valeur est infinie. + """Check if a value is infinite. -Example: ``math.isinf(float('-inf'))`` + Example: ``math.isinf(float('-inf'))`` -:param x: Un nombre. -:return: ``True`` if ``x`` is infinite, ``False`` otherwise.""" + :param x: A number. + :return: ``True`` if ``x`` is infinite, ``False`` otherwise. + """ ... def isnan(x: float) -> bool: - """Vérifie si une valeur n'est pas un nombre (NaN). + """Check if a value is not-a-number (NaN). -Example: ``math.isnan(float('nan'))`` + Example: ``math.isnan(float('nan'))`` -:param x: Un nombre -:return: ``True`` if ``x`` is not-a-number (NaN), ``False`` otherwise.""" + :param x: A number + :return: ``True`` if ``x`` is not-a-number (NaN), ``False`` otherwise.""" ... def ldexp(x: float, exp: int) -> float: - """Calculer ``x * (2**exp)``. + """Calculate ``x * (2**exp)``. -Example: ``math.ldexp(0.5, 2)`` + Example: ``math.ldexp(0.5, 2)`` -:param x: Un nombre -:param exp: Exposant entier -:return: ``x * (2**exp)``""" + :param x: A number + :param exp: Integer exponent + :return: ``x * (2**exp)`` + """ ... -def log(x: float, base: float=e) -> float: - """Calculer le logarithme de ``x`` à la base donnée (logarithme naturel par défaut). +def log(x: float, base: float = e) -> float: + """Calculate the logarithm of ``x`` to the given base (defaults to natural logorithm). -Example: ``math.log(math.e)`` + Example: ``math.log(math.e)`` -With one argument, return the natural logarithm of x (to base e). + With one argument, return the natural logarithm of x (to base e). -With two arguments, return the logarithm of x to the given base, calculated as ``log(x)/log(base)``. + With two arguments, return the logarithm of x to the given base, calculated as ``log(x)/log(base)``. -:param x: Un nombre -:param base: La base à utiliser -:return: The natural logarithm of ``x``""" + :param x: A number + :param base: The base to use + :return: The natural logarithm of ``x`` + """ ... def modf(x: float) -> Tuple[float, float]: - """Calculer les parties fractionnelles et intégrales de ``x``. + """Calculate the fractional and integral parts of ``x``. -Example: ``fractional, integral = math.modf(1.5)`` + Example: ``fractional, integral = math.modf(1.5)`` -:param x: Un nombre -:return: A tuple of two floats representing the fractional then integral parts of ``x``. + :param x: A number + :return: A tuple of two floats representing the fractional then integral parts of ``x``. -Both the fractional and integral values have the same sign as ``x``.""" + Both the fractional and integral values have the same sign as ``x``. + """ ... def pow(x: float, y: float) -> float: - """Renvoie ``x`` à la puissance ``y``. + """Returns ``x`` to the power of ``y``. -Example: ``math.pow(4, 0.5)`` + Example: ``math.pow(4, 0.5)`` -:param x: Un nombre -:param y: L'exposant -:return: ``x`` to the power of ``y``""" + :param x: A number + :param y: The exponent + :return: ``x`` to the power of ``y`` + """ ... def radians(x: float) -> float: - """Convertir les degrés en radians. + """Convert a degrees to radians. -Example: ``math.radians(360)`` + Example: ``math.radians(360)`` -:param x: Une valeur en degrés -:return: The value converted to radians""" + :param x: A value in degrees + :return: The value converted to radians + """ ... def sin(x: float) -> float: - """Calculer le sinus de ``x``. + """Calculate the sine of ``x``. -Example: ``math.sin(math.pi/2)`` + Example: ``math.sin(math.pi/2)`` -:param x: Un nombre -:return: The sine of ``x``""" + :param x: A number + :return: The sine of ``x`` + """ ... def sqrt(x: float) -> float: - """Calculer la racine carrée de ``x``. + """Calculate the square root of ``x``. -Example: ``math.sqrt(4)`` + Example: ``math.sqrt(4)`` -:param x: Un nombre -:return: The square root of ``x``""" + :param x: A number + :return: The square root of ``x`` + """ ... def tan(x: float) -> float: - """Calculer la tangente de ``x``. + """Calculate the tangent of ``x``. -Example: ``math.tan(0)`` + Example: ``math.tan(0)`` -:param x: Un nombre -:return: The tangent of ``x``.""" + :param x: A number + :return: The tangent of ``x``. + """ ... def trunc(x: float) -> int: - """Arrondir un nombre vers 0. + """Round a number towards 0. -Example: ``math.trunc(-0.9)`` + Example: ``math.trunc(-0.9)`` -:param x: Un nombre -:return: ``x`` rounded towards zero.""" + :param x: A number + :return: ``x`` rounded towards zero. + """ ... + e: float -"""Base du logarithme naturel""" +"""Base of the natural logarithm""" + pi: float -"""Le ratio entre la circonférence d'un cercle et son diamètre""" \ No newline at end of file +"""The ratio of a circle's circumference to its diameter""" diff --git a/lang/fr/typeshed/stdlib/microbit/__init__.pyi b/lang/fr/typeshed/stdlib/microbit/__init__.pyi index 90bf6e6..f12158f 100644 --- a/lang/fr/typeshed/stdlib/microbit/__init__.pyi +++ b/lang/fr/typeshed/stdlib/microbit/__init__.pyi @@ -1,6 +1,11 @@ -"""Broches, images, sons, température et volume""" +"""Pins, images, sounds, temperature and volume. +""" + from typing import Any, Callable, List, Optional, Tuple, Union, overload + from _typeshed import ReadableBuffer + +# V2 only from . import accelerometer as accelerometer from . import audio as audio from . import compass as compass @@ -11,700 +16,831 @@ from . import speaker as speaker from . import spi as spi from . import uart as uart -def run_every(callback: Optional[Callable[[], None]]=None, days: int=0, h: int=0, min: int=0, s: int=0, ms: int=0) -> Callable[[Callable[[], None]], Callable[[], None]]: - """Planifie l'exécution d'une fonction à l'intervalle spécifié par les arguments temporels **V2 uniquement**. +def run_every( + callback: Optional[Callable[[], None]] = None, + days: int = 0, + h: int = 0, + min: int = 0, + s: int = 0, + ms: int = 0, +) -> Callable[[Callable[[], None]], Callable[[], None]]: + """Schedule to run a function at the interval specified by the time arguments **V2 only**. -Example: ``run_every(my_logging, min=5)`` + Example: ``run_every(my_logging, min=5)`` -``run_every`` can be used in two ways: + ``run_every`` can be used in two ways: -As a Decorator - placed on top of the function to schedule. For example:: + As a Decorator - placed on top of the function to schedule. For example:: - @run_every(h=1, min=20, s=30, ms=50) - def my_function(): - # Do something here + @run_every(h=1, min=20, s=30, ms=50) + def my_function(): + # Do something here -As a Function - passing the callback as a positional argument. For example:: + As a Function - passing the callback as a positional argument. For example:: - def my_function(): - # Do something here - run_every(my_function, s=30) + def my_function(): + # Do something here + run_every(my_function, s=30) -Each argument corresponds to a different time unit and they are additive. -So ``run_every(min=1, s=30)`` schedules the callback every minute and a half. + Each argument corresponds to a different time unit and they are additive. + So ``run_every(min=1, s=30)`` schedules the callback every minute and a half. -When an exception is thrown inside the callback function it deschedules the -function. To avoid this you can catch exceptions with ``try/except``. + When an exception is thrown inside the callback function it deschedules the + function. To avoid this you can catch exceptions with ``try/except``. -:param callback: Fonction à appeler à l'intervalle fourni. À omettre en cas d'utilisation comme décorateur. -:param days: Définit la marque du jour pour la programmation. -:param h: Définit la marque d'heure pour la programmation. -:param min: Définit la marque de minute pour la programmation. -:param s: Définit la marque de seconde pour la programmation. -:param ms: Définit la marque de milliseconde pour la programmation.""" + :param callback: Function to call at the provided interval. Omit when using as a decorator. + :param days: Sets the day mark for the scheduling. + :param h: Sets the hour mark for the scheduling. + :param min: Sets the minute mark for the scheduling. + :param s: Sets the second mark for the scheduling. + :param ms: Sets the millisecond mark for the scheduling. + """ def panic(n: int) -> None: - """Passer en mode panique. + """Enter a panic mode. -Example: ``panic(127)`` + Example: ``panic(127)`` -:param n: Un nombre entier arbitraire <= 255 pour indiquer un état. + :param n: An arbitrary integer <= 255 to indicate a status. -Requires restart.""" + Requires restart. + """ def reset() -> None: - """Redémarrer la carte.""" + """Restart the board.""" + @overload def scale(value: float, from_: Tuple[float, float], to: Tuple[int, int]) -> int: - """Convertit une valeur dans l'intervalle donné vers son équivalent dans un autre intervalle d'entiers. + """Converts a value from a range to an integer range. -Example: ``volume = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255))`` + Example: ``volume = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255))`` -For example, to convert an accelerometer X value to a speaker volume. + For example, to convert an accelerometer X value to a speaker volume. -If one of the numbers in the ``to`` parameter is a floating point -(i.e a decimal number like ``10.0``), this function will return a -floating point number. + If one of the numbers in the ``to`` parameter is a floating point + (i.e a decimal number like ``10.0``), this function will return a + floating point number. - temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0)) + temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0)) -:param value: Un nombre à convertir. -:param from_: Un tuple qui définit l'intervalle de départ. -:param to: Un tuple qui définit l'intervalle d'arrivée. -:return: The ``value`` converted to the ``to`` range.""" + :param value: A number to convert. + :param from_: A tuple to define the range to convert from. + :param to: A tuple to define the range to convert to. + :return: The ``value`` converted to the ``to`` range. + """ @overload def scale(value: float, from_: Tuple[float, float], to: Tuple[float, float]) -> float: - """Convertit une valeur dans l'intervalle donné vers son équivalent dans un autre intervalle de nombres à virgule flottante. + """Converts a value from a range to a floating point range. -Example: ``temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0))`` + Example: ``temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0))`` -For example, to convert temperature from a Celsius scale to Fahrenheit. + For example, to convert temperature from a Celsius scale to Fahrenheit. -If one of the numbers in the ``to`` parameter is a floating point -(i.e a decimal number like ``10.0``), this function will return a -floating point number. -If they are both integers (i.e ``10``), it will return an integer:: + If one of the numbers in the ``to`` parameter is a floating point + (i.e a decimal number like ``10.0``), this function will return a + floating point number. + If they are both integers (i.e ``10``), it will return an integer:: - returns_int = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255)) + returns_int = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255)) -:param value: Un nombre à convertir. -:param from_: Un tuple qui définit l'intervalle de départ. -:param to: Un tuple qui définit l'intervalle d'arrivée. -:return: The ``value`` converted to the ``to`` range.""" + :param value: A number to convert. + :param from_: A tuple to define the range to convert from. + :param to: A tuple to define the range to convert to. + :return: The ``value`` converted to the ``to`` range. + """ def sleep(n: float) -> None: - """Attendre ``n`` millisecondes. + """Wait for ``n`` milliseconds. -Example: ``sleep(1000)`` + Example: ``sleep(1000)`` -:param n: Le nombre de millisecondes à attendre + :param n: The number of milliseconds to wait -One second is 1000 milliseconds, so:: + One second is 1000 milliseconds, so:: - microbit.sleep(1000) + microbit.sleep(1000) -will pause the execution for one second.""" + will pause the execution for one second. + """ def running_time() -> int: - """Obtenir le temps de fonctionnement de la carte. + """Get the running time of the board. -:return: The number of milliseconds since the board was switched on or restarted.""" + :return: The number of milliseconds since the board was switched on or restarted. + """ def temperature() -> int: - """Obtenir la température du micro:bit en degrés Celsius.""" + """Get the temperature of the micro:bit in degrees Celsius.""" def set_volume(v: int) -> None: - """Définit le volume. + """Sets the volume. -Example: ``set_volume(127)`` + Example: ``set_volume(127)`` -:param v: Une valeur entre 0 (bas) et 255 (haut). + :param v: a value between 0 (low) and 255 (high). -Out of range values will be clamped to 0 or 255. + Out of range values will be clamped to 0 or 255. -**V2** only.""" + **V2** only. + """ ... class Button: - """La classe pour les boutons ``button_a`` et ``button_b``.""" + """The class for the buttons ``button_a`` and ``button_b``.""" def is_pressed(self) -> bool: - """Vérifier si le bouton est appuyé. + """Check if the button is pressed. -:return: ``True`` if the specified button ``button`` is pressed, and ``False`` otherwise.""" + :return: ``True`` if the specified button ``button`` is pressed, and ``False`` otherwise. + """ ... - def was_pressed(self) -> bool: - """Vérifie si le bouton a été pressé depuis que l'appareil a été démarré ou depuis la dernière fois où cette méthode a été appelée. + """Check if the button was pressed since the device started or the last time this method was called. -Calling this method will clear the press state so -that the button must be pressed again before this method will return -``True`` again. + Calling this method will clear the press state so + that the button must be pressed again before this method will return + ``True`` again. -:return: ``True`` if the specified button ``button`` was pressed, and ``False`` otherwise""" + :return: ``True`` if the specified button ``button`` was pressed, and ``False`` otherwise + """ ... - def get_presses(self) -> int: - """Obtenir le nombre total d'occurrences où le bouton a été appuyé, et réinitialise ce total avant de retourner. + """Get the running total of button presses, and resets this total + to zero before returning. -:return: The number of presses since the device started or the last time this method was called""" + :return: The number of presses since the device started or the last time this method was called + """ ... + button_a: Button -"""L'objet bouton ``Button`` gauche.""" +"""The left button ``Button`` object.""" + button_b: Button -"""L'objet bouton ``Button`` droit.""" +"""The right button ``Button`` object.""" class MicroBitDigitalPin: - """Une broche numérique. + """A digital pin. + + Some pins support analog and touch features using the ``MicroBitAnalogDigitalPin`` and ``MicroBitTouchPin`` subclasses. + """ -Some pins support analog and touch features using the ``MicroBitAnalogDigitalPin`` and ``MicroBitTouchPin`` subclasses.""" NO_PULL: int PULL_UP: int PULL_DOWN: int - def read_digital(self) -> int: - """Récupère la valeur numérique de la broche + """Get the digital value of the pin. -Example: ``value = pin0.read_digital()`` + Example: ``value = pin0.read_digital()`` -:return: 1 if the pin is high, and 0 if it's low.""" + :return: 1 if the pin is high, and 0 if it's low. + """ ... - def write_digital(self, value: int) -> None: - """Définit la valeur numérique de la broche + """Set the digital value of the pin. -Example: ``pin0.write_digital(1)`` + Example: ``pin0.write_digital(1)`` -:param value: 1 pour définir la broche à un niveau haut ou 0 pour définir la broche à un niveau bas""" + :param value: 1 to set the pin high or 0 to set the pin low""" ... - def set_pull(self, value: int) -> None: - """Définissez l'état de tirage sur l'une des trois valeurs possibles\xa0: ``PULL_UP``, ``PULL_DOWN`` ou ``NO_PULL``. + """Set the pull state to one of three possible values: ``PULL_UP``, ``PULL_DOWN`` or ``NO_PULL``. -Example: ``pin0.set_pull(pin0.PULL_UP)`` + Example: ``pin0.set_pull(pin0.PULL_UP)`` -:param value: L'état de tirage sur la broche correspondante, par exemple ``pin0.PULL_UP``.""" + :param value: The pull state from the relevant pin, e.g. ``pin0.PULL_UP``. + """ ... - def get_pull(self) -> int: - """Obtenir l'état de tirage sur une broche. + """Get the pull state on a pin. -Example: ``pin0.get_pull()`` + Example: ``pin0.get_pull()`` -:return: ``NO_PULL``, ``PULL_DOWN``, or ``PULL_UP`` + :return: ``NO_PULL``, ``PULL_DOWN``, or ``PULL_UP`` -These are set using the ``set_pull()`` method or automatically configured -when a pin mode requires it.""" + These are set using the ``set_pull()`` method or automatically configured + when a pin mode requires it. + """ ... - def get_mode(self) -> str: - """Renvoie le mode de la broche + """Returns the pin mode. -Example: ``pin0.get_mode()`` + Example: ``pin0.get_mode()`` -When a pin is used for a specific function, like -writing a digital value, or reading an analog value, the pin mode -changes. + When a pin is used for a specific function, like + writing a digital value, or reading an analog value, the pin mode + changes. -:return: ``"unused"``, ``"analog"``, ``"read_digital"``, ``"write_digital"``, ``"display"``, ``"button"``, ``"music"``, ``"audio"``, ``"touch"``, ``"i2c"``, or ``"spi"``""" + :return: ``"unused"``, ``"analog"``, ``"read_digital"``, ``"write_digital"``, ``"display"``, ``"button"``, ``"music"``, ``"audio"``, ``"touch"``, ``"i2c"``, or ``"spi"`` + """ ... - def write_analog(self, value: int) -> None: - """Sortie d'un signal PWM sur la broche, avec un rapport cyclique proportionnel à ``value``. - -Example: ``pin0.write_analog(254)`` + """Output a PWM signal on the pin, with the duty cycle proportional to ``value``. -:param value: Un entier ou un nombre à virgule flottante entre 0 (rapport cyclique à 0%) et 1023 (rapport cyclique à 100%).""" + Example: ``pin0.write_analog(254)`` + :param value: An integer or a floating point number between 0 (0% duty cycle) and 1023 (100% duty). + """ def set_analog_period(self, period: int) -> None: - """Définit la période de sortie du signal PWM à ``period`` en millisecondes. + """Set the period of the PWM signal being output to ``period`` in milliseconds. -Example: ``pin0.set_analog_period(10)`` - -:param period: La période en millisecondes avec une valeur minimale valide de 1 ms.""" + Example: ``pin0.set_analog_period(10)`` + :param period: The period in milliseconds with a minimum valid value of 1ms. + """ def set_analog_period_microseconds(self, period: int) -> None: - """Définit la période de sortie du signal PWM à ``period`` en millisecondes. + """Set the period of the PWM signal being output to ``period`` in microseconds. -Example: ``pin0.set_analog_period_microseconds(512)`` + Example: ``pin0.set_analog_period_microseconds(512)`` -:param period: La période en microsecondes avec une valeur minimale valide de 256µs.""" + :param period: The period in microseconds with a minimum valid value of 256µs. + """ class MicroBitAnalogDigitalPin(MicroBitDigitalPin): - """Une broche avec des fonctions analogiques et numériques.""" + """A pin with analog and digital features.""" def read_analog(self) -> int: - """Lit la tension appliquée à la broche. + """Read the voltage applied to the pin. -Example: ``pin0.read_analog()`` + Example: ``pin0.read_analog()`` -:return: An integer between 0 (meaning 0V) and 1023 (meaning 3.3V).""" + :return: An integer between 0 (meaning 0V) and 1023 (meaning 3.3V). + """ class MicroBitTouchPin(MicroBitAnalogDigitalPin): - """Une broche avec des fonctions analogiques, numériques et tactiles.""" + """A pin with analog, digital and touch features.""" + CAPACITIVE: int RESISTIVE: int - def is_touched(self) -> bool: - """Vérifie si la broche est touchée. + """Check if the pin is being touched. -Example: ``pin0.is_touched()`` + Example: ``pin0.is_touched()`` -The default touch mode for the pins on the edge connector is ``resistive``. -The default for the logo pin **V2** is ``capacitive``. + The default touch mode for the pins on the edge connector is ``resistive``. + The default for the logo pin **V2** is ``capacitive``. -**Resistive touch** -This test is done by measuring how much resistance there is between the -pin and ground. A low resistance gives a reading of ``True``. To get -a reliable reading using a finger you may need to touch the ground pin -with another part of your body, for example your other hand. + **Resistive touch** + This test is done by measuring how much resistance there is between the + pin and ground. A low resistance gives a reading of ``True``. To get + a reliable reading using a finger you may need to touch the ground pin + with another part of your body, for example your other hand. -**Capacitive touch** -This test is done by interacting with the electric field of a capacitor -using a finger as a conductor. `Capacitive touch -`_ -does not require you to make a ground connection as part of a circuit. + **Capacitive touch** + This test is done by interacting with the electric field of a capacitor + using a finger as a conductor. `Capacitive touch + `_ + does not require you to make a ground connection as part of a circuit. -:return: ``True`` if the pin is being touched with a finger, otherwise return ``False``.""" + :return: ``True`` if the pin is being touched with a finger, otherwise return ``False``. + """ ... - def set_touch_mode(self, value: int) -> None: - """Définit le mode tactile pour la broche. + """Set the touch mode for the pin. -Example: ``pin0.set_touch_mode(pin0.CAPACITIVE)`` + Example: ``pin0.set_touch_mode(pin0.CAPACITIVE)`` -The default touch mode for the pins on the edge connector is -``resistive``. The default for the logo pin **V2** is ``capacitive``. + The default touch mode for the pins on the edge connector is + ``resistive``. The default for the logo pin **V2** is ``capacitive``. -:param value: ``CAPACITIVE`` ou ``RESISTIVE`` pour la broche correspondante.""" + :param value: ``CAPACITIVE`` or ``RESISTIVE`` from the relevant pin. + """ ... + pin0: MicroBitTouchPin -"""Broche avec des fonctionnalités numériques, analogiques, et tactiles.""" +"""Pin with digital, analog and touch features.""" + pin1: MicroBitTouchPin -"""Broche avec des fonctionnalités numériques, analogiques, et tactiles.""" +"""Pin with digital, analog and touch features.""" + pin2: MicroBitTouchPin -"""Broche avec des fonctionnalités numériques, analogiques, et tactiles.""" +"""Pin with digital, analog and touch features.""" + pin3: MicroBitAnalogDigitalPin -"""Broche avec des fonctionnalités numériques et analogiques.""" +"""Pin with digital and analog features.""" + pin4: MicroBitAnalogDigitalPin -"""Broche avec des fonctionnalités numériques et analogiques.""" +"""Pin with digital and analog features.""" + pin5: MicroBitDigitalPin -"""Broche avec des fonctionnalités numériques""" +"""Pin with digital features.""" + pin6: MicroBitDigitalPin -"""Broche avec des fonctionnalités numériques""" +"""Pin with digital features.""" + pin7: MicroBitDigitalPin -"""Broche avec des fonctionnalités numériques""" +"""Pin with digital features.""" + pin8: MicroBitDigitalPin -"""Broche avec des fonctionnalités numériques""" +"""Pin with digital features.""" + pin9: MicroBitDigitalPin -"""Broche avec des fonctionnalités numériques""" +"""Pin with digital features.""" + pin10: MicroBitAnalogDigitalPin -"""Broche avec des fonctionnalités numériques et analogiques.""" +"""Pin with digital and analog features.""" + pin11: MicroBitDigitalPin -"""Broche avec des fonctionnalités numériques""" +"""Pin with digital features.""" + pin12: MicroBitDigitalPin -"""Broche avec des fonctionnalités numériques""" +"""Pin with digital features.""" + pin13: MicroBitDigitalPin -"""Broche avec des fonctionnalités numériques""" +"""Pin with digital features.""" + pin14: MicroBitDigitalPin -"""Broche avec des fonctionnalités numériques""" +"""Pin with digital features.""" + pin15: MicroBitDigitalPin -"""Broche avec des fonctionnalités numériques""" +"""Pin with digital features.""" + pin16: MicroBitDigitalPin -"""Broche avec des fonctionnalités numériques""" +"""Pin with digital features.""" + pin19: MicroBitDigitalPin -"""Broche avec des fonctionnalités numériques""" +"""Pin with digital features.""" + pin20: MicroBitDigitalPin -"""Broche avec des fonctionnalités numériques""" +"""Pin with digital features.""" + pin_logo: MicroBitTouchPin -"""Une broche logo sensible au toucher sur l'avant du micro:bit, qui est définie par défaut en mode tactile capacitif.""" +"""A touch sensitive logo pin on the front of the micro:bit, which by default is set to capacitive touch mode.""" + pin_speaker: MicroBitAnalogDigitalPin -"""Une broche pour adresser le haut-parleur micro:bit. +"""A pin to address the micro:bit speaker. This API is intended only for use in Pulse-Width Modulation pin operations e.g. pin_speaker.write_analog(128). """ class Image: - """Une image à afficher sur l'écran LED du micro:bit. + """An image to show on the micro:bit LED display. -Given an image object it's possible to display it via the ``display`` API:: + Given an image object it's possible to display it via the ``display`` API:: + + display.show(Image.HAPPY) + """ - display.show(Image.HAPPY)""" HEART: Image - """Image d'un cœur.""" + """Heart image.""" + HEART_SMALL: Image - """Petite image d'un cœur""" + """Small heart image.""" + HAPPY: Image - """Image de visage heureux.""" + """Happy face image.""" + SMILE: Image - """Image de visage souriant.""" + """Smiling mouth image.""" + SAD: Image - """Image de visage triste.""" + """Sad face image.""" + CONFUSED: Image - """Image d'un visage perplexe.""" + """Confused face image.""" + ANGRY: Image - """Image de visage en colère.""" + """Angry face image.""" + ASLEEP: Image - """Image de visage endormi""" + """Sleeping face image.""" + SURPRISED: Image - """Image de visage surpris.""" + """Surprised face image.""" + SILLY: Image - """Image de visage absurde.""" + """Silly face image.""" + FABULOUS: Image - """Image de visage avec lunettes de soleil.""" + """Sunglasses face image.""" + MEH: Image - """Image de visage pas impressionné""" + """Unimpressed face image.""" + YES: Image - """Image d'une coche.""" + """Tick image.""" + NO: Image - """Image d'une croix.""" + """Cross image.""" + CLOCK12: Image - """Image avec une ligne indiquant vers 12 heures.""" + """Image with line pointing to 12 o'clock.""" + CLOCK11: Image - """Image avec une ligne indiquant vers 11 heures.""" + """Image with line pointing to 11 o'clock.""" + CLOCK10: Image - """Image avec une ligne indiquant vers 10 heures.""" + """Image with line pointing to 10 o'clock.""" + CLOCK9: Image - """Image avec une ligne indiquant vers 9 heures.""" + """Image with line pointing to 9 o'clock.""" + CLOCK8: Image - """Image avec une ligne indiquant vers 8 heures.""" + """Image with line pointing to 8 o'clock.""" + CLOCK7: Image - """Image avec une ligne indiquant vers 7 heures.""" + """Image with line pointing to 7 o'clock.""" + CLOCK6: Image - """Image avec une ligne indiquant vers 6 heures.""" + """Image with line pointing to 6 o'clock.""" + CLOCK5: Image - """Image avec une ligne indiquant vers 5 heures.""" + """Image with line pointing to 5 o'clock.""" + CLOCK4: Image - """Image avec une ligne indiquant vers 4 heures.""" + """Image with line pointing to 4 o'clock.""" + CLOCK3: Image - """Image avec une ligne indiquant vers 3 heures.""" + """Image with line pointing to 3 o'clock.""" + CLOCK2: Image - """Image avec une ligne indiquant vers 2 heures.""" + """Image with line pointing to 2 o'clock.""" + CLOCK1: Image - """Image avec une ligne indiquant vers 1 heure.""" + """Image with line pointing to 1 o'clock.""" + ARROW_N: Image - """Image de flèche pointant vers le nord.""" + """Image of arrow pointing north.""" + ARROW_NE: Image - """Image de flèche pointant vers le nord est.""" + """Image of arrow pointing north east.""" + ARROW_E: Image - """Image de flèche pointant vers l'est.""" + """Image of arrow pointing east.""" + ARROW_SE: Image - """Image de flèche pointant vers le sud-est.""" + """Image of arrow pointing south east.""" + ARROW_S: Image - """Image de flèche pointant vers le sud.""" + """Image of arrow pointing south.""" + ARROW_SW: Image - """Image de flèche pointant vers le sud-ouest.""" + """Image of arrow pointing south west.""" + ARROW_W: Image - """Image de flèche pointant vers l'ouest.""" + """Image of arrow pointing west.""" + ARROW_NW: Image - """Image de flèche pointant vers le nord ouest.""" + """Image of arrow pointing north west.""" + TRIANGLE: Image - """Image d'un triangle pointant vers le haut.""" + """Image of a triangle pointing up.""" + TRIANGLE_LEFT: Image - """Image d'un triangle dans le coin gauche.""" + """Image of a triangle in the left corner.""" + CHESSBOARD: Image - """Éclairage alternatif des LEDs dans un motif d'échiquier.""" + """Alternate LEDs lit in a chessboard pattern.""" + DIAMOND: Image - """Image de diamant.""" + """Diamond image.""" + DIAMOND_SMALL: Image - """Petite image de diamant.""" + """Small diamond image.""" + SQUARE: Image - """Image de carré.""" + """Square image.""" + SQUARE_SMALL: Image - """Petite image de carré.""" + """Small square image.""" + RABBIT: Image - """Image de lapin.""" + """Rabbit image.""" + COW: Image - """Image de vache.""" + """Cow image.""" + MUSIC_CROTCHET: Image - """Image d'une note.""" + """Crotchet note image.""" + MUSIC_QUAVER: Image - """Image d'une croche.""" + """Quaver note image.""" + MUSIC_QUAVERS: Image - """Image d'une paire de croche.""" + """Pair of quavers note image.""" + PITCHFORK: Image - """Image d'une fourche.""" + """Pitchfork image.""" + XMAS: Image - """Image d'un arbre de Noël.""" + """Christmas tree image.""" + PACMAN: Image - """Image du personnage d'arcade Pac-Man.""" + """Pac-Man arcade character image.""" + TARGET: Image - """Image d'une cible.""" + """Target image.""" + TSHIRT: Image - """Image de t-shirt.""" + """T-shirt image.""" + ROLLERSKATE: Image - """Image de patin à roulette.""" + """Rollerskate image.""" + DUCK: Image - """Image de canard.""" + """Duck image.""" + HOUSE: Image - """Image d'une maison.""" + """House image.""" + TORTOISE: Image - """Image d'une tortue.""" + """Tortoise image.""" + BUTTERFLY: Image - """Image d'un papillon.""" + """Butterfly image.""" + STICKFIGURE: Image - """Image d'un personnage.""" + """Stick figure image.""" + GHOST: Image - """Image de fantôme.""" + """Ghost image.""" + SWORD: Image - """Image d'une épée.""" + """Sword image.""" + GIRAFFE: Image - """Image d'une girafe.""" + """Giraffe image.""" + SKULL: Image - """Image d'un crâne.""" + """Skull image.""" + UMBRELLA: Image - """Image d'un parapluie.""" + """Umbrella image.""" + SNAKE: Image - """Image de serpent.""" + """Snake image.""" + SCISSORS: Image - """Image de ciseaux.""" + """Scissors image.""" + ALL_CLOCKS: List[Image] - """Une liste contenant toutes les images CLOCK_ en séquence.""" - ALL_ARROWS: List[Image] - """Une liste contenant toutes les images ARROW_ en séquence.""" + """A list containing all the CLOCK_ images in sequence.""" + ALL_ARROWS: List[Image] + """A list containing all the ARROW_ images in sequence.""" @overload def __init__(self, string: str) -> None: - """Créer une image à partir d'une chaîne de caractères décrivant quelles LED sont allumées. + """Create an image from a string describing which LEDs are lit. -``string`` has to consist of digits 0-9 arranged into lines, -describing the image, for example:: + ``string`` has to consist of digits 0-9 arranged into lines, + describing the image, for example:: - image = Image("90009:" - "09090:" - "00900:" - "09090:" - "90009") + 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 newlines (\\n) insead of the colons. + 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 newlines (\\n) insead of the colons. -:param string: La chaîne de caractères décrivant l'image.""" + :param string: The string describing the image. + """ ... - @overload - def __init__(self, width: int=5, height: int=5, buffer: ReadableBuffer=None) -> None: - """Créer une image vide avec ``width`` colonnes et ``height`` lignes. + def __init__( + self, width: int = 5, height: int = 5, buffer: ReadableBuffer = None + ) -> None: + """Create an empty image with ``width`` columns and ``height`` rows. -:param width: Largeur optionnelle de l'image -:param height: Hauteur optionnelle de l'image -:param buffer: Tableau optionnel ou octets de ``width``×``height`` entiers dans la plage 0-9 pour initialiser l'image + :param width: Optional width of the image + :param height: Optional height of the image + :param buffer: Optional array or bytes of ``width``×``height`` integers in range 0-9 to initialize the image -Examples:: + Examples:: - Image(2, 2, b'\x08\x08\x08\x08') - Image(2, 2, bytearray([9,9,9,9])) + Image(2, 2, b'\x08\x08\x08\x08') + Image(2, 2, bytearray([9,9,9,9])) -These create 2 x 2 pixel images at full brightness.""" + These create 2 x 2 pixel images at full brightness. + """ ... - def width(self) -> int: - """Récupère le nombre de colonnes. + """Get the number of columns. -:return: The number of columns in the image""" + :return: The number of columns in the image + """ ... - def height(self) -> int: - """Récupère le nombre de lignes. + """Get the number of rows. -:return: The number of rows in the image""" + :return: The number of rows in the image + """ ... - def set_pixel(self, x: int, y: int, value: int) -> None: - """Définit la luminosité d'un pixel. + """Set the brightness of a pixel. -Example: ``my_image.set_pixel(0, 0, 9)`` + Example: ``my_image.set_pixel(0, 0, 9)`` -:param x: Le numéro de colonne -:param y: Le numéro de ligne -:param value: La luminosité sous la forme d'un entier compris entre 0 (sombre) et 9 (lumineux) + :param x: The column number + :param y: The row number + :param value: The brightness as an integer 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``.""" + 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: - """Récupère la luminosité d'un pixel. + """Get the brightness of a pixel. -Example: ``my_image.get_pixel(0, 0)`` + Example: ``my_image.get_pixel(0, 0)`` -:param x: Le numéro de colonne -:param y: Le numéro de ligne -:return: The brightness as an integer between 0 and 9.""" + :param x: The column number + :param y: The row number + :return: The brightness as an integer between 0 and 9. + """ ... - def shift_left(self, n: int) -> Image: - """Créer une nouvelle image en déplaçant l'image à gauche. + """Create a new image by shifting the picture left. -Example: ``Image.HEART_SMALL.shift_left(1)`` + Example: ``Image.HEART_SMALL.shift_left(1)`` -:param n: Le nombre de colonnes par lequel déplacer -:return: The shifted image""" + :param n: The number of columns to shift by + :return: The shifted image + """ ... - def shift_right(self, n: int) -> Image: - """Créer une nouvelle image en déplaçant l'image à droite. + """Create a new image by shifting the picture right. -Example: ``Image.HEART_SMALL.shift_right(1)`` + Example: ``Image.HEART_SMALL.shift_right(1)`` -:param n: Le nombre de colonnes par lequel déplacer -:return: The shifted image""" + :param n: The number of columns to shift by + :return: The shifted image + """ ... - def shift_up(self, n: int) -> Image: - """Créer une nouvelle image en déplaçant l'image vers le haut. + """Create a new image by shifting the picture up. -Example: ``Image.HEART_SMALL.shift_up(1)`` + Example: ``Image.HEART_SMALL.shift_up(1)`` -:param n: Le nombre de lignes par lequel déplacer -:return: The shifted image""" + :param n: The number of rows to shift by + :return: The shifted image + """ ... - def shift_down(self, n: int) -> Image: - """Créer une nouvelle image en déplaçant l'image vers le bas. + """Create a new image by shifting the picture down. -Example: ``Image.HEART_SMALL.shift_down(1)`` + Example: ``Image.HEART_SMALL.shift_down(1)`` -:param n: Le nombre de lignes par lequel déplacer -:return: The shifted image""" + :param n: The number of rows to shift by + :return: The shifted image + """ ... - def crop(self, x: int, y: int, w: int, h: int) -> Image: - """Créer une nouvelle image en recadrant l'image. + """Create a new image by cropping the picture. -Example: ``Image.HEART.crop(1, 1, 3, 3)`` + Example: ``Image.HEART.crop(1, 1, 3, 3)`` -:param x: Le nombre de colonnes duquel décaler le recadrage -:param y: Le nombre de lignes duquel décaler le recadrage -:param w: La largeur du recadrage -:param h: La hauteur du recadrage -:return: The new image""" + :param x: The crop offset column + :param y: The crop offset row + :param w: The crop width + :param h: The crop height + :return: The new image + """ ... - def copy(self) -> Image: - """Créer une copie exacte de l'image. + """Create an exact copy of the image. -Example: ``Image.HEART.copy()`` + Example: ``Image.HEART.copy()`` -:return: The new image""" + :return: The new image + """ ... - def invert(self) -> Image: - """Créer une nouvelle image en inversant la luminosité des pixels de l'image source. + """Create a new image by inverting the brightness of the pixels in the + source image. -Example: ``Image.SMALL_HEART.invert()`` + Example: ``Image.SMALL_HEART.invert()`` -:return: The new image.""" + :return: The new image. + """ ... - def fill(self, value: int) -> None: - """Définit la luminosité de tous les pixels de l'image. + """Set the brightness of all the pixels in the image. -Example: ``my_image.fill(5)`` + Example: ``my_image.fill(5)`` -:param value: La nouvelle luminosité sous la forme d'un nombre compris entre 0 (sombre) et 9 (lumineux). + :param value: The new brightness as a number 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``.""" + 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: - """Copier la zone d'une autre image vers cette image. - -Example: ``my_image.blit(Image.HEART, 1, 1, 3, 3, 1, 1)`` - -:param src: L'image source -:param x: Le décalage de la colonne de départ dans l'image source -:param y: Décalage de la ligne de départ dans l'image source -:param w: Le nombre de colonnes à copier -:param h: Le nombre de lignes à copier -:param xdest: Le décalage de la colonne à modifier dans cette image -:param ydest: Le décalage de la ligne à modifier dans cette image - -Pixels outside the source image are treated as having a brightness 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 blit( + self, + src: Image, + x: int, + y: int, + w: int, + h: int, + xdest: int = 0, + ydest: int = 0, + ) -> None: + """Copy an area from another image into this image. + + Example: ``my_image.blit(Image.HEART, 1, 1, 3, 3, 1, 1)`` + + :param src: The source image + :param x: The starting column offset in the source image + :param y: The starting row offset in the source image + :param w: The number of columns to copy + :param h: The number of rows to copy + :param xdest: The column offset to modify in this image + :param ydest: The row offset to modify in this image + + Pixels outside the source image are treated as having a brightness 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: - """Récupère une représentation de l'image sous forme de texte compact.""" + """Get a compact string representation of the image.""" ... - def __str__(self) -> str: - """Récupère une chaîne de caractères lisible de l'image.""" + """Get a readable string representation of the image.""" ... - def __add__(self, other: Image) -> Image: - """Crée une nouvelle image en additionnant les valeurs de luminosité des deux images -pour chaque pixel. + """Create a new image by adding the brightness values from the two + images for each pixel. -Example: ``Image.HEART + Image.HAPPY`` + Example: ``Image.HEART + Image.HAPPY`` -:param other: L'image à ajouter.""" + :param other: The image to add. + """ ... - def __sub__(self, other: Image) -> Image: - """Crée une nouvelle image en soustrayant de cette image les valeurs de luminosité de -l'autre image. + """Create a new image by subtracting the brightness values of the + other image from this image. -Example: ``Image.HEART - Image.HEART_SMALL`` + Example: ``Image.HEART - Image.HEART_SMALL`` -:param other: L'image à soustraire.""" + :param other: The image to subtract. + """ ... - def __mul__(self, n: float) -> Image: - """Crée une nouvelle image en multipliant la luminosité de chaque pixel par -``n``. + """Create a new image by multiplying the brightness of each pixel by + ``n``. -Example: ``Image.HEART * 0.5`` + Example: ``Image.HEART * 0.5`` -:param n: La valeur par laquelle multiplier.""" + :param n: The value to multiply by. + """ ... - def __truediv__(self, n: float) -> Image: - """Crée une nouvelle image en divisant la luminosité de chaque pixel par -``n``. + """Create a new image by dividing the brightness of each pixel by + ``n``. -Example: ``Image.HEART / 2`` + Example: ``Image.HEART / 2`` -:param n: La valeur par laquelle diviser.""" + :param n: The value to divide by. + """ ... class SoundEvent: LOUD: SoundEvent - """Représente la transition d'événements sonores, de ``quiet`` à ``loud`` comme un clap dans les mains ou un cri.""" + """Represents the transition of sound events, from ``quiet`` to ``loud`` like clapping or shouting.""" + QUIET: SoundEvent - """Représente la transition d'événements sonores de ``loud`` à ``quiet`` comme parler ou écouter de la musique de fond.""" + """Represents the transition of sound events, from ``loud`` to ``quiet`` like speaking or background music.""" class Sound: - """Les sons intégrés peuvent être appelés en utilisant ``audio.play(Sound.NAME)``.""" + """The built-in sounds can be called using ``audio.play(Sound.NAME)``.""" + GIGGLE: Sound - """Bruit de gloussement.""" + """Giggling sound.""" + HAPPY: Sound - """Son joyeux.""" + """Happy sound.""" + HELLO: Sound - """Son de salutation.""" + """Greeting sound.""" + MYSTERIOUS: Sound - """Son mystérieux.""" + """Mysterious sound.""" + SAD: Sound - """Son triste.""" + """Sad sound.""" + SLIDE: Sound - """Bruit de glissade.""" + """Sliding sound.""" + SOARING: Sound - """Bruit d'envolée.""" + """Soaring sound.""" + SPRING: Sound - """Son d'un ressort.""" + """Spring sound.""" + TWINKLE: Sound - """Son de scintillement.""" + """Twinkling sound.""" + YAWN: Sound - """Son de bâillement.""" \ No newline at end of file + """Yawning sound.""" diff --git a/lang/fr/typeshed/stdlib/microbit/accelerometer.pyi b/lang/fr/typeshed/stdlib/microbit/accelerometer.pyi index f9f069b..bac82c0 100644 --- a/lang/fr/typeshed/stdlib/microbit/accelerometer.pyi +++ b/lang/fr/typeshed/stdlib/microbit/accelerometer.pyi @@ -1,103 +1,115 @@ -"""Mesurer l'accélération du micro:bit et reconnaitre des mouvements.""" +"""Measure the acceleration of the micro:bit and recognise gestures. +""" + from typing import Tuple def get_x() -> int: - """Récupérer la mesure de l'accélération dans l'axe ``x`` en milli-g. + """Get the acceleration measurement in the ``x`` axis in milli-g. -Example: ``accelerometer.get_x()`` + Example: ``accelerometer.get_x()`` -:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" + :return: A positive or negative integer depending on direction in the range +/- 2000mg. + """ ... def get_y() -> int: - """Récupérer la mesure de l'accélération dans l'axe ``y`` en milli-g. + """Get the acceleration measurement in the ``y`` axis in milli-g. -Example: ``accelerometer.get_y()`` + Example: ``accelerometer.get_y()`` -:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" + :return: A positive or negative integer depending on direction in the range +/- 2000mg. + """ ... def get_z() -> int: - """Récupérer la mesure de l'accélération dans l'axe ``z`` en milli-g. + """Get the acceleration measurement in the ``z`` axis in milli-g. -Example: ``accelerometer.get_z()`` + Example: ``accelerometer.get_z()`` -:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" + :return: A positive or negative integer depending on direction in the range +/- 2000mg. + """ ... def get_values() -> Tuple[int, int, int]: - """Récupérer en une fois les mesures d'accélération dans tous les axes sous forme d'un tuple. + """Get the acceleration measurements in all axes at once as a tuple. -Example: ``x, y, z = accelerometer.get_values()`` + Example: ``x, y, z = accelerometer.get_values()`` -:return: a three-element tuple of integers ordered as X, Y, Z, each value a positive or negative integer depending on direction in the range +/- 2000mg""" + :return: a three-element tuple of integers ordered as X, Y, Z, each value a positive or negative integer depending on direction in the range +/- 2000mg + """ ... def get_strength() -> int: - """Obtenir la mesure de l'accélération de tous les axes combinés, sous la forme d'un nombre entier positif. C'est la somme pythagoricienne des axes X, Y et Z. + """Get the acceleration measurement of all axes combined, as a positive integer. This is the Pythagorean sum of the X, Y and Z axes. -Example: ``accelerometer.get_strength()`` + Example: ``accelerometer.get_strength()`` -:return: The combined acceleration strength of all the axes, in milli-g.""" + :return: The combined acceleration strength of all the axes, in milli-g. + """ ... def current_gesture() -> str: - """Récupérer le nom du geste actuel. + """Get the name of the current gesture. -Example: ``accelerometer.current_gesture()`` + Example: ``accelerometer.current_gesture()`` -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. + 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. -:return: The current gesture""" + :return: The current gesture + """ ... def is_gesture(name: str) -> bool: - """Vérifier si le geste nommé est actif en ce moment. + """Check if the named gesture is currently active. -Example: ``accelerometer.is_gesture('shake')`` + Example: ``accelerometer.is_gesture('shake')`` -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. + 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. -:param name: Le nom du geste. -:return: ``True`` if the gesture is active, ``False`` otherwise.""" + :param name: The gesture name. + :return: ``True`` if the gesture is active, ``False`` otherwise. + """ ... def was_gesture(name: str) -> bool: - """Vérifier si le geste nommé a été actif depuis le dernier appel. + """Check if the named gesture was active since the last call. -Example: ``accelerometer.was_gesture('shake')`` + Example: ``accelerometer.was_gesture('shake')`` -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. + 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. -:param name: Le nom du geste. -:return: ``True`` if the gesture was active since the last call, ``False`` otherwise.""" + :param name: The gesture name. + :return: ``True`` if the gesture was active since the last call, ``False`` otherwise. + """ def get_gestures() -> Tuple[str, ...]: - """Renvoyer un tuple de l'historique des gestes. + """Return a tuple of the gesture history. -Example: ``accelerometer.get_gestures()`` + Example: ``accelerometer.get_gestures()`` -Clears the gesture history before returning. + Clears the gesture history before returning. -Gestures are not updated in the background so there needs to be constant -calls to some accelerometer method to do the gesture detection. Usually -gestures can be detected using a loop with a small :func:`microbit.sleep` delay. + Gestures are not updated in the background so there needs to be constant + calls to some accelerometer method to do the gesture detection. Usually + gestures can be detected using a loop with a small :func:`microbit.sleep` delay. -:return: The history as a tuple, most recent last.""" + :return: The history as a tuple, most recent last. + """ ... def set_range(value: int) -> None: - """Définir la plage de sensibilité de l'accéléromètre, en g (gravité standard), à la valeur la plus proche supportée par le matériel, l'arrondi se fait soit à ``2``, ``4``, ou ``8`` g. + """Set the accelerometer sensitivity range, in g (standard gravity), to the closest values supported by the hardware, so it rounds to either ``2``, ``4``, or ``8`` g. -Example: ``accelerometer.set_range(8)`` + Example: ``accelerometer.set_range(8)`` -:param value: Nouvelle plage pour l'accéléromètre, un entier en ``g``.""" \ No newline at end of file + :param value: New range for the accelerometer, an integer in ``g``. + """ diff --git a/lang/fr/typeshed/stdlib/microbit/audio.pyi b/lang/fr/typeshed/stdlib/microbit/audio.pyi index 4c814a3..3b1e327 100644 --- a/lang/fr/typeshed/stdlib/microbit/audio.pyi +++ b/lang/fr/typeshed/stdlib/microbit/audio.pyi @@ -1,124 +1,160 @@ -"""Jouer des sons en utilisant le micro:bit (importer ``audio`` pour compatibilité V1).""" +"""Play sounds using the micro:bit (import ``audio`` for V1 compatibility). +""" + from ..microbit import MicroBitDigitalPin, Sound, pin0 from typing import ClassVar, Iterable, Union -def play(source: Union[Iterable[AudioFrame], Sound, SoundEffect], wait: bool=True, pin: MicroBitDigitalPin=pin0, return_pin: Union[MicroBitDigitalPin, None]=None) -> None: - """Jouer un son intégré, un effet sonore ou des frames audio personnalisées. +def play( + source: Union[Iterable[AudioFrame], Sound, SoundEffect], + wait: bool = True, + pin: MicroBitDigitalPin = pin0, + return_pin: Union[MicroBitDigitalPin, None] = None, +) -> None: + """Play a built-in sound, sound effect or custom audio frames. -Example: ``audio.play(Sound.GIGGLE)`` + Example: ``audio.play(Sound.GIGGLE)`` -:param source: Un ``Sound`` intégré tel que ``Sound.GIGGLE``, un ``SoundEffect`` ou un échantillon de données sous la forme d'un itérable d'objets ``AudioFrame``. -:param wait: Si ``wait`` est ``True``, cette fonction bloquera jusqu'à ce que le son soit terminé. -:param pin: (broche) Un argument optionnel pour spécifier la broche de sortie, peut être utilisé pour remplacer la valeur par défaut ``pin0``. Si nous ne voulons pas que le son soit joué, il est possible d'utiliser ``pin=None``. -:param return_pin: Spécifie une broche de connecteur de bord différentiel à connecter à un haut-parleur externe au lieu de la masse. Ceci est ignoré dans la révision **V2**.""" + :param source: A built-in ``Sound`` such as ``Sound.GIGGLE``, a ``SoundEffect`` or sample data as an iterable of ``AudioFrame`` objects. + :param wait: If ``wait`` is ``True``, this function will block until the sound is complete. + :param pin: An optional argument to specify the output pin can be used to override the default of ``pin0``. If we do not want any sound to play we can use ``pin=None``. + :param return_pin: Specifies a differential edge connector pin to connect to an external speaker instead of ground. This is ignored for the **V2** revision. + """ def is_playing() -> bool: - """Vérifier si un son est en train d'être joué. + """Check whether a sound is playing. -Example: ``audio.is_playing()`` + Example: ``audio.is_playing()`` -:return: ``True`` if audio is playing, otherwise ``False``.""" + :return: ``True`` if audio is playing, otherwise ``False``.""" ... def stop() -> None: - """Arrêter toute lecture audio. + """Stop all audio playback. -Example: ``audio.stop()``""" + Example: ``audio.stop()`` + """ ... class SoundEffect: - """Un effet sonore, composé d'un ensemble de paramètres configurés via le constructeur ou les attributs.""" + """A sound effect, composed by a set of parameters configured via the constructor or attributes.""" + WAVEFORM_SINE: ClassVar[int] - """Option d'onde sinusoïdale utilisée pour le paramètre ``waveform``.""" + """Sine wave option used for the ``waveform`` parameter.""" + WAVEFORM_SAWTOOTH: ClassVar[int] - """Optionde forme d'onde en dent de scie utilisée pour le paramètre ``waveform``.""" + """Sawtooth wave option used for the ``waveform`` parameter.""" + WAVEFORM_TRIANGLE: ClassVar[int] - """Option d'onde triangulaire utilisée pour le paramètre ``waveform``.""" + """Triangle wave option used for the ``waveform`` parameter.""" + WAVEFORM_SQUARE: ClassVar[int] - """Option d'onde carrée utilisée pour le paramètre ``waveform``.""" + """Square wave option used for the ``waveform`` parameter.""" + WAVEFORM_NOISE: ClassVar[int] - """Option d'onde de bruit utilisée pour le paramètre ``waveform``.""" + """Noise option used for the ``waveform`` parameter.""" + SHAPE_LINEAR: ClassVar[int] - """Option d'interpolation linéaire utilisée pour le paramètre ``shape``.""" + """Linear interpolation option used for the ``shape`` parameter.""" + SHAPE_CURVE: ClassVar[int] - """Option d'interpolation courbe utilisée pour le paramètre ``shape``.""" + """Curve interpolation option used for the ``shape`` parameter.""" + SHAPE_LOG: ClassVar[int] - """Option d'interpolation logarithmique utilisée pour le paramètre ``shape``.""" + """Logarithmic interpolation option used for the ``shape`` parameter.""" + FX_NONE: ClassVar[int] - """Option sans effet utilisée pour le paramètre ``fx``.""" + """No effect option used for the ``fx`` parameter.""" + FX_TREMOLO: ClassVar[int] - """Option d'effet tremolo utilisée pour le paramètre ``fx``.""" + """Tremolo effect option used for the ``fx`` parameter.""" + FX_VIBRATO: ClassVar[int] - """Option d'effet vibrato utilisée pour le paramètre ``fx``.""" + """Vibrato effect option used for the ``fx`` parameter.""" + FX_WARBLE: ClassVar[int] - """Option d'effet de Warble utilisée pour le paramètre ``fx``.""" + """Warble effect option used for the ``fx`` parameter.""" + freq_start: int - """Fréquence de départ en Hertz (Hz), un nombre compris entre ``0`` et ``9999``""" + """Start frequency in Hertz (Hz), a number between ``0`` and ``9999``""" + freq_end: int - """Fréquence de fin en Hertz (Hz), un nombre compris entre ``0`` et ``9999``""" + """End frequency in Hertz (Hz), a number between ``0`` and ``9999``""" + duration: int - """Durée du son en millisecondes, un nombre compris entre ``0`` et ``9999``""" - vol_start: int - """Valeur du volume de départ, un nombre compris entre ``0`` et ``255``""" - vol_end: int - """Valeur du volume à la fin, un nombre compris entre ``0`` et ``255``""" - waveform: int - """Type de forme d'onde, une de ces valeurs : ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (bruit généré aléatoirement)""" - fx: int - """Effet à ajouter au son, l'une des valeurs suivantes : ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, ou ``FX_NONE``""" - shape: int - """Le type de la courbe d'interpolation entre les fréquences de début et de fin, les différentes formes d'onde ont des taux de variation de fréquence différents. L'une des valeurs suivantes : ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``""" + """Duration of the sound in milliseconds, a number between ``0`` and ``9999``""" - def __init__(self, freq_start: int=500, freq_end: int=2500, duration: int=500, vol_start: int=255, vol_end: int=0, waveform: int=WAVEFORM_SQUARE, fx: int=FX_NONE, shape: int=SHAPE_LOG): - """Créer un nouvel effet sonore. + vol_start: int + """Start volume value, a number between ``0`` and ``255``""" -Example: ``my_effect = SoundEffect(duration=1000)`` + vol_end: int + """End volume value, a number between ``0`` and ``255``""" -All the parameters are optional, with default values as shown above, and -they can all be modified via attributes of the same name. For example, we -can first create an effect ``my_effect = SoundEffect(duration=1000)``, -and then change its attributes ``my_effect.duration = 500``. + waveform: int + """Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise)""" -:param freq_start: Fréquence de départ en Hertz (Hz), un nombre compris entre ``0`` et ``9999``. -:param freq_end: Fréquence de fin en Hertz (Hz), un nombre compris entre ``0`` et ``9999``. -:param duration: Durée du son en millisecondes, un nombre compris entre ``0`` et ``9999``. -:param vol_start: Valeur du volume de départ, un nombre compris entre ``0`` et ``255``. -:param vol_end: Valeur du volume à la fin, un nombre compris entre ``0`` et ``255``. -:param waveform: Type de forme d'onde, une de ces valeurs : ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (bruit généré aléatoirement). -:param fx: Effet à ajouter au son, l'une des valeurs suivantes : ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, ou ``FX_NONE``. -:param shape: Le type de la courbe d'interpolation entre les fréquences de début et de fin, les différentes formes d'onde ont des taux de variation de fréquence différents. L'une des valeurs suivantes : ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``.""" + fx: int + """Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``""" + shape: int + """The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``""" + + def __init__( + self, + freq_start: int = 500, + freq_end: int = 2500, + duration: int = 500, + vol_start: int = 255, + vol_end: int = 0, + waveform: int = WAVEFORM_SQUARE, + fx: int = FX_NONE, + shape: int = SHAPE_LOG, + ): + """Create a new sound effect. + + Example: ``my_effect = SoundEffect(duration=1000)`` + + All the parameters are optional, with default values as shown above, and + they can all be modified via attributes of the same name. For example, we + can first create an effect ``my_effect = SoundEffect(duration=1000)``, + and then change its attributes ``my_effect.duration = 500``. + + :param freq_start: Start frequency in Hertz (Hz), a number between ``0`` and ``9999``. + :param freq_end: End frequency in Hertz (Hz), a number between ``0`` and ``9999``. + :param duration: Duration of the sound in milliseconds, a number between ``0`` and ``9999``. + :param vol_start: Start volume value, a number between ``0`` and ``255``. + :param vol_end: End volume value, a number between ``0`` and ``255``. + :param waveform: Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise). + :param fx: Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``. + :param shape: The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``. + """ def copy(self) -> SoundEffect: - """Créer une copie de ce ``SoundEffect``. + """Create a copy of this ``SoundEffect``. -Example: ``sound_2 = sound_1.copy()`` + Example: ``sound_2 = sound_1.copy()`` -:return: A copy of the SoundEffect.""" + :return: A copy of the SoundEffect. + """ class AudioFrame: - """Un objet ``AudioFrame`` est une liste de 32 échantillons, chacun d'eux étant un octet non signé -(nombre entier entre 0 et 255). + """An ``AudioFrame`` object is a list of 32 samples each of which is a unsigned byte + (whole number between 0 and 255). -It takes just over 4 ms to play a single frame. + It takes just over 4 ms to play a single frame. -Example:: + Example:: - frame = AudioFrame() - for i in range(len(frame)): - frame[i] = 252 - i * 8""" + frame = AudioFrame() + for i in range(len(frame)): + frame[i] = 252 - i * 8 + """ def copyfrom(self, other: AudioFrame) -> None: - """Écraser les données de ce ``AudioFrame`` avec les données d'une autre instance ``AudioFrame``. - -Example: ``my_frame.copyfrom(source_frame)`` - -:param other: Instance ``AudioFrame`` à partir de laquelle copier les données.""" - - def __len__(self) -> int: - ... + """Overwrite the data in this ``AudioFrame`` with the data from another ``AudioFrame`` instance. - def __setitem__(self, key: int, value: int) -> None: - ... + Example: ``my_frame.copyfrom(source_frame)`` - def __getitem__(self, key: int) -> int: - ... \ No newline at end of file + :param other: ``AudioFrame`` instance from which to copy the data. + """ + def __len__(self) -> int: ... + def __setitem__(self, key: int, value: int) -> None: ... + def __getitem__(self, key: int) -> int: ... diff --git a/lang/fr/typeshed/stdlib/microbit/compass.pyi b/lang/fr/typeshed/stdlib/microbit/compass.pyi index 6dfd7d2..c74a47b 100644 --- a/lang/fr/typeshed/stdlib/microbit/compass.pyi +++ b/lang/fr/typeshed/stdlib/microbit/compass.pyi @@ -1,70 +1,78 @@ -"""Utiliser la boussole intégrée.""" +"""Use the built-in compass. +""" def calibrate() -> None: - """Démarrer le processus d'étalonnage. + """Starts the calibration process. -Example: ``compass.calibrate()`` + Example: ``compass.calibrate()`` -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.""" + 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: - """Vérifier si la boussole est étalonnée. + """Check is the compass is calibrated. -Example: ``compass.is_calibrated()`` + Example: ``compass.is_calibrated()`` -:return: ``True`` if the compass has been successfully calibrated, ``False`` otherwise.""" + :return: ``True`` if the compass has been successfully calibrated, ``False`` otherwise. + """ ... def clear_calibration() -> None: - """Annule l'étalonnage, la boussole est ainsi à nouveau non-étalonnée. + """Undoes the calibration, making the compass uncalibrated again. -Example: ``compass.clear_calibration()``""" + Example: ``compass.clear_calibration()`` + """ ... def get_x() -> int: - """Obtenir la force du champ magnétique sur l'axe ``x``. + """Get the magnetic field strength on the ``x`` axis. -Example: ``compass.get_x()`` + Example: ``compass.get_x()`` -Call ``calibrate`` first or the results will be inaccurate. + Call ``calibrate`` first or the results will be inaccurate. -:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" + :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. + """ ... def get_y() -> int: - """Obtenir la force du champ magnétique sur l'axe ``y``. + """Get the magnetic field strength on the ``y`` axis. -Example: ``compass.get_y()`` + Example: ``compass.get_y()`` -Call ``calibrate`` first or the results will be inaccurate. + Call ``calibrate`` first or the results will be inaccurate. -:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" + :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. + """ ... def get_z() -> int: - """Obtenir la force du champ magnétique sur l'axe ``z``. + """Get the magnetic field strength on the ``z`` axis. -Example: ``compass.get_z()`` + Example: ``compass.get_z()`` -Call ``calibrate`` first or the results will be inaccurate. + Call ``calibrate`` first or the results will be inaccurate. -:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" + :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. + """ ... def heading() -> int: - """Obtenir le cap de la boussole. + """Get the compass heading. -Example: ``compass.heading()`` + Example: ``compass.heading()`` -:return: An integer in the range from 0 to 360, representing the angle in degrees, clockwise, with north as 0.""" + :return: An integer in the range from 0 to 360, representing the angle in degrees, clockwise, with north as 0. + """ ... def get_field_strength() -> int: - """Récupère la magnitude du champ magnétique autour de l'appareil. + """Get the magnitude of the magnetic field around the device. -Example: ``compass.get_field_strength()`` + Example: ``compass.get_field_strength()`` -:return: An integer indication of the magnitude of the magnetic field in nano tesla.""" - ... \ No newline at end of file + :return: An integer indication of the magnitude of the magnetic field in nano tesla.""" + ... diff --git a/lang/fr/typeshed/stdlib/microbit/display.pyi b/lang/fr/typeshed/stdlib/microbit/display.pyi index b3c8311..aa4013e 100644 --- a/lang/fr/typeshed/stdlib/microbit/display.pyi +++ b/lang/fr/typeshed/stdlib/microbit/display.pyi @@ -1,92 +1,115 @@ -"""Afficher du texte, des images et des animations sur l'écran LED 5×5.""" +"""Show text, images and animations on the 5×5 LED display. +""" + from ..microbit import Image from typing import Union, overload, Iterable def get_pixel(x: int, y: int) -> int: - """Récupère la luminosité de la LED à la colonne ``x`` et à la ligne ``y``. + """Get the brightness of the LED at column ``x`` and row ``y``. -Example: ``display.get_pixel(0, 0)`` + Example: ``display.get_pixel(0, 0)`` -:param x: La colonne d'affichage (0..4) -:param y: La ligne d'affichage (0..4) -:return: A number between 0 (off) and 9 (bright)""" + :param x: The display column (0..4) + :param y: The display row (0..4) + :return: A number between 0 (off) and 9 (bright) + """ ... def set_pixel(x: int, y: int, value: int) -> None: - """Définit la luminosité de la LED à la colonne ``x`` et à la ligne ``y``. + """Set the brightness of the LED at column ``x`` and row ``y``. -Example: ``display.set_pixel(0, 0, 9)`` + Example: ``display.set_pixel(0, 0, 9)`` -:param x: La colonne d'affichage (0..4) -:param y: La ligne d'affichage (0..4) -:param value: La luminosité entre 0 (éteint) et 9 (lumineux)""" + :param x: The display column (0..4) + :param y: The display row (0..4) + :param value: The brightness between 0 (off) and 9 (bright) + """ ... def clear() -> None: - """Régler la luminosité de toutes les LED à 0 (éteintes). + """Set the brightness of all LEDs to 0 (off). -Example: ``display.clear()``""" + Example: ``display.clear()`` + """ ... -def show(image: Union[str, float, int, Image, Iterable[Image]], delay: int=400, wait: bool=True, loop: bool=False, clear: bool=False) -> None: - """Afficher des images, des lettres ou des chiffres sur l'affichage LED. +def show( + image: Union[str, float, int, Image, Iterable[Image]], + delay: int = 400, + wait: bool = True, + loop: bool = False, + clear: bool = False, +) -> None: + """Shows images, letters or digits on the LED display. -Example: ``display.show(Image.HEART)`` + Example: ``display.show(Image.HEART)`` -When ``image`` is an image or a list of images then each image is displayed in turn. -If ``image`` is a string or number, each letter or digit is displayed in turn. + When ``image`` is an image or a list of images then each image is displayed in turn. + If ``image`` is a string or number, each letter or digit is displayed in turn. -:param image: Une chaîne de caractères, un nombre, une image ou une liste d'images à afficher. -:param delay: Chaque lettre, chiffre ou image est séparé par un délai de ``delay`` millisecondes. -:param wait: Si ``wait`` est ``True`` cette fonction bloquera jusqu'à la fin de l'animation, sinon l'animation s'effectuera en arrière-plan. -:param loop: Si ``loop`` est ``True``, l'animation se répétera indéfiniment. -:param clear: Si ``clear`` est ``True``, l'affichage sera effacé une fois la séquence terminée. + :param image: A string, number, image or list of images to show. + :param delay: Each letter, digit or image is shown with ``delay`` milliseconds between them. + :param wait: If ``wait`` is ``True``, this function will block until the animation is finished, otherwise the animation will happen in the background. + :param loop: If ``loop`` is ``True``, the animation will repeat forever. + :param clear: If ``clear`` is ``True``, the display will be cleared after the sequence has finished. -The ``wait``, ``loop`` and ``clear`` arguments must be specified using their keyword.""" + The ``wait``, ``loop`` and ``clear`` arguments must be specified using their keyword. + """ ... -def scroll(text: Union[str, float, int], delay: int=150, wait: bool=True, loop: bool=False, monospace: bool=False) -> None: - """Faire défiler un nombre ou un texte sur l'affichage LED. - -Example: ``display.scroll('micro:bit')`` - -:param text: La chaîne de caractères à faire défiler. Si ``text`` est un entier ou un nombre décimal, il sera converti en une chaîne avec ``str()``. -:param delay: Le paramètre ``delay`` contrôle la vitesse de défilement du texte. -:param wait: Si ``wait`` est ``True`` cette fonction bloquera jusqu'à la fin de l'animation, sinon l'animation s'effectuera en arrière-plan. -:param loop: Si ``loop`` est ``True``, l'animation se répétera indéfiniment. -:param monospace: Si ``monospace`` est ``True``, tous les caractères utiliseront 5 pixels en largeur, sinon, exactement 1 colonne de pixel vide sera insérée entre chaque caractère lors du défilement. - -The ``wait``, ``loop`` and ``monospace`` arguments must be specified -using their keyword.""" +def scroll( + text: Union[str, float, int], + delay: int = 150, + wait: bool = True, + loop: bool = False, + monospace: bool = False, +) -> None: + """Scrolls a number or text on the LED display. + + Example: ``display.scroll('micro:bit')`` + + :param text: The string to scroll. If ``text`` is an integer or float it is first converted to a string using ``str()``. + :param delay: The ``delay`` parameter controls how fast the text is scrolling. + :param wait: If ``wait`` is ``True``, this function will block until the animation is finished, otherwise the animation will happen in the background. + :param loop: If ``loop`` is ``True``, the animation will repeat forever. + :param monospace: 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. + + The ``wait``, ``loop`` and ``monospace`` arguments must be specified + using their keyword. + """ ... def on() -> None: - """Allumer l'écran LED. + """Turn on the LED display. -Example: ``display.on()``""" + Example: ``display.on()`` + """ ... def off() -> None: - """Eteindre l'écran LED (désactiver l'affichage vous permet de réutiliser les broches GPIO à d'autres fins). + """Turn off the LED display (disabling the display allows you to re-use the GPIO pins for other purposes). -Example: ``display.off()``""" + Example: ``display.off()`` + """ ... def is_on() -> bool: - """Vérifier si l'affichage LED est activé. + """Check whether the LED display is enabled. -Example: ``display.is_on()`` + Example: ``display.is_on()`` -:return: ``True`` if the display is on, otherwise returns ``False``.""" + :return: ``True`` if the display is on, otherwise returns ``False``. + """ ... def read_light_level() -> int: - """Lit le niveau de lumière. + """Read the light level. -Example: ``display.read_light_level()`` + Example: ``display.read_light_level()`` -Uses the display's LEDs in reverse-bias mode to sense the amount of light -falling on the display. + Uses the display's LEDs in reverse-bias mode to sense the amount of light + falling on the display. -:return: An integer between 0 and 255 representing the light level, with larger meaning more light.""" - ... \ No newline at end of file + :return: An integer between 0 and 255 representing the light level, with larger meaning more light. + """ + ... diff --git a/lang/fr/typeshed/stdlib/microbit/i2c.pyi b/lang/fr/typeshed/stdlib/microbit/i2c.pyi index dc0230f..df26efa 100644 --- a/lang/fr/typeshed/stdlib/microbit/i2c.pyi +++ b/lang/fr/typeshed/stdlib/microbit/i2c.pyi @@ -1,49 +1,57 @@ -"""Communiquer avec les périphériques en utilisant le protocole de bus I²C.""" +"""Communicate with devices using the I²C bus protocol. +""" + from _typeshed import ReadableBuffer from ..microbit import MicroBitDigitalPin, pin19, pin20 from typing import List -def init(freq: int=100000, sda: MicroBitDigitalPin=pin20, scl: MicroBitDigitalPin=pin19) -> None: - """Réinitialiser un périphérique. +def init( + freq: int = 100000, sda: MicroBitDigitalPin = pin20, scl: MicroBitDigitalPin = pin19 +) -> None: + """Re-initialize a peripheral. -Example: ``i2c.init()`` + Example: ``i2c.init()`` -:param freq: fréquence d'horloge -:param sda: Broche ``sda`` (19 par défaut) -:param scl: Broche ``scl`` (19 par défaut) + :param freq: clock frequency + :param sda: ``sda`` pin (default 20) + :param scl: ``scl`` pin (default 19) -On a micro:bit V1 board, changing the I²C pins from defaults will make -the accelerometer and compass stop working, as they are connected -internally to those pins. This warning does not apply to the **V2** -revision of the micro:bit as this has `separate I²C lines `_ -for the motion sensors and the edge connector.""" + On a micro:bit V1 board, changing the I²C pins from defaults will make + the accelerometer and compass stop working, as they are connected + internally to those pins. This warning does not apply to the **V2** + revision of the micro:bit as this has `separate I²C lines `_ + for the motion sensors and the edge connector. + """ ... def scan() -> List[int]: - """Scanner le bus pour détecter des périphériques. + """Scan the bus for devices. -Example: ``i2c.scan()`` + Example: ``i2c.scan()`` -:return: A list of 7-bit addresses corresponding to those devices that responded to the scan.""" + :return: A list of 7-bit addresses corresponding to those devices that responded to the scan. + """ ... -def read(addr: int, n: int, repeat: bool=False) -> bytes: - """Lire des octets depuis un périphérique. +def read(addr: int, n: int, repeat: bool = False) -> bytes: + """Read bytes from a device. -Example: ``i2c.read(0x50, 64)`` + Example: ``i2c.read(0x50, 64)`` -:param addr: L'adresse 7-bit du périphérique -:param n: Le nombre d'octets à lire -:param repeat: Si ``True``, aucun bit d'arrêt ne sera envoyé -:return: The bytes read""" + :param addr: The 7-bit address of the device + :param n: The number of bytes to read + :param repeat: If ``True``, no stop bit will be sent + :return: The bytes read + """ ... -def write(addr: int, buf: ReadableBuffer, repeat: bool=False) -> None: - """Écrire des octets sur un périphérique. +def write(addr: int, buf: ReadableBuffer, repeat: bool = False) -> None: + """Write bytes to a device. -Example: ``i2c.write(0x50, bytes([1, 2, 3]))`` + Example: ``i2c.write(0x50, bytes([1, 2, 3]))`` -:param addr: L'adresse 7-bit du périphérique -:param buf: Un buffer contenant les octets à écrire -:param repeat: Si ``True``, aucun bit d'arrêt ne sera envoyé""" - ... \ No newline at end of file + :param addr: The 7-bit address of the device + :param buf: A buffer containing the bytes to write + :param repeat: If ``True``, no stop bit will be sent + """ + ... diff --git a/lang/fr/typeshed/stdlib/microbit/microphone.pyi b/lang/fr/typeshed/stdlib/microbit/microphone.pyi index f8071e7..68e8f3a 100644 --- a/lang/fr/typeshed/stdlib/microbit/microphone.pyi +++ b/lang/fr/typeshed/stdlib/microbit/microphone.pyi @@ -1,62 +1,70 @@ -"""Réagir à du son en utilisant le microphone intégré (V2 uniquement).""" +"""Respond to sound using the built-in microphone (V2 only). +""" + from typing import Optional, Tuple from ..microbit import SoundEvent def current_event() -> Optional[SoundEvent]: - """Récupérer le dernier événement sonore enregistré + """Get the last recorded sound event -Example: ``microphone.current_event()`` + Example: ``microphone.current_event()`` -:return: The event, ``SoundEvent('loud')`` or ``SoundEvent('quiet')``.""" + :return: The event, ``SoundEvent('loud')`` or ``SoundEvent('quiet')``. + """ ... def was_event(event: SoundEvent) -> bool: - """Vérifier si un son a été entendu au moins une fois depuis le dernier appel. + """Check if a sound was heard at least once since the last call. -Example: ``microphone.was_event(SoundEvent.LOUD)`` + Example: ``microphone.was_event(SoundEvent.LOUD)`` -This call clears the sound history before returning. + This call clears the sound history before returning. -:param event: L'événement à vérifier, tel que ``SoundEvent.LOUD`` ou ``SoundEvent.QUIET`` -:return: ``True`` if sound was heard at least once since the last call, otherwise ``False``.""" + :param event: The event to check for, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET`` + :return: ``True`` if sound was heard at least once since the last call, otherwise ``False``. + """ ... def is_event(event: SoundEvent) -> bool: - """Vérifier l'événement sonore le plus récent détecté. + """Check the most recent sound event detected. -Example: ``microphone.is_event(SoundEvent.LOUD)`` + Example: ``microphone.is_event(SoundEvent.LOUD)`` -This call does not clear the sound event history. + This call does not clear the sound event history. -:param event: L'événement à vérifier, tel que ``SoundEvent.LOUD`` ou ``SoundEvent.QUIET`` -:return: ``True`` if sound was the most recent heard, ``False`` otherwise.""" + :param event: The event to check for, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET`` + :return: ``True`` if sound was the most recent heard, ``False`` otherwise. + """ ... def get_events() -> Tuple[SoundEvent, ...]: - """Récupérer l'historique des événements sonores en tant que tuple. + """Get the sound event history as a tuple. -Example: ``microphone.get_events()`` + Example: ``microphone.get_events()`` -This call clears the sound history before returning. + This call clears the sound history before returning. -:return: A tuple of the event history with the most recent event last.""" + :return: A tuple of the event history with the most recent event last. + """ ... def set_threshold(event: SoundEvent, value: int) -> None: - """Définir le seuil pour un événement sonore. + """Set the threshold for a sound event. -Example: ``microphone.set_threshold(SoundEvent.LOUD, 250)`` + Example: ``microphone.set_threshold(SoundEvent.LOUD, 250)`` -A high threshold means the event will only trigger if the sound is very loud (>= 250 in the example). + A high threshold means the event will only trigger if the sound is very loud (>= 250 in the example). -:param event: Un événement sonore, tel que ``SoundEvent.LOUD`` ou ``SoundEvent.QUIET``. -:param value: Le niveau du seuil dans la plage 0-255.""" + :param event: A sound event, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET``. + :param value: The threshold level in the range 0-255. + """ ... def sound_level() -> int: - """Obtenir le niveau de pression acoustique. + """Get the sound pressure level. -Example: ``microphone.sound_level()`` + Example: ``microphone.sound_level()`` -:return: A representation of the sound pressure level in the range 0 to 255.""" - ... \ No newline at end of file + :return: A representation of the sound pressure level in the range 0 to 255. + """ + ... diff --git a/lang/fr/typeshed/stdlib/microbit/speaker.pyi b/lang/fr/typeshed/stdlib/microbit/speaker.pyi index 07024ed..5a74a4d 100644 --- a/lang/fr/typeshed/stdlib/microbit/speaker.pyi +++ b/lang/fr/typeshed/stdlib/microbit/speaker.pyi @@ -1,15 +1,18 @@ -"""Contrôler le haut-parleur intégré (V2 uniquement).""" +"""Control the built-in speaker (V2 only). +""" def off() -> None: - """Éteindre le haut-parleur. + """Turn the speaker off. -Example: ``speaker.off()`` + Example: ``speaker.off()`` -This does not disable sound output to an edge connector pin.""" + This does not disable sound output to an edge connector pin. + """ ... def on() -> None: - """Activer le haut-parleur. + """Turn the speaker on. -Example: ``speaker.on()``""" - ... \ No newline at end of file + Example: ``speaker.on()`` + """ + ... diff --git a/lang/fr/typeshed/stdlib/microbit/spi.pyi b/lang/fr/typeshed/stdlib/microbit/spi.pyi index 08c0860..09c4046 100644 --- a/lang/fr/typeshed/stdlib/microbit/spi.pyi +++ b/lang/fr/typeshed/stdlib/microbit/spi.pyi @@ -1,47 +1,60 @@ -"""Communiquer avec les périphériques à l'aide du bus SPI (Serial Peripheral Interface).""" +"""Communicate with devices using the serial peripheral interface (SPI) bus. +""" + from _typeshed import ReadableBuffer, WriteableBuffer from ..microbit import pin13, pin14, pin15, MicroBitDigitalPin -def init(baudrate: int=1000000, bits: int=8, mode: int=0, sclk: MicroBitDigitalPin=pin13, mosi: MicroBitDigitalPin=pin15, miso: MicroBitDigitalPin=pin14) -> None: - """Initialiser la communication SPI. - -Example: ``spi.init()`` - -For correct communication, the parameters have to be the same on both communicating devices. - -:param baudrate: La vitesse de communication. -:param bits: La largeur en bits de chaque transfert. Actuellement, seul ``bits=8`` est pris en charge. Cependant, cela peut évoluer à l'avenir. -:param mode: Détermine la combinaison de la polarité et de la phase de l'horloge. - `voir le tableau en ligne `_. -:param sclk: Broche sclk (13 par défaut) -:param mosi: Broche mosi (15 par défaut) -:param miso: Broche miso (14 par défaut)""" +def init( + baudrate: int = 1000000, + bits: int = 8, + mode: int = 0, + sclk: MicroBitDigitalPin = pin13, + mosi: MicroBitDigitalPin = pin15, + miso: MicroBitDigitalPin = pin14, +) -> None: + """Initialize SPI communication. + + Example: ``spi.init()`` + + For correct communication, the parameters have to be the same on both communicating devices. + + :param baudrate: The speed of communication. + :param bits: The width in bits of each transfer. Currently only ``bits=8`` is supported. However, this may change in the future. + :param mode: Determines the combination of clock polarity and phase - `see online table `_. + :param sclk: sclk pin (default 13) + :param mosi: mosi pin (default 15) + :param miso: miso pin (default 14) + """ ... -def read(nbytes: int, out: int=0) -> bytes: - """Lire des octets. +def read(nbytes: int, out: int = 0) -> bytes: + """Read at most ``nbytes`` while continuously writing the single byte given by ``out``. -Example: ``spi.read(64)`` + Example: ``spi.read(64)`` -:param nbytes: Nombre maximal d'octets à lire. -:param out: The byte value to write (default 0). -:return: The bytes read.""" + :param nbytes: Maximum number of bytes to read. + :param out: The byte value to write (default 0). + :return: The bytes read. + """ ... def write(buffer: ReadableBuffer) -> None: - """Écrire des octets sur le bus. + """Write bytes to the bus. -Example: ``spi.write(bytes([1, 2, 3]))`` + Example: ``spi.write(bytes([1, 2, 3]))`` -:param buffer: Un buffer à partir duquel lire les données.""" + :param buffer: A buffer to read data from. + """ ... def write_readinto(out: WriteableBuffer, in_: ReadableBuffer) -> None: - """Ecrire le buffer ``out`` sur le bus et lire toute réponse dans le buffer ``in_``. + """Write the ``out`` buffer to the bus and read any response into the ``in_`` buffer. -Example: ``spi.write_readinto(out_buffer, in_buffer)`` + Example: ``spi.write_readinto(out_buffer, in_buffer)`` -The length of the buffers should be the same. The buffers can be the same object. + The length of the buffers should be the same. The buffers can be the same object. -:param out: Le buffer vers lequel écrire une réponse. -:param in_: Le buffer depuis lequel lire les données.""" - ... \ No newline at end of file + :param out: The buffer to write any response to. + :param in_: The buffer to read data from. + """ + ... diff --git a/lang/fr/typeshed/stdlib/microbit/uart.pyi b/lang/fr/typeshed/stdlib/microbit/uart.pyi index 6d566a9..2ab650f 100644 --- a/lang/fr/typeshed/stdlib/microbit/uart.pyi +++ b/lang/fr/typeshed/stdlib/microbit/uart.pyi @@ -1,79 +1,96 @@ -"""Communiquer avec un périphérique à l'aide d'une interface série.""" +"""Communicate with a device using a serial interface. +""" + from _typeshed import WriteableBuffer from ..microbit import MicroBitDigitalPin from typing import Optional, Union -ODD: int -"""Parité impaire""" -EVEN: int -"""Parité paire""" - -def init(baudrate: int=9600, bits: int=8, parity: Optional[int]=None, stop: int=1, tx: Optional[MicroBitDigitalPin]=None, rx: Optional[MicroBitDigitalPin]=None) -> None: - """Initialiser la communication série. - -Example: ``uart.init(115200, tx=pin0, rx=pin1)`` -:param baudrate: La vitesse de communication. -:param bits: La taille des octets transmis. micro:bit ne prend en charge que 8. -:param parity: Comment la parité est vérifiée, ``None``, ``uart.ODD`` ou ``uart.EVEN``. -:param stop: Le nombre de bits d'arrêt, doit être 1 pour micro:bit. -:param tx: Broche de transmission. -:param rx: Broche de réception. - -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. +ODD: int +"""Odd parity""" -For more details see `the online documentation `_.""" +EVEN: int +"""Even parity""" + +def init( + baudrate: int = 9600, + bits: int = 8, + parity: Optional[int] = None, + stop: int = 1, + tx: Optional[MicroBitDigitalPin] = None, + rx: Optional[MicroBitDigitalPin] = None, +) -> None: + """Initialize serial communication. + + Example: ``uart.init(115200, tx=pin0, rx=pin1)`` + + :param baudrate: The speed of communication. + :param bits: The size of bytes being transmitted. micro:bit only supports 8. + :param parity: How parity is checked, ``None``, ``uart.ODD`` or ``uart.EVEN``. + :param stop: The number of stop bits, has to be 1 for micro:bit. + :param tx: Transmitting pin. + :param rx: Receiving pin. + + 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. + + For more details see `the online documentation `_. + """ ... def any() -> bool: - """Vérifier s'il y a des données en attente. + """Check if any data is waiting. -Example: ``uart.any()`` + Example: ``uart.any()`` -:return: ``True`` if any data is waiting, else ``False``.""" + :return: ``True`` if any data is waiting, else ``False``. + """ ... -def read(nbytes: Optional[int]=None) -> Optional[bytes]: - """Lire des octets. +def read(nbytes: Optional[int] = None) -> Optional[bytes]: + """Read bytes. -Example: ``uart.read()`` + Example: ``uart.read()`` -:param nbytes: Si ``nbytes`` est spécifié, alors lire au maximum cette quantité d'octets, sinon lire autant d'octets que possible -:return: A bytes object or ``None`` on timeout""" + :param nbytes: If ``nbytes`` is specified then read at most that many bytes, otherwise read as many bytes as possible + :return: A bytes object or ``None`` on timeout + """ ... -def readinto(buf: WriteableBuffer, nbytes: Optional[int]=None) -> Optional[int]: - """Lire les octets dans le ``buf``. +def readinto(buf: WriteableBuffer, nbytes: Optional[int] = None) -> Optional[int]: + """Read bytes into the ``buf``. -Example: ``uart.readinto(input_buffer)`` + Example: ``uart.readinto(input_buffer)`` -:param buf: Le buffer dans lequel écrire. -:param nbytes: Si ``nbytes`` est spécifié, alors lire au maximum cette quantité d'octets, sinon lire ``len(buf)`` octets. -:return: number of bytes read and stored into ``buf`` or ``None`` on timeout.""" + :param buf: The buffer to write to. + :param nbytes: If ``nbytes`` is specified then read at most that many bytes, otherwise read ``len(buf)`` bytes. + :return: number of bytes read and stored into ``buf`` or ``None`` on timeout. + """ ... def readline() -> Optional[bytes]: - """Lire une ligne terminée par un caractère de nouvelle ligne. + """Read a line, ending in a newline character. -Example: ``uart.readline()`` + Example: ``uart.readline()`` -:return: The line read or ``None`` on timeout. The newline character is included in the returned bytes.""" + :return: The line read or ``None`` on timeout. The newline character is included in the returned bytes. + """ ... def write(buf: Union[bytes, str]) -> Optional[int]: - """Écrire un buffer sur un bus + """Write a buffer to the bus. -Example: ``uart.write('hello world')`` + Example: ``uart.write('hello world')`` -:param buf: Un objet d'octets ou une chaîne de caractères. -:return: The number of bytes written, or ``None`` on timeout. + :param buf: A bytes object or a string. + :return: The number of bytes written, or ``None`` on timeout. -Examples:: + Examples:: - uart.write('hello world') - uart.write(b'hello world') - uart.write(bytes([1, 2, 3]))""" - ... \ No newline at end of file + uart.write('hello world') + uart.write(b'hello world') + uart.write(bytes([1, 2, 3])) + """ + ... diff --git a/lang/fr/typeshed/stdlib/micropython.pyi b/lang/fr/typeshed/stdlib/micropython.pyi index 1ea05cc..7a6079f 100644 --- a/lang/fr/typeshed/stdlib/micropython.pyi +++ b/lang/fr/typeshed/stdlib/micropython.pyi @@ -1,132 +1,144 @@ -"""Les coulisses de MicroPython.""" +"""MicroPython internals.""" + from typing import Any, TypeVar, overload -_T = TypeVar('_T') + +_T = TypeVar("_T") def const(expr: _T) -> _T: - """Utilisé pour déclarer que l'expression est une constante afin que le compilateur puisse -l'optimiser. + """Used to declare that the expression is a constant so that the compiler can + optimise it. -The use of this function should be as follows:: + The use of this function should be as follows:: - from micropython import const - CONST_X = const(123) - CONST_Y = const(2 * CONST_X + 1) + from micropython import const + CONST_X = const(123) + CONST_Y = const(2 * CONST_X + 1) -Constants declared this way are still accessible as global variables from -outside the module they are declared in. On the other hand, if a constant -begins with an underscore then it is hidden, it is not available as a -global variable, and does not take up any memory during execution. + Constants declared this way are still accessible as global variables from + outside the module they are declared in. On the other hand, if a constant + begins with an underscore then it is hidden, it is not available as a + global variable, and does not take up any memory during execution. -:param expr: Une expression constante.""" + :param expr: A constant expression. + """ ... @overload def opt_level() -> int: - """Récupère le niveau d'optimisation actuel pour la compilation des scripts. + """Get the current optimisation level for the compilation of scripts. -Example: ``micropython.opt_level()`` + Example: ``micropython.opt_level()`` -The optimisation level controls the following compilation features: + The optimisation level controls the following compilation features: -- Assertions: at level 0 assertion statements are enabled and compiled - into the bytecode; at levels 1 and higher assertions are not compiled. + - Assertions: at level 0 assertion statements are enabled and compiled + into the bytecode; at levels 1 and higher assertions are not compiled. -- Built-in ``__debug__`` variable: at level 0 this variable expands to - True; at levels 1 and higher it expands to False. + - Built-in ``__debug__`` variable: at level 0 this variable expands to + True; at levels 1 and higher it expands to False. -- Source-code line numbers: at levels 0, 1 and 2 source-code line number - are stored along with the bytecode so that exceptions can report the - line number they occurred at; at levels 3 and higher line numbers are - not stored. + - Source-code line numbers: at levels 0, 1 and 2 source-code line number + are stored along with the bytecode so that exceptions can report the + line number they occurred at; at levels 3 and higher line numbers are + not stored. -:return: An integer representing the current level.""" + :return: An integer representing the current level. + """ ... @overload def opt_level(level: int) -> None: - """Définir le niveau d'optimisation pour la compilation ultérieure des scripts. + """Sets the optimisation level for subsequent compilation of scripts. -Example: ``micropython.opt_level(1)`` + Example: ``micropython.opt_level(1)`` -The optimisation level controls the following compilation features: + The optimisation level controls the following compilation features: -- Assertions: at level 0 assertion statements are enabled and compiled - into the bytecode; at levels 1 and higher assertions are not compiled. + - Assertions: at level 0 assertion statements are enabled and compiled + into the bytecode; at levels 1 and higher assertions are not compiled. -- Built-in ``__debug__`` variable: at level 0 this variable expands to - True; at levels 1 and higher it expands to False. + - Built-in ``__debug__`` variable: at level 0 this variable expands to + True; at levels 1 and higher it expands to False. -- Source-code line numbers: at levels 0, 1 and 2 source-code line number - are stored along with the bytecode so that exceptions can report the - line number they occurred at; at levels 3 and higher line numbers are - not stored. + - Source-code line numbers: at levels 0, 1 and 2 source-code line number + are stored along with the bytecode so that exceptions can report the + line number they occurred at; at levels 3 and higher line numbers are + not stored. -The default optimisation level is usually level 0. + The default optimisation level is usually level 0. -:param level: Un entier indiquant le niveau d'optimisation.""" + :param level: An integer optimisation level. + """ ... -def mem_info(verbose: Any=None) -> None: - """Afficher des informations sur la mémoire actuellement utilisée. +def mem_info(verbose: Any = None) -> None: + """Print information about currently used memory. -Example: ``micropython.mem_info()`` + Example: ``micropython.mem_info()`` -:param verbose: Si l'argument ``verbose`` est spécifié, des informations supplémentaires seront affichées.""" + :param verbose: If the ``verbose`` argument is given then extra information is printed. + """ ... -def qstr_info(verbose: Any=None) -> None: - """Affiche des informations sur les chaînes de caractères internalisées. +def qstr_info(verbose: Any = None) -> None: + """Print information about currently interned strings. -Example: ``micropython.qstr_info()`` + Example: ``micropython.qstr_info()`` -:param verbose: Si l'argument ``verbose`` est spécifié, des informations supplémentaires seront affichées. + :param verbose: If the ``verbose`` argument is given then extra information is printed. -The information that is printed is implementation dependent, but currently -includes the number of interned strings and the amount of RAM they use. In -verbose mode it prints out the names of all RAM-interned strings.""" + The information that is printed is implementation dependent, but currently + includes the number of interned strings and the amount of RAM they use. In + verbose mode it prints out the names of all RAM-interned strings. + """ ... def stack_use() -> int: - """Renvoie un nombre entier représentant la taille de la pile en cours d'utilisation. + """Return an integer representing the current amount of stack that is being + used. -Example: ``micropython.stack_use()`` + Example: ``micropython.stack_use()`` -The absolute value of this is not particularly useful, rather it -should be used to compute differences in stack usage at different points. + The absolute value of this is not particularly useful, rather it + should be used to compute differences in stack usage at different points. -:return: An integer representing current stack use.""" + :return: An integer representing current stack use. + """ ... def heap_lock() -> None: - """Verrouille le tas (heap). + """Lock the heap. -Example: ``micropython.heap_lock()`` + Example: ``micropython.heap_lock()`` -When locked no memory allocation can occur and a ``MemoryError`` will be -raised if any heap allocation is attempted.""" + When locked no memory allocation can occur and a ``MemoryError`` will be + raised if any heap allocation is attempted. + """ ... def heap_unlock() -> None: - """Déverrouille le tas (heap). + """Unlock the heap. -Example: ``micropython.heap_unlock()`` + Example: ``micropython.heap_unlock()`` -When locked no memory allocation can occur and a ``MemoryError`` will be -raised if any heap allocation is attempted.""" + When locked no memory allocation can occur and a ``MemoryError`` will be + raised if any heap allocation is attempted. + """ ... def kbd_intr(chr: int) -> None: - """Définir le caractère qui lèvera une exception ``KeyboardInterrupt``. + """Set the character that will raise a ``KeyboardInterrupt`` exception. -Example: ``micropython.kbd_intr(-1)`` + Example: ``micropython.kbd_intr(-1)`` -:param chr: Code de caractère pour générer l'interruption ou -1 pour désactiver la capture de Ctrl-C. + :param chr: Character code to raise the interrupt or -1 to disable capture of Ctrl-C. -By default this is set to 3 during script execution, corresponding to Ctrl-C. -Passing -1 to this function will disable capture of Ctrl-C, and passing 3 -will restore it. + By default this is set to 3 during script execution, corresponding to Ctrl-C. + Passing -1 to this function will disable capture of Ctrl-C, and passing 3 + will restore it. -This function can be used to prevent the capturing of Ctrl-C on the -incoming stream of characters that is usually used for the REPL, in case -that stream is used for other purposes.""" - ... \ No newline at end of file + This function can be used to prevent the capturing of Ctrl-C on the + incoming stream of characters that is usually used for the REPL, in case + that stream is used for other purposes. + """ + ... diff --git a/lang/fr/typeshed/stdlib/music.pyi b/lang/fr/typeshed/stdlib/music.pyi index cf7e2fc..5f4778b 100644 --- a/lang/fr/typeshed/stdlib/music.pyi +++ b/lang/fr/typeshed/stdlib/music.pyi @@ -1,128 +1,167 @@ -"""Créer et jouer des mélodies.""" +"""Create and play melodies. +""" from typing import Optional, Tuple, Union, List + from .microbit import MicroBitDigitalPin, pin0 + DADADADUM: Tuple[str, ...] -"""Mélodie : l'ouverture de la 5e symphonie en do mineur de Beethoven.""" +"""Melody: the opening to Beethoven’s 5th Symphony in C minor.""" + ENTERTAINER: Tuple[str, ...] -"""Mélodie : le fragment d'ouverture du classique de ragtime "The Entertainer" de Scott Joplin.""" +"""Melody: the opening fragment of Scott Joplin’s Ragtime classic “The Entertainer”.""" + PRELUDE: Tuple[str, ...] -"""Mélodie : le prélude et fugue en ut majeur (BWV 846) de Jean-Sébastien Bach.""" +"""Melody: the opening of the first Prelude in C Major of J.S.Bach’s 48 Preludes and Fugues.""" + ODE: Tuple[str, ...] -"""Mélodie : le thème de l'"Ode à la joie" de la 9e symphonie en ré mineur de Beethoven.""" +"""Melody: the “Ode to Joy” theme from Beethoven’s 9th Symphony in D minor.""" + NYAN: Tuple[str, ...] -"""Mélodie : le thème de Nyan Cat (http://www.nyan.cat/). +"""Melody: the Nyan Cat theme (http://www.nyan.cat/). The composer is unknown. This is fair use for educational porpoises (as they say in New York).""" + RINGTONE: Tuple[str, ...] -"""Mélodie : son qui ressemble à une sonnerie de téléphone mobile. +"""Melody: something that sounds like a mobile phone ringtone. To be used to indicate an incoming message. """ + FUNK: Tuple[str, ...] -"""Mélodie : une ligne de basse funky pour les agents secrets et les cerveaux criminels.""" +"""Melody: a funky bass line for secret agents and criminal masterminds.""" + BLUES: Tuple[str, ...] -"""Mélodie : une walking bass blues de boogie-woogie à 12 mesures.""" +"""Melody: a boogie-woogie 12-bar blues walking bass.""" + BIRTHDAY: Tuple[str, ...] -"""Mélodie : « Joyeux anniversaire…» +"""Melody: “Happy Birthday to You…” For copyright status see: http://www.bbc.co.uk/news/world-us-canada-34332853 """ + WEDDING: Tuple[str, ...] -"""Mélodie : la marche nuptiale de l'opéra "Lohengrin" de Wagner.""" +"""Melody: the bridal chorus from Wagner’s opera “Lohengrin”.""" + FUNERAL: Tuple[str, ...] -"""Mélodie : la "marche funèbre " aussi connue sous le nom de Sonate pour piano n° 2 en B♭ mineur, opus 35 de Frédéric Chopin.""" +"""Melody: the “funeral march” otherwise known as Frédéric Chopin’s Piano Sonata No. 2 in B♭ minor, Op. 35.""" + PUNCHLINE: Tuple[str, ...] -"""Mélodie : un extrait amusant qui signifie qu'une blague a été faite.""" +"""Melody: a fun fragment that signifies a joke has been made.""" + PYTHON: Tuple[str, ...] -"""Mélodie : La marche "Liberty Bell" de John Philip Sousa, alias le thème du "Monty Python's Flying Circus" (qui a donné son nom au langage de programmation Python).""" +"""Melody: John Philip Sousa’s march “Liberty Bell” aka, the theme for “Monty Python’s Flying Circus” (after which the Python programming language is named).""" + BADDY: Tuple[str, ...] -"""Mélodie\xa0: entrée d'un méchant à l'époque des films muets.""" +"""Melody: silent movie era entrance of a baddy.""" + CHASE: Tuple[str, ...] -"""Mélodie : scène de poursuite à l'époque du film muet.""" +"""Melody: silent movie era chase scene.""" + BA_DING: Tuple[str, ...] -"""Mélodie : un signal court pour indiquer que quelque chose s'est produit.""" +"""Melody: a short signal to indicate something has happened.""" + WAWAWAWAA: Tuple[str, ...] -"""Mélodie : un trombone très triste.""" +"""Melody: a very sad trombone.""" + JUMP_UP: Tuple[str, ...] -"""Mélodie\xa0: pour une utilisation dans un jeu, indiquant un mouvement vers le haut.""" +"""Melody: for use in a game, indicating upward movement.""" + JUMP_DOWN: Tuple[str, ...] -"""Mélodie\xa0: pour une utilisation dans un jeu, indiquant un mouvement vers le bas.""" +"""Melody: for use in a game, indicating downward movement.""" + POWER_UP: Tuple[str, ...] -"""Mélodie : une fanfare pour indiquer un succès débloqué.""" +"""Melody: a fanfare to indicate an achievement unlocked.""" + POWER_DOWN: Tuple[str, ...] -"""Mélodie : une fanfare triste pour indiquer un succès manqué.""" +"""Melody: a sad fanfare to indicate an achievement lost.""" -def set_tempo(ticks: int=4, bpm: int=120) -> None: - """Définir le tempo approximatif pour la lecture. +def set_tempo(ticks: int = 4, bpm: int = 120) -> None: + """Sets the approximate tempo for playback. -Example: ``music.set_tempo(bpm=120)`` + Example: ``music.set_tempo(bpm=120)`` -:param ticks: Le nombre de ticks constituant un battement. -:param bpm: Un entier déterminant le nombre de battements par minute. + :param ticks: The number of ticks constituting a beat. + :param bpm: An integer determining how many beats per minute. -Suggested default values allow the following useful behaviour: + Suggested default values allow the following useful behaviour: -- music.set_tempo() – reset the tempo to default of ticks = 4, bpm = 120 -- music.set_tempo(ticks=8) – change the “definition” of a beat -- music.set_tempo(bpm=180) – just change the tempo + - music.set_tempo() – reset the tempo to default of ticks = 4, bpm = 120 + - music.set_tempo(ticks=8) – change the “definition” of a beat + - music.set_tempo(bpm=180) – just change the tempo -To work out the length of a tick in milliseconds is very simple arithmetic: -60000/bpm/ticks_per_beat. For the default values that’s -60000/120/4 = 125 milliseconds or 1 beat = 500 milliseconds.""" + To work out the length of a tick in milliseconds is very simple arithmetic: + 60000/bpm/ticks_per_beat. For the default values that’s + 60000/120/4 = 125 milliseconds or 1 beat = 500 milliseconds. + """ ... def get_tempo() -> Tuple[int, int]: - """Récupérer le tempo actuel sous la forme d'un tuple d'entiers : ``(ticks, bpm)``. + """Gets the current tempo as a tuple of integers: ``(ticks, bpm)``. -Example: ``ticks, beats = music.get_tempo()`` + Example: ``ticks, beats = music.get_tempo()`` -:return: The temp as a tuple with two integer values, the ticks then the beats per minute.""" + :return: The temp as a tuple with two integer values, the ticks then the beats per minute. + """ ... -def play(music: Union[str, List[str], Tuple[str, ...]], pin: Optional[MicroBitDigitalPin]=pin0, wait: bool=True, loop: bool=False) -> None: - """Jouer de la musique. +def play( + music: Union[str, List[str], Tuple[str, ...]], + pin: Optional[MicroBitDigitalPin] = pin0, + wait: bool = True, + loop: bool = False, +) -> None: + """Plays music. -Example: ``music.play(music.NYAN)`` + Example: ``music.play(music.NYAN)`` -:param music: musique spécifiée dans `une notation spéciale `_ -:param pin: (broche) la broche de sortie à utiliser avec un haut-parleur externe (par défaut ``pin0``), ``None`` pour aucun son. -:param wait: Si ``wait`` est défini à ``True``, cette fonction est bloquante. -:param loop: Si ``loop`` est défini à ``True``, la mélodie se répète jusqu'à ce que ``stop`` soit appelé, ou que l'appel bloquant soit interrompu. + :param music: music specified in `a special notation `_ + :param pin: the output pin for use with an external speaker (default ``pin0``), ``None`` for no sound. + :param wait: If ``wait`` is set to ``True``, this function is blocking. + :param loop: If ``loop`` is set to ``True``, the tune repeats until ``stop`` is called or the blocking call is interrupted. -Many built-in melodies are defined in this module.""" + Many built-in melodies are defined in this module. + """ ... -def pitch(frequency: int, duration: int=-1, pin: Optional[MicroBitDigitalPin]=pin0, wait: bool=True) -> None: - """Jouer une note. (tangage) +def pitch( + frequency: int, + duration: int = -1, + pin: Optional[MicroBitDigitalPin] = pin0, + wait: bool = True, +) -> None: + """Play a note. -Example: ``music.pitch(185, 1000)`` + Example: ``music.pitch(185, 1000)`` -:param frequency: (fréquence) Une fréquence entière -:param duration: Une durée en milliseconde. Si la valeur est négative alors le son sera continu jusqu'au prochain appel, ou jusqu'à un appel à ``stop``. -:param pin: (broche) Broche de sortie optionnelle (par défaut ``pin0``). -:param wait: Si ``wait`` est défini à ``True``, cette fonction est bloquante. + :param frequency: An integer frequency + :param duration: A millisecond duration. If negative then sound is continuous until the next call or a call to ``stop``. + :param pin: Optional output pin (default ``pin0``). + :param wait: If ``wait`` is set to ``True``, this function is blocking. -For example, if the frequency is set to 440 and the length to -1000 then we hear a standard concert A for one second. + For example, if the frequency is set to 440 and the length to + 1000 then we hear a standard concert A for one second. -You can only play one pitch on one pin at any one time.""" + You can only play one pitch on one pin at any one time. + """ ... -def stop(pin: Optional[MicroBitDigitalPin]=pin0) -> None: - """Met fin à toute lecture de musique sur le haut-parleur intégré et à tout son en sortie sur la broche. +def stop(pin: Optional[MicroBitDigitalPin] = pin0) -> None: + """Stops all music playback on the built-in speaker and any pin outputting sound. -Example: ``music.stop()`` + Example: ``music.stop()`` -:param pin: (broche) Un argument optionnel peut être spécifié pour indiquer une broche, par exemple ``music.stop(pin1)``.""" + :param pin: An optional argument can be provided to specify a pin, e.g. ``music.stop(pin1)``. + """ def reset() -> None: - """Réinitialiser les ticks, bpm, durée et octave à leurs valeurs par défaut. + """Resets ticks, bpm, duration and octave to their default values. -Example: ``music.reset()`` + Example: ``music.reset()`` -Values: -- ``ticks = 4`` -- ``bpm = 120`` -- ``duration = 4`` -- ``octave = 4``""" - ... \ No newline at end of file + Values: + - ``ticks = 4`` + - ``bpm = 120`` + - ``duration = 4`` + - ``octave = 4`` + """ + ... diff --git a/lang/fr/typeshed/stdlib/neopixel.pyi b/lang/fr/typeshed/stdlib/neopixel.pyi index cbe90e5..2d5a749 100644 --- a/lang/fr/typeshed/stdlib/neopixel.pyi +++ b/lang/fr/typeshed/stdlib/neopixel.pyi @@ -1,81 +1,82 @@ -"""Bandes LED RGB et RGBW individuellement adressables.""" +"""Individually addressable RGB and RGBW LED strips. +""" from .microbit import MicroBitDigitalPin from typing import Tuple class NeoPixel: + def __init__(self, pin: MicroBitDigitalPin, n: int, bpp: int = 3) -> None: + """Initialise a new strip of neopixel LEDs controlled via a pin. - def __init__(self, pin: MicroBitDigitalPin, n: int, bpp: int=3) -> None: - """Initialiser une nouvelle bande de LEDs neopixel contrôlée via une broche. + Example: ``np = neopixel.NeoPixel(pin0, 8)`` -Example: ``np = neopixel.NeoPixel(pin0, 8)`` + To support RGBW neopixels, a third argument can be passed to + ``NeoPixel`` to indicate the number of bytes per pixel (``bpp``). + For RGBW, this is is 4 rather than the default of 3 for RGB and GRB. -To support RGBW neopixels, a third argument can be passed to -``NeoPixel`` to indicate the number of bytes per pixel (``bpp``). -For RGBW, this is is 4 rather than the default of 3 for RGB and GRB. + Each pixel is addressed by a position (starting from 0). Neopixels are + given RGB (red, green, blue) / RGBW (red, green, blue, white) values + between 0-255 as a tuple. For example, in RGB, ``(255,255,255)`` is + white. In RGBW, ``(255,255,255,0)`` or ``(0,0,0,255)`` is white. -Each pixel is addressed by a position (starting from 0). Neopixels are -given RGB (red, green, blue) / RGBW (red, green, blue, white) values -between 0-255 as a tuple. For example, in RGB, ``(255,255,255)`` is -white. In RGBW, ``(255,255,255,0)`` or ``(0,0,0,255)`` is white. + See `the online docs `_ for warnings and other advice. -See `the online docs `_ for warnings and other advice. - -:param pin: (broche) La broche qui contrôle la bande neopixel. -:param n: Le nombre de neopixels sur la bande. -:param bpp: Octets par pixel. Pour le support du neopixel RGBW, passez 4 plutôt que la valeur par défaut 3 pour RGB et GRB.""" + :param pin: The pin controlling the neopixel strip. + :param n: The number of neopixels in the strip. + :param bpp: Bytes per pixel. For RGBW neopixel support, pass 4 rather than the default of 3 for RGB and GRB. + """ ... - def clear(self) -> None: - """Effacer tous les pixels. + """Clear all the pixels. -Example: ``np.clear()``""" + Example: ``np.clear()`` + """ ... - def show(self) -> None: - """Afficher les pixels. + """Show the pixels. -Example: ``np.show()`` + Example: ``np.show()`` -Must be called for any updates to become visible.""" + Must be called for any updates to become visible. + """ ... - def write(self) -> None: - """Afficher les pixels (micro:bit V2 uniquement). + """Show the pixels (micro:bit V2 only). -Example: ``np.write()`` + Example: ``np.write()`` -Must be called for any updates to become visible. + Must be called for any updates to become visible. -Equivalent to ``show``.""" + Equivalent to ``show``. + """ ... - def fill(self, colour: Tuple[int, ...]) -> None: - """Colorer tous les pixels d'une valeur RGB/RGBW donnée (micro:bit V2 uniquement). + """Colour all pixels a given RGB/RGBW value (micro:bit V2 only). -Example: ``np.fill((0, 0, 255))`` + Example: ``np.fill((0, 0, 255))`` -:param colour: Un tuple de la même longueur que le nombre d'octets par pixel (bpp). + :param colour: A tuple of the same length as the number of bytes per pixel (bpp). -Use in conjunction with ``show()`` to update the neopixels.""" + Use in conjunction with ``show()`` to update the neopixels. + """ ... - def __setitem__(self, key: int, value: Tuple[int, ...]) -> None: - """Définit une couleur de pixel. + """Set a pixel colour. -Example: ``np[0] = (255, 0, 0)`` - -:param key: Le numéro du pixel -:param value: La couleur.""" + Example: ``np[0] = (255, 0, 0)`` + :param key: The pixel number. + :param value: The colour. + """ def __getitem__(self, key: int) -> Tuple[int, ...]: - """Récupère la couleur d'un pixel - -Example: ``r, g, b = np[0]`` + """Get a pixel colour. -:param key: Le numéro du pixel -:return: The colour tuple.""" + Example: ``r, g, b = np[0]`` + :param key: The pixel number. + :return: The colour tuple. + """ def __len__(self) -> int: - """Récupère la longueur de cette bande de pixels. + """Get length of this pixel strip. -Example: ``len(np)``""" \ No newline at end of file + Example: ``len(np)`` + """ diff --git a/lang/fr/typeshed/stdlib/os.pyi b/lang/fr/typeshed/stdlib/os.pyi index 091695a..2f2db77 100644 --- a/lang/fr/typeshed/stdlib/os.pyi +++ b/lang/fr/typeshed/stdlib/os.pyi @@ -1,63 +1,73 @@ -"""Accéder au système de fichiers.""" +"""Access the file system. +""" + from typing import Tuple from typing import List def listdir() -> List[str]: - """Lister les fichiers. + """List files. -Example: ``os.listdir()`` + Example: ``os.listdir()`` -:return: A list of the names of all the files contained within the local -persistent on-device file system.""" + :return: A list of the names of all the files contained within the local + persistent on-device file system. + """ ... def remove(filename: str) -> None: - """Supprimer (effacer) un fichier. + """Remove (delete) a file. -Example: ``os.remove('data.txt')`` + Example: ``os.remove('data.txt')`` -:param filename: Le fichier à effacer. + :param filename: The file to delete. -If the file does not exist an ``OSError`` exception will occur.""" + If the file does not exist an ``OSError`` exception will occur. + """ ... def size(filename: str) -> int: - """Retourne la taille d'un fichier. + """Returns the size of a file. -Example: ``os.size('data.txt')`` + Example: ``os.size('data.txt')`` -:param filename: Le fichier -:return: The size in bytes. + :param filename: The file + :return: The size in bytes. -If the file does not exist an ``OSError`` exception will occur.""" + If the file does not exist an ``OSError`` exception will occur. + """ class uname_result(Tuple[str, str, str, str, str]): - """Résultat de ``os.uname()``""" + """Result of ``os.uname()``""" sysname: str - """Nom du système d'exploitation.""" + """Operating system name.""" + nodename: str - """Nom de la machine sur le réseau (selon implémentation).""" + """Name of machine on network (implementation-defined).""" + release: str - """La release du système d'exploitation""" + """Operating system release.""" + version: str - """Version du système d'exploitation""" + """Operating system version.""" + machine: str - """Identifiant matériel.""" + """Hardware identifier.""" def uname() -> uname_result: - """Retourne les informations identifiant le système d'exploitation actuel. + """Returns information identifying the current operating system. -Example: ``os.uname()`` + Example: ``os.uname()`` -The return value is an object with five attributes: + The return value is an object with five attributes: -- ``sysname`` - operating system name -- ``nodename`` - name of machine on network (implementation-defined) -- ``release`` - operating system release -- ``version`` - operating system version -- ``machine`` - hardware identifier + - ``sysname`` - operating system name + - ``nodename`` - name of machine on network (implementation-defined) + - ``release`` - operating system release + - ``version`` - operating system version + - ``machine`` - hardware identifier -There is no underlying operating system in MicroPython. As a result the -information returned by the ``uname`` function is mostly useful for -versioning details.""" - ... \ No newline at end of file + There is no underlying operating system in MicroPython. As a result the + information returned by the ``uname`` function is mostly useful for + versioning details. + """ + ... diff --git a/lang/fr/typeshed/stdlib/radio.pyi b/lang/fr/typeshed/stdlib/radio.pyi index 256533d..8dd0267 100644 --- a/lang/fr/typeshed/stdlib/radio.pyi +++ b/lang/fr/typeshed/stdlib/radio.pyi @@ -1,130 +1,152 @@ -"""Communiquer entre micro:bits avec la radio intégrée.""" +"""Communicate between micro:bits with the built-in radio. +""" + from _typeshed import WriteableBuffer from typing import Optional, Tuple + RATE_1MBIT: int -"""Constante utilisée pour indiquer un débit de 1 MBit par seconde.""" +"""Constant used to indicate a throughput of 1 MBit a second.""" + RATE_2MBIT: int -"""Constante utilisée pour indiquer un débit de 2 MBit par seconde.""" +"""Constant used to indicate a throughput of 2 MBit a second.""" def on() -> None: - """Allume la radio. + """Turns the radio on. -Example: ``radio.on()`` + Example: ``radio.on()`` -This needs to be explicitly called since the radio draws power and takes -up memory that you may otherwise need.""" + This needs to be explicitly called since the radio draws power and takes + up memory that you may otherwise need. + """ ... def off() -> None: - """Désactive la radio, économisant ainsi de l'énergie et de la mémoire. + """Turns off the radio, saving power and memory. -Example: ``radio.off()``""" + Example: ``radio.off()`` + """ ... -def config(length: int=32, queue: int=3, channel: int=7, power: int=6, address: int=1969383796, group: int=0, data_rate: int=RATE_1MBIT) -> None: - """Configure la radio. - -Example: ``radio.config(group=42)`` - -The default configuration is suitable for most use. - -:param length: (par défaut=32) définit la longueur maximale en octets d'un message envoyé via la radio. -Il peut faire jusqu'à 251 octets de long (254 - 3 octets pour S0, LENGTH et préambule S1). -:param queue: (par défaut=3) spécifie le nombre de messages qui peuvent être stockés dans la file d'attente des messages entrants. -S'il n'y a plus de place dans la file d'attente des messages entrants, alors le message entrant est abandonné. -:param channel: (par défaut=7) une valeur entière comprise entre 0 et 83 (y compris) qui définit un « canal » arbitraire sur lequel la radio est réglée. -Les messages seront envoyés via ce canal et seuls les messages reçus via ce canal seront placés dans la file d'attente des messages entrants. Chaque incrément est de 1 MHz de largeur, basé à 2400 MHz. -:param power: (par défaut=6) est une valeur entière comprise entre 0 et 7 (y compris) pour indiquer la force du signal utilisé lors de la diffusion d'un message. -Plus la valeur est élevée, plus le signal est fort, mais plus les besoins en alimentation sont élevés. La numérotation se traduit par des positions dans la liste suivante de valeurs en dBm (décibel milliwatt) : -30, -20, -16, -12, -8, -4, 0, 4. -:param address: (par défaut=0x75626974) un nom arbitraire, exprimé sous la forme d'une adresse 32-bit, utilisé pour filtrer au niveau matériel les paquet entrants, seuls les paquets correspondant à l'adresse définie seront conservés. -La valeur par défaut utilisée par d'autres plateformes liées au micro:bit est celle indiquée ici. -:param group: (par défaut=0) une valeur de 8 bits (0-255) utilisée avec ``address`` lors du filtrage des messages. -Conceptuellement, "adress" est comme l'adresse d'une maison ou d'un bureau, et "group" est comme la personne à laquelle vous voulez envoyer votre message. -:param data_rate: (par défaut=``radio.RATE_1MBIT``) indique la vitesse à laquelle le débit de données a lieu. -Peut être une des constantes suivantes définies dans le module ``radio``\xa0: ``RATE_250KBIT``, ``RATE_1MBIT`` ou ``RATE_2MBIT``. - -If ``config`` is not called then the defaults described above are assumed.""" +def config( + length: int = 32, + queue: int = 3, + channel: int = 7, + power: int = 6, + address: int = 0x75626974, + group: int = 0, + data_rate: int = RATE_1MBIT, +) -> None: + """Configures the radio. + + Example: ``radio.config(group=42)`` + + The default configuration is suitable for most use. + + :param length: (default=32) defines the maximum length, in bytes, of a message sent via the radio. + It can be up to 251 bytes long (254 - 3 bytes for S0, LENGTH and S1 preamble). + :param queue: (default=3) specifies the number of messages that can be stored on the incoming message queue. + If there are no spaces left on the queue for incoming messages, then the incoming message is dropped. + :param channel: (default=7) an integer value from 0 to 83 (inclusive) that defines an arbitrary "channel" to which the radio is tuned. + Messages will be sent via this channel and only messages received via this channel will be put onto the incoming message queue. Each step is 1MHz wide, based at 2400MHz. + :param power: (default=6) is an integer value from 0 to 7 (inclusive) to indicate the strength of signal used when broadcasting a message. + The higher the value the stronger the signal, but the more power is consumed by the device. The numbering translates to positions in the following list of dBm (decibel milliwatt) values: -30, -20, -16, -12, -8, -4, 0, 4. + :param address: (default=0x75626974) an arbitrary name, expressed as a 32-bit address, that's used to filter incoming packets at the hardware level, keeping only those that match the address you set. + The default used by other micro:bit related platforms is the default setting used here. + :param group: (default=0) an 8-bit value (0-255) used with the ``address`` when filtering messages. + Conceptually, "address" is like a house/office address and "group" is like the person at that address to which you want to send your message. + :param data_rate: (default=``radio.RATE_1MBIT``) indicates the speed at which data throughput takes place. + Can be one of the following constants defined in the ``radio`` module: ``RATE_250KBIT``, ``RATE_1MBIT`` or ``RATE_2MBIT``. + + If ``config`` is not called then the defaults described above are assumed. + """ ... def reset() -> None: - """Réinitialiser les paramètres à leurs valeurs par défaut. + """Reset the settings to their default values. -Example: ``radio.reset()`` + Example: ``radio.reset()`` -The defaults as as per the ``config`` function above.""" + The defaults as as per the ``config`` function above. + """ ... def send_bytes(message: bytes) -> None: - """Envoie un message contenant des octets. + """Sends a message containing bytes. -Example: ``radio.send_bytes(b'hello')`` + Example: ``radio.send_bytes(b'hello')`` -:param message: Les octets à envoyer.""" + :param message: The bytes to send. + """ ... def receive_bytes() -> Optional[bytes]: - """Recevoir le message entrant suivant dans la file d'attente des messages. + """Receive the next incoming message on the message queue. -Example: ``radio.receive_bytes()`` + Example: ``radio.receive_bytes()`` -:return: The message bytes if any, otherwise ``None``.""" + :return: The message bytes if any, otherwise ``None``. + """ ... def receive_bytes_into(buffer: WriteableBuffer) -> Optional[int]: - """Copier le message entrant suivant de la file d'attente des messages vers un buffer. + """Copy the next incoming message on the message queue into a buffer. -Example: ``radio.receive_bytes_info(buffer)`` + Example: ``radio.receive_bytes_info(buffer)`` -:param buffer: Le buffer cible. Le message est tronqué s'il est plus grand que le buffer. -:return: ``None`` if there are no pending messages, otherwise it returns the length of the message (which might be more than the length of the buffer).""" + :param buffer: The target buffer. The message is truncated if larger than the buffer. + :return: ``None`` if there are no pending messages, otherwise it returns the length of the message (which might be more than the length of the buffer). + """ ... def send(message: str) -> None: - """Envoie un message avec une chaîne de caractères. + """Sends a message string. -Example: ``radio.send('hello')`` + Example: ``radio.send('hello')`` -This is the equivalent of ``radio.send_bytes(bytes(message, 'utf8'))`` but with ``b'\x01\x00\x01'`` -prepended to the front (to make it compatible with other platforms that target the micro:bit). + This is the equivalent of ``radio.send_bytes(bytes(message, 'utf8'))`` but with ``b'\x01\x00\x01'`` + prepended to the front (to make it compatible with other platforms that target the micro:bit). -:param message: Le texte à envoyer.""" + :param message: The string to send. + """ ... def receive() -> Optional[str]: - """Fonctionne exactement de la même manière que ``receive_bytes`` mais retourne ce qui a été envoyé. + """Works in exactly the same way as ``receive_bytes`` but returns whatever was sent. -Example: ``radio.receive()`` + Example: ``radio.receive()`` -Equivalent to ``str(receive_bytes(), 'utf8')`` but with a check that the the first -three bytes are ``b'\x01\x00\x01'`` (to make it compatible with other platforms that -may target the micro:bit). + Equivalent to ``str(receive_bytes(), 'utf8')`` but with a check that the the first + three bytes are ``b'\x01\x00\x01'`` (to make it compatible with other platforms that + may target the micro:bit). -:return: The message with the prepended bytes stripped and converted to a string. + :return: The message with the prepended bytes stripped and converted to a string. -A ``ValueError`` exception is raised if conversion to string fails.""" + A ``ValueError`` exception is raised if conversion to string fails. + """ ... def receive_full() -> Optional[Tuple[bytes, int, int]]: - """Retourne un tuple contenant trois valeurs qui représentent le prochain message entrant dans la file d'attente. + """Returns a tuple containing three values representing the next incoming message on the message queue. -Example: ``radio.receive_full()`` + Example: ``radio.receive_full()`` -If there are no pending messages then ``None`` is returned. + If there are no pending messages then ``None`` is returned. -The three values in the tuple represent: + The three values in the tuple represent: -- the next incoming message on the message queue as bytes. -- the RSSI (signal strength): a value between 0 (strongest) and -255 (weakest) as measured in dBm. -- a microsecond timestamp: the value returned by ``time.ticks_us()`` when the message was received. + - the next incoming message on the message queue as bytes. + - the RSSI (signal strength): a value between 0 (strongest) and -255 (weakest) as measured in dBm. + - a microsecond timestamp: the value returned by ``time.ticks_us()`` when the message was received. -For example:: + For example:: - details = radio.receive_full() - if details: - msg, rssi, timestamp = details + details = radio.receive_full() + if details: + msg, rssi, timestamp = details -This function is useful for providing information needed for triangulation -and/or trilateration with other micro:bit devices. + This function is useful for providing information needed for triangulation + and/or trilateration with other micro:bit devices. -:return: ``None`` if there is no message, otherwise a tuple of length three with the bytes, strength and timestamp values.""" - ... \ No newline at end of file + :return: ``None`` if there is no message, otherwise a tuple of length three with the bytes, strength and timestamp values. + """ + ... diff --git a/lang/fr/typeshed/stdlib/random.pyi b/lang/fr/typeshed/stdlib/random.pyi index ffd86c1..a2c2ef3 100644 --- a/lang/fr/typeshed/stdlib/random.pyi +++ b/lang/fr/typeshed/stdlib/random.pyi @@ -1,80 +1,93 @@ -"""Générer des nombres aléatoires.""" +"""Generate random numbers. +""" from typing import TypeVar, Sequence, Union, overload def getrandbits(n: int) -> int: - """Générer un entier avec ``n`` bits aléatoires. + """Generate an integer with ``n`` random bits. -Example: ``random.getrandbits(1)`` + Example: ``random.getrandbits(1)`` -:param n: Une valeur comprise entre 1-30 (inclus).""" + :param n: A value between 1-30 (inclusive). + """ ... def seed(n: int) -> None: - """Initialiser le générateur de nombres aléatoires. + """Initialize the random number generator. -Example: ``random.seed(0)`` + Example: ``random.seed(0)`` -:param n: La graine aléatoire + :param n: The integer seed -This will give you reproducibly deterministic randomness from a given starting -state (``n``).""" + This will give you reproducibly deterministic randomness from a given starting + state (``n``). + """ ... def randint(a: int, b: int) -> int: - """Choisir un entier aléatoire entre ``a`` et ``b`` inclus. + """Choose a random integer between ``a`` and ``b`` inclusive. -Example: ``random.randint(0, 9)`` + Example: ``random.randint(0, 9)`` -:param a: Valeur de départ pour l'intervalle (inclus) -:param b: Valeur de fin pour l'intervalle (inclus) + :param a: Start value for the range (inclusive) + :param b: End value for the range (inclusive) -Alias for ``randrange(a, b + 1)``.""" + Alias for ``randrange(a, b + 1)``. + """ ... @overload def randrange(stop: int) -> int: - """Choisir un entier aléatoirement entre zéro et ``stop`` (mais sans inclure ce dernier). + """Choose a randomly selected integer between zero and up to (but not + including) ``stop``. -Example: ``random.randrange(10)`` + Example: ``random.randrange(10)`` -:param stop: Valeur de fin pour l'intervalle (exclusif)""" + :param stop: End value for the range (exclusive) + """ ... @overload -def randrange(start: int, stop: int, step: int=1) -> int: - """Choisir un élément sélectionné aléatoirement dans ``range(start, stop, step)``. +def randrange(start: int, stop: int, step: int = 1) -> int: + """ + Choose a randomly selected element from ``range(start, stop, step)``. -Example: ``random.randrange(0, 10)`` + Example: ``random.randrange(0, 10)`` -:param start: Le début de la plage (inclus) -:param stop: La fin de l'intervalle (exclusif) -:param step: L'incrément.""" + :param start: The start of the range (inclusive) + :param stop: The end of the range (exclusive) + :param step: The step. + """ ... -_T = TypeVar('_T') + +_T = TypeVar("_T") def choice(seq: Sequence[_T]) -> _T: - """Choisir un élément aléatoire dans la séquence non vide ``seq``. + """Choose a random element from the non-empty sequence ``seq``. -Example: ``random.choice([Image.HAPPY, Image.SAD])`` + Example: ``random.choice([Image.HAPPY, Image.SAD])`` -:param seq: Une séquence. + :param seq: A sequence. -If ``seq`` is empty, raises ``IndexError``.""" + If ``seq`` is empty, raises ``IndexError``. + """ ... def random() -> float: - """Générer un nombre aléatoire à virgule flottante [0.0, 1.0). + """Generate a random floating point number in the range [0.0, 1.0). -Example: ``random.random()`` + Example: ``random.random()`` -:return: The random floating point number""" + :return: The random floating point number + """ ... def uniform(a: float, b: float) -> float: - """Renvoie un nombre aléatoire à virgule flottante entre ``a`` et ``b`` inclus. + """ + Return a random floating point number between ``a`` and ``b`` inclusive. -Example: ``random.uniform(0, 9)`` + Example: ``random.uniform(0, 9)`` -:param a: Valeur de départ pour l'intervalle (inclus) -:param b: Valeur de fin pour l'intervalle (inclus)""" - ... \ No newline at end of file + :param a: Start value for the range (inclusive) + :param b: End value for the range (inclusive) + """ + ... diff --git a/lang/fr/typeshed/stdlib/speech.pyi b/lang/fr/typeshed/stdlib/speech.pyi index 5a9ac34..349d188 100644 --- a/lang/fr/typeshed/stdlib/speech.pyi +++ b/lang/fr/typeshed/stdlib/speech.pyi @@ -1,79 +1,106 @@ -"""Faites parler ou chanter le micro:bit, ainsi que d'autres sons liés à la parole.""" +"""Make the micro:bit talk, sing and make other speech like sounds. +""" + from typing import Optional from .microbit import MicroBitDigitalPin, pin0 def translate(words: str) -> str: - """Traduire les mots anglais en phonèmes. + """Translate English words to phonemes. -Example: ``speech.translate('hello world')`` + Example: ``speech.translate('hello world')`` -:param words: Une chaîne de caractères de mots anglais. -:return: A string containing a best guess at the appropriate phonemes to pronounce. -The output is generated from this `text to phoneme translation table `_. + :param words: A string of English words. + :return: A string containing a best guess at the appropriate phonemes to pronounce. + The output is generated from this `text to phoneme translation table `_. -This function should be used to generate a first approximation of phonemes -that can be further hand-edited to improve accuracy, inflection and -emphasis. + This function should be used to generate a first approximation of phonemes + that can be further hand-edited to improve accuracy, inflection and + emphasis. -See `the online documentation `_ for detailed information.""" + See `the online documentation `_ for detailed information. + """ ... -def pronounce(phonemes: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: Optional[MicroBitDigitalPin]=pin0) -> None: - """Prononcer les phonèmes. - -Example: ``speech.pronounce(' /HEHLOW WERLD')`` - -:param phonemes: La chaîne de phonèmes à prononcer -:param pitch: (tangage) Un nombre représentant le ton de la voix -:param speed: Un nombre représentant la vitesse de la voix -:param mouth: Un nombre représentant la bouche de la voix -:param throat: Un nombre représentant la gorge de la voix -:param pin: (broche) Argument optionnel pour spécifier la broche de sortie. Peut être utilisé pour remplacer la valeur par défaut de ``pin0``. -Pour empêcher l'émission d'un son via les broches, il est possible d'utiliser ``pin=None``. micro:bit V2 seulement. - -Override the optional pitch, speed, mouth and throat settings to change the -timbre (quality) of the voice. - -See `the online documentation `_ for detailed information.""" +def pronounce( + phonemes: str, + pitch: int = 64, + speed: int = 72, + mouth: int = 128, + throat: int = 128, + pin: Optional[MicroBitDigitalPin] = pin0, +) -> None: + """Pronounce phonemes. + + Example: ``speech.pronounce(' /HEHLOW WERLD')`` + + :param phonemes: The string of phonemes to pronounce + :param pitch: A number representing the pitch of the voice + :param speed: A number representing the speed of the voice + :param mouth: A number representing the mouth of the voice + :param throat: A number representing the throat of the voice + :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. + If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. + + Override the optional pitch, speed, mouth and throat settings to change the + timbre (quality) of the voice. + + See `the online documentation `_ for detailed information. + """ ... -def say(words: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: MicroBitDigitalPin=pin0) -> None: - """Dire des mots anglais. - -Example: ``speech.say('hello world')`` - -:param words: La chaîne de mots à dire. -:param pitch: (tangage) Un nombre représentant le ton de la voix -:param speed: Un nombre représentant la vitesse de la voix -:param mouth: Un nombre représentant la bouche de la voix -:param throat: Un nombre représentant la gorge de la voix -:param pin: (broche) Argument optionnel pour spécifier la broche de sortie. Peut être utilisé pour remplacer la valeur par défaut de ``pin0``. -Pour empêcher l'émission d'un son via les broches, il est possible d'utiliser ``pin=None``. micro:bit V2 seulement. - -The result is semi-accurate for English. Override the optional pitch, speed, -mouth and throat settings to change the timbre (quality) of the voice. - -This is a short-hand equivalent of: -``speech.pronounce(speech.translate(words))`` - -See `the online documentation `_ for detailed information.""" +def say( + words: str, + pitch: int = 64, + speed: int = 72, + mouth: int = 128, + throat: int = 128, + pin: MicroBitDigitalPin = pin0, +) -> None: + """Say English words. + + Example: ``speech.say('hello world')`` + + :param words: The string of words to say. + :param pitch: A number representing the pitch of the voice + :param speed: A number representing the speed of the voice + :param mouth: A number representing the mouth of the voice + :param throat: A number representing the throat of the voice + :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. + If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. + + The result is semi-accurate for English. Override the optional pitch, speed, + mouth and throat settings to change the timbre (quality) of the voice. + + This is a short-hand equivalent of: + ``speech.pronounce(speech.translate(words))`` + + See `the online documentation `_ for detailed information. + """ ... -def sing(phonemes: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: MicroBitDigitalPin=pin0) -> None: - """Chanter des phonèmes. - -Example: ``speech.sing(' /HEHLOW WERLD')`` - -:param phonemes: La chaîne de mots à chanter. -:param pitch: (tangage) Un nombre représentant le ton de la voix -:param speed: Un nombre représentant la vitesse de la voix -:param mouth: Un nombre représentant la bouche de la voix -:param throat: Un nombre représentant la gorge de la voix -:param pin: (broche) Argument optionnel pour spécifier la broche de sortie. Peut être utilisé pour remplacer la valeur par défaut de ``pin0``. -Pour empêcher l'émission d'un son via les broches, il est possible d'utiliser ``pin=None``. micro:bit V2 seulement. - -Override the optional pitch, speed, mouth and throat settings to change -the timbre (quality) of the voice. - -See `the online documentation `_ for detailed information.""" - ... \ No newline at end of file +def sing( + phonemes: str, + pitch: int = 64, + speed: int = 72, + mouth: int = 128, + throat: int = 128, + pin: MicroBitDigitalPin = pin0, +) -> None: + """Sing phonemes. + + Example: ``speech.sing(' /HEHLOW WERLD')`` + + :param phonemes: The string of words to sing. + :param pitch: A number representing the pitch of the voice + :param speed: A number representing the speed of the voice + :param mouth: A number representing the mouth of the voice + :param throat: A number representing the throat of the voice + :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. + If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. + + Override the optional pitch, speed, mouth and throat settings to change + the timbre (quality) of the voice. + + See `the online documentation `_ for detailed information. + """ + ... diff --git a/lang/fr/typeshed/stdlib/struct.pyi b/lang/fr/typeshed/stdlib/struct.pyi index efffeb6..53b3e0b 100644 --- a/lang/fr/typeshed/stdlib/struct.pyi +++ b/lang/fr/typeshed/stdlib/struct.pyi @@ -1,56 +1,65 @@ -"""Rassembler et désassembler des types de données primitives.""" +"""Pack and unpack primitive data types. +""" + from _typeshed import ReadableBuffer, WriteableBuffer from typing import Any, Tuple, Union def calcsize(fmt: str) -> int: - """Récupère le nombre d'octets nécessaires pour stocker le ``fmt`` donné. + """Get the number of bytes needed to store the given ``fmt``. -Example: ``struct.calcsize('hf')`` + Example: ``struct.calcsize('hf')`` -:param fmt: Une chaîne de mise en forme. -:return The number of bytes needed to store such a value.""" + :param fmt: A format string. + :return The number of bytes needed to store such a value. + """ ... def pack(fmt: str, v1: Any, *vn: Any) -> bytes: - """Rassembler les valeurs selon une chaîne de mise en forme. + """Pack values according to a format string. -Example: ``struct.pack('hf', 1, 3.1415)`` + Example: ``struct.pack('hf', 1, 3.1415)`` -:param fmt: La chaîne de mise en forme. -:param v1: La première valeur. -:param *vn: Les valeurs restantes. -:return A bytes object encoding the values.""" + :param fmt: The format string. + :param v1: The first value. + :param *vn: The remaining values. + :return A bytes object encoding the values. + """ ... -def pack_into(fmt: str, buffer: WriteableBuffer, offset: int, v1: Any, *vn: Any) -> None: - """Rassembler les valeurs selon une chaîne de format. (Rassembler dans) +def pack_into( + fmt: str, buffer: WriteableBuffer, offset: int, v1: Any, *vn: Any +) -> None: + """Pack values according to a format string. -Example: ``struct.pack_info('hf', buffer, 1, 3.1415)`` + Example: ``struct.pack_info('hf', buffer, 1, 3.1415)`` -:param fmt: La chaîne de format. -:param buffer: Le tampon cible dans lequel écrire. -:param offset: Le décalage dans le tampon. Peut être négatif pour compter à partir de la fin du tampon. -:param v1: La première valeur. -:param *vn: Les valeurs restantes.""" + :param fmt: The format string. + :param buffer: The target buffer to write into. + :param offset: The offset into the buffer. May be negative to count from the end of the buffer. + :param v1: The first value. + :param *vn: The remaining values. + """ ... def unpack(fmt: str, data: ReadableBuffer) -> Tuple[Any, ...]: - """Décompacter les données selon une chaîne de format. + """Unpack data according to a format string. -Example: ``v1, v2 = struct.unpack('hf', buffer)`` + Example: ``v1, v2 = struct.unpack('hf', buffer)`` -:param fmt: La chaîne de format. -:param data: Les données. -:return: A tuple of the unpacked values.""" + :param fmt: The format string. + :param data: The data. + :return: A tuple of the unpacked values. + """ ... -def unpack_from(fmt: str, buffer: ReadableBuffer, offset: int=0) -> Tuple: - """Décompacter les données d'un tampon selon une chaîne de format. +def unpack_from(fmt: str, buffer: ReadableBuffer, offset: int = 0) -> Tuple: + """Unpack data from a buffer according to a format string. -Example: ``v1, v2 = struct.unpack_from('hf', buffer)`` + Example: ``v1, v2 = struct.unpack_from('hf', buffer)`` -:param fmt: La chaîne de format. -:param buffer: Le tampon source à partir duquel lire. -:param offset: Le décalage dans le tampon. Peut être négatif pour compter à partir de la fin du tampon. -:return: A tuple of the unpacked values.""" - ... \ No newline at end of file + :param fmt: The format string. + :param buffer: The source buffer to read from. + :param offset: The offset into the buffer. May be negative to count from the end of the buffer. + :return: A tuple of the unpacked values. + """ + ... diff --git a/lang/fr/typeshed/stdlib/sys.pyi b/lang/fr/typeshed/stdlib/sys.pyi index acb99fe..320bac9 100644 --- a/lang/fr/typeshed/stdlib/sys.pyi +++ b/lang/fr/typeshed/stdlib/sys.pyi @@ -1,36 +1,43 @@ -"""Fonctions spécifiques au système""" +"""System specific functions""" + from typing import Any, Dict, List, NoReturn, TextIO, Tuple -def exit(retval: object=...) -> NoReturn: - """Terminer le programme en cours avec un code de sortie donné. +def exit(retval: object = ...) -> NoReturn: + """Terminate current program with a given exit code. -Example: ``sys.exit(1)`` + Example: ``sys.exit(1)`` -This function raises a ``SystemExit`` exception. If an argument is given, its -value given as an argument to ``SystemExit``. + This function raises a ``SystemExit`` exception. If an argument is given, its + value given as an argument to ``SystemExit``. -:param retval: Le code de sortie ou le message.""" + :param retval: The exit code or message. + """ ... def print_exception(exc: Exception) -> None: - """Imprime une exception avec une pile d'appels. + """ + Print an exception with a traceback. + + Example: ``sys.print_exception(e)`` -Example: ``sys.print_exception(e)`` + :param exc: The exception to print -:param exc: L'exception à imprimer + This is simplified version of a function which appears in the + ``traceback`` module in CPython. + """ -This is simplified version of a function which appears in the -``traceback`` module in CPython.""" argv: List[str] -"""Une liste mutable d'arguments avec lesquels le programme courant a été démarré.""" +"""A mutable list of arguments the current program was started with.""" + byteorder: str -"""L'ordre des octets du système (``"little"`` ou ``"big"``).""" +"""The byte order of the system (``"little"`` or ``"big"``).""" class _implementation: name: str version: Tuple[int, int, int] + implementation: _implementation -"""Objet avec des informations sur l'implémentation actuelle de Python. +"""Object with information about the current Python implementation. For MicroPython, it has following attributes: @@ -44,12 +51,13 @@ minimal ports). CPython mandates more attributes for this object, but the actual useful bare minimum is implemented in MicroPython. """ + maxsize: int """ -Valeur maximale qu'un entier natif peut stocker sur la plate-forme courante, -ou valeur maximale représentable par le type entier de MicroPython, si elle est plus petite -que la valeur maximale de la plate-forme (c'est le cas pour les portages MicroPython sans support -des entiers long). +Maximum value which a native integer type can hold on the current platform, +or maximum value representable by MicroPython integer type, if it's smaller +than platform max value (that is the case for MicroPython ports without +long int support). This attribute is useful for detecting "bitness" of a platform (32-bit vs 64-bit, etc.). It's recommended to not compare this attribute to some @@ -69,14 +77,17 @@ value directly, but instead count number of bits in it:: # (e.g. 31) due to peculiarities described above, so use "> 16", # "> 32", "> 64" style of comparisons. """ + modules: Dict[str, Any] -"""Dictionnaire des modules chargés. +"""Dictionary of loaded modules. On some ports, it may not include builtin modules.""" + path: List[str] -"""Une liste mutable de répertoires dans lesquels rechercher des modules importés.""" +"""A mutable list of directories to search for imported modules.""" + platform: str -"""La plate-forme sur laquelle MicroPython s'exécute. +"""The platform that MicroPython is running on. For OS/RTOS ports, this is usually an identifier of the OS, e.g. ``"linux"``. For baremetal ports it is an identifier of a board, e.g. ``"pyboard"`` for @@ -86,11 +97,13 @@ distinguish one board from another. If you need to check whether your program runs on MicroPython (vs other Python implementation), use ``sys.implementation`` instead. """ + version: str -"""Version du langage Python à laquelle cette implémentation correspond, sous la forme d'une chaîne de caractères .""" +"""Python language version that this implementation conforms to, as a string.""" + version_info: Tuple[int, int, int] -"""Version du langage Python à laquelle cette implémentation correspond, sous forme d'un tuple d'entiers. +"""Python language version that this implementation conforms to, as a tuple of ints. Only the first three version numbers (major, minor, micro) are supported and they can be referenced only by index, not by name. -""" \ No newline at end of file +""" diff --git a/lang/fr/typeshed/stdlib/time.pyi b/lang/fr/typeshed/stdlib/time.pyi index 349a64b..598c483 100644 --- a/lang/fr/typeshed/stdlib/time.pyi +++ b/lang/fr/typeshed/stdlib/time.pyi @@ -1,115 +1,132 @@ -"""Mesurer le temps et ajouter des retards aux programmes.""" +"""Measure time and add delays to programs. +""" + from typing import Union def sleep(seconds: Union[int, float]) -> None: - """Temporiser d'un certain nombre de secondes. + """ + Delay a number of seconds. -Example: ``time.sleep(1)`` + Example: ``time.sleep(1)`` -:param seconds: Le nombre de secondes pendant lesquelles dormir. -Utiliser un nombre à virgule flottante pour dormir pendant un nombre fractionnaire de secondes.""" + :param seconds: The number of seconds to sleep for. + Use a floating-point number to sleep for a fractional number of seconds. + """ ... def sleep_ms(ms: int) -> None: - """Temporiser pour un nombre donné de millisecondes. + """ + Delay for given number of milliseconds. -Example: ``time.sleep_ms(1_000_000)`` + Example: ``time.sleep_ms(1_000_000)`` -:param ms: Le nombre de millisecondes à attendre (>= 0).""" + :param ms: The number of milliseconds delay (>= 0). + """ ... def sleep_us(us: int) -> None: - """Temporiser pour un nombre donné de microsecondes. + """ + Delay for given number of microseconds. -Example: ``time.sleep_us(1000)`` + Example: ``time.sleep_us(1000)`` -:param us: Le nombre de microsecondes à attendre (>= 0).""" + :param us: The number of microseconds delay (>= 0). + """ ... def ticks_ms() -> int: - """Obtenir un compteur croissant en millisecondes avec un point de référence arbitraire. -Le compteur revient à zéro après une certaine valeur. + """ + Get an increasing, millisecond counter with an arbitrary reference point, + that wraps around after some value. -Example: ``time.ticks_ms()`` + Example: ``time.ticks_ms()`` -:return: The counter value in milliseconds.""" + :return: The counter value in milliseconds. + """ ... def ticks_us() -> int: - """Obtenir un compteur croissant en microsecondes avec un point de référence arbitraire. -Le compteur revient à zéro après une certaine valeur. + """ + Get an increasing, microsecond counter with an arbitrary reference point, + that wraps around after some value. -Example: ``time.ticks_us()`` + Example: ``time.ticks_us()`` -:return: The counter value in microseconds.""" + :return: The counter value in microseconds. + """ ... def ticks_add(ticks: int, delta: int) -> int: - """Décaler les ticks par un nombre donné, positif ou négatif. + """ + Offset ticks value by a given number, which can be either positive or + negative. -Example: ``time.ticks_add(time.ticks_ms(), 200)`` + Example: ``time.ticks_add(time.ticks_ms(), 200)`` -Given a ticks value, this function allows to calculate ticks -value delta ticks before or after it, following modular-arithmetic -definition of tick values. + Given a ticks value, this function allows to calculate ticks + value delta ticks before or after it, following modular-arithmetic + definition of tick values. -:param ticks: Une valeur de ticks -:param delta: Un entier représentant le décalage + :param ticks: A ticks value + :param delta: An integer offset -Example:: + Example:: - # Find out what ticks value there was 100ms ago - print(ticks_add(time.ticks_ms(), -100)) + # Find out what ticks value there was 100ms ago + print(ticks_add(time.ticks_ms(), -100)) - # Calculate deadline for operation and test for it - deadline = ticks_add(time.ticks_ms(), 200) - while ticks_diff(deadline, time.ticks_ms()) > 0: - do_a_little_of_something() + # Calculate deadline for operation and test for it + deadline = ticks_add(time.ticks_ms(), 200) + while ticks_diff(deadline, time.ticks_ms()) > 0: + do_a_little_of_something() - # Find out TICKS_MAX used by this port - print(ticks_add(0, -1))""" + # Find out TICKS_MAX used by this port + print(ticks_add(0, -1)) + """ ... def ticks_diff(ticks1: int, ticks2: int) -> int: - """Mesurer la différence des ticks entre les valeurs retournées par -``time.ticks_ms()`` ou ``ticks_us()``, sous la forme d'une valeur signée -qui peut passer plusieurs fois par zéro. - -Example: ``time.ticks_diff(scheduled_time, now)`` - -:param ticks1: La valeur à partir de laquelle soustraire -:param ticks2: La valeur à soustraire - -The argument order is the same as for subtraction operator, -``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. - -``ticks_diff()`` is designed to accommodate various usage -patterns, among them: - -Polling with timeout. In this case, the order of events is known, and you -will deal only with positive results of :func:`time.ticks_diff()`:: - - # Wait for GPIO pin to be asserted, but at most 500us - start = time.ticks_us() - while pin.value() == 0: - if time.ticks_diff(time.ticks_us(), start) > 500: - raise TimeoutError - - -Scheduling events. In this case, :func:`time.ticks_diff()` result may be -negative if an event is overdue:: - - # This code snippet is not optimized - now = time.ticks_ms() - scheduled_time = task.scheduled_time() - if ticks_diff(scheduled_time, now) > 0: - print("Too early, let's nap") - sleep_ms(ticks_diff(scheduled_time, now)) - task.run() - elif ticks_diff(scheduled_time, now) == 0: - print("Right at time!") - task.run() - elif ticks_diff(scheduled_time, now) < 0: - print("Oops, running late, tell task to run faster!") - task.run(run_faster=True)""" - ... \ No newline at end of file + """ + Measure ticks difference between values returned from + ``time.ticks_ms()`` or ``ticks_us()``, as a signed value + which may wrap around. + + Example: ``time.ticks_diff(scheduled_time, now)`` + + :param ticks1: The value to subtract from + :param ticks2: The value to subtract + + The argument order is the same as for subtraction operator, + ``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. + + ``ticks_diff()`` is designed to accommodate various usage + patterns, among them: + + Polling with timeout. In this case, the order of events is known, and you + will deal only with positive results of :func:`time.ticks_diff()`:: + + # Wait for GPIO pin to be asserted, but at most 500us + start = time.ticks_us() + while pin.value() == 0: + if time.ticks_diff(time.ticks_us(), start) > 500: + raise TimeoutError + + + Scheduling events. In this case, :func:`time.ticks_diff()` result may be + negative if an event is overdue:: + + # This code snippet is not optimized + now = time.ticks_ms() + scheduled_time = task.scheduled_time() + if ticks_diff(scheduled_time, now) > 0: + print("Too early, let's nap") + sleep_ms(ticks_diff(scheduled_time, now)) + task.run() + elif ticks_diff(scheduled_time, now) == 0: + print("Right at time!") + task.run() + elif ticks_diff(scheduled_time, now) < 0: + print("Oops, running late, tell task to run faster!") + task.run(run_faster=True) + """ + ... diff --git a/lang/ja/typeshed/stdlib/gc.pyi b/lang/ja/typeshed/stdlib/gc.pyi index 31e433d..1370abf 100644 --- a/lang/ja/typeshed/stdlib/gc.pyi +++ b/lang/ja/typeshed/stdlib/gc.pyi @@ -1,68 +1,73 @@ -"""ガベージコレクターを制御します。""" +"""Control the garbage collector""" + from typing import overload def enable() -> None: - """自動ガベージコレクションを有効にします。""" + """Enable automatic garbage collection.""" ... def disable() -> None: - """自動ガベージコレクションを無効にします。 + """Disable automatic garbage collection. -Heap memory can still be allocated, -and garbage collection can still be initiated manually using ``gc.collect``.""" + Heap memory can still be allocated, + and garbage collection can still be initiated manually using ``gc.collect``.""" def collect() -> None: - """ガベージコレクションを実行します。""" + """Run a garbage collection.""" ... def mem_alloc() -> int: - """割り当てられているヒープRAMのバイト数を取得します。 + """Get the number of bytes of heap RAM that are allocated. -:return: The number of bytes allocated. + :return: The number of bytes allocated. -This function is MicroPython extension.""" + This function is MicroPython extension. + """ ... def mem_free() -> int: - """使用可能なヒープRAMのバイト数を取得します。この量が不明の場合は -1が返されます。 + """Get the number of bytes of available heap RAM, or -1 if this amount is not known. -:return: The number of bytes free. + :return: The number of bytes free. -This function is MicroPython extension.""" + This function is MicroPython extension. + """ ... @overload def threshold() -> int: - """追加のGC 割り当てしきい値を照会します。 + """Query the additional GC allocation threshold. -:return: The GC allocation threshold. + :return: The GC allocation threshold. -This function is a MicroPython extension. CPython has a similar -function - ``set_threshold()``, but due to different GC -implementations, its signature and semantics are different.""" + This function is a MicroPython extension. CPython has a similar + function - ``set_threshold()``, but due to different GC + implementations, its signature and semantics are different. + """ ... @overload def threshold(amount: int) -> None: - """追加の GC 割り当てしきい値を設定します。 - -Normally, a collection is triggered only when a new allocation -cannot be satisfied, i.e. on an out-of-memory (OOM) condition. -If this function is called, in addition to OOM, a collection -will be triggered each time after ``amount`` bytes have been -allocated (in total, since the previous time such an amount of bytes -have been allocated). ``amount`` is usually specified as less than the -full heap size, with the intention to trigger a collection earlier than when the -heap becomes exhausted, and in the hope that an early collection will prevent -excessive memory fragmentation. This is a heuristic measure, the effect -of which will vary from application to application, as well as -the optimal value of the ``amount`` parameter. - -A value of -1 means a disabled allocation threshold. - -This function is a MicroPython extension. CPython has a similar -function - ``set_threshold()``, but due to different GC -implementations, its signature and semantics are different. - -:param amount: ガベージコレクションを起こすバイト数。""" - ... \ No newline at end of file + """Set the additional GC allocation threshold. + + Normally, a collection is triggered only when a new allocation + cannot be satisfied, i.e. on an out-of-memory (OOM) condition. + If this function is called, in addition to OOM, a collection + will be triggered each time after ``amount`` bytes have been + allocated (in total, since the previous time such an amount of bytes + have been allocated). ``amount`` is usually specified as less than the + full heap size, with the intention to trigger a collection earlier than when the + heap becomes exhausted, and in the hope that an early collection will prevent + excessive memory fragmentation. This is a heuristic measure, the effect + of which will vary from application to application, as well as + the optimal value of the ``amount`` parameter. + + A value of -1 means a disabled allocation threshold. + + This function is a MicroPython extension. CPython has a similar + function - ``set_threshold()``, but due to different GC + implementations, its signature and semantics are different. + + :param amount: The number of bytes after which a garbage collection should be triggered. + """ + ... diff --git a/lang/ja/typeshed/stdlib/log.pyi b/lang/ja/typeshed/stdlib/log.pyi index ed5ff86..c9870fa 100644 --- a/lang/ja/typeshed/stdlib/log.pyi +++ b/lang/ja/typeshed/stdlib/log.pyi @@ -1,89 +1,104 @@ -"""micro:bit V2のログにデータを記録します。""" +"""Log data to your micro:bit V2.""" + from typing import Literal, Mapping, Optional, Union, overload + MILLISECONDS = 1 -"""ミリ秒単位の日時フォーマット。""" +"""Milliseconds timestamp format.""" + SECONDS = 10 -"""秒単位の日時フォーマット。""" +"""Seconds timestamp format.""" + MINUTES = 600 -"""分単位の日時フォーマット。""" +"""Minutes timestamp format.""" + HOURS = 36000 -"""時間単位の日時フォーマット。""" +"""Hours timestamp format.""" + DAYS = 864000 -"""日単位の日時フォーマット。""" +"""Days timestamp format.""" -def set_labels(*labels: str, timestamp: Optional[Literal[1, 10, 36000, 864000]]=SECONDS) -> None: - """ログファイルのヘッダーを設定します。 +def set_labels( + *labels: str, timestamp: Optional[Literal[1, 10, 36000, 864000]] = SECONDS +) -> None: + """Set up the log file header. -Example: ``log.set_labels('X', 'Y', 'Z', timestamp=log.MINUTES)`` + Example: ``log.set_labels('X', 'Y', 'Z', timestamp=log.MINUTES)`` -Ideally this function should be called a single time, before any data is -logged, to configure the data table header once. + Ideally this function should be called a single time, before any data is + logged, to configure the data table header once. -If a log file already exists when the program starts, or if this function -is called multiple times, it will check the labels already defined in the -log file. If this function call contains any new labels not already -present, it will generate a new header row with the additional columns. + If a log file already exists when the program starts, or if this function + is called multiple times, it will check the labels already defined in the + log file. If this function call contains any new labels not already + present, it will generate a new header row with the additional columns. -By default the first column contains a timestamp for each row. The time -unit can be selected via the timestamp argument. + By default the first column contains a timestamp for each row. The time + unit can be selected via the timestamp argument. -:param *labels: 任意の数の位置引数で。それぞれがログヘッダの見出しになります。 -:param timestamp: すべての行の最初の列として自動的に追加されるタイムスタンプの単位を選択します。タイムスタンプの値は ``log.MILLISECONDS``、 ``log.SECONDS``、``log.MINUTES``、``log.HOURS``、``log.DAYS`` またはタイムスタンプを無効にする ``None`` のうちのいずれかである必要があります。デフォルト値は ``log.SECONDS`` です。""" + :param *labels: Any number of positional arguments, each corresponding to an entry in the log header. + :param timestamp: Select the timestamp unit that will be automatically added as the first column in every row. Timestamp values can be one of ``log.MILLISECONDS``, ``log.SECONDS``, ``log.MINUTES``, ``log.HOURS``, ``log.DAYS`` or ``None`` to disable the timestamp. The default value is ``log.SECONDS``. + """ ... @overload -def add(data_dictionary: Optional[Mapping[str, Union[str, int, float]]]) -> None: - """ヘッダーと値の辞書を渡すことにより、ログにデータ行を追加します。 +def add( + data_dictionary: Optional[Mapping[str, Union[str, int, float]]], +) -> None: + """Add a data row to the log by passing a dictionary of headers and values. -Example: ``log.add({ 'temp': temperature() })`` + Example: ``log.add({ 'temp': temperature() })`` -Each call to this function adds a row to the log. + Each call to this function adds a row to the log. -New labels not previously specified via the set_labels function, or by a -previous call to this function, will trigger a new header entry to be added -to the log with the extra labels. + New labels not previously specified via the set_labels function, or by a + previous call to this function, will trigger a new header entry to be added + to the log with the extra labels. -Labels previously specified and not present in a call to this function will -be skipped with an empty value in the log row. + Labels previously specified and not present in a call to this function will + be skipped with an empty value in the log row. -:param data_dictionary: (data dictionary とはデータ辞書の意味です) 記録するデータを辞書で指定します。辞書の各キーが見出しを表します。""" + :param data_dictionary: The data to log as a dictionary with a key for each header. + """ ... @overload def add(**kwargs: Union[str, int, float]) -> None: - """キーワード引数でログにデータ行を追加します。 + """Add a data row to the log using keyword arguments. -Example: ``log.add(temp=temperature())`` + Example: ``log.add(temp=temperature())`` -Each call to this function adds a row to the log. + Each call to this function adds a row to the log. -New labels not previously specified via the set_labels function, or by a -previous call to this function, will trigger a new header entry to be added -to the log with the extra labels. + New labels not previously specified via the set_labels function, or by a + previous call to this function, will trigger a new header entry to be added + to the log with the extra labels. -Labels previously specified and not present in a call to this function will -be skipped with an empty value in the log row.""" + Labels previously specified and not present in a call to this function will + be skipped with an empty value in the log row. + """ ... def delete(full=False): - """ログの内容を、ヘッダーもあわせて削除します。 + """Deletes the contents of the log, including headers. -Example: ``log.delete()`` + Example: ``log.delete()`` -To add the log headers again the ``set_labels`` function should to be called after this function. + To add the log headers again the ``set_labels`` function should to be called after this function. -There are two erase modes; “full” completely removes the data from the physical storage, -and “fast” invalidates the data without removing it. + There are two erase modes; “full” completely removes the data from the physical storage, + and “fast” invalidates the data without removing it. -:param full: ``True`` を指定すると「完全」消去になり、``False`` を指定すると「高速」消去になります。""" + :param full: ``True`` selects a “full” erase and ``False`` selects the “fast” erase method. + """ ... def set_mirroring(serial: bool): - """ログのデータ記録をシリアル出力にミラーリングするかを設定します。 + """Configure mirroring of the data logging activity to the serial output. -Example: ``log.set_mirroring(True)`` + Example: ``log.set_mirroring(True)`` -Serial mirroring is disabled by default. When enabled, it will print to serial each row logged into the log file. + Serial mirroring is disabled by default. When enabled, it will print to serial each row logged into the log file. -:param serial: ``True`` を指定するとシリアル出力にデータをミラーリングします。""" - ... \ No newline at end of file + :param serial: ``True`` enables mirroring data to the serial output. + """ + ... diff --git a/lang/ja/typeshed/stdlib/machine.pyi b/lang/ja/typeshed/stdlib/machine.pyi index dc84b74..2e82f5b 100644 --- a/lang/ja/typeshed/stdlib/machine.pyi +++ b/lang/ja/typeshed/stdlib/machine.pyi @@ -1,84 +1,97 @@ -"""低レベルユーティリティ""" +"""Low-level utilities. +""" from typing import Any from .microbit import MicroBitDigitalPin def unique_id() -> bytes: - """ボードの一意の識別子を持つバイト列を取得します。 + """Get a byte string with a unique identifier of a board. -Example: ``machine.unique_id()`` + Example: ``machine.unique_id()`` -:return: An identifier that varies from one board instance to another.""" + :return: An identifier that varies from one board instance to another. + """ ... def reset() -> None: - """外部のRESETボタンを押したと同様にデバイスをリセットします。 + """Reset the device in a manner similar to pushing the external RESET button. -Example: ``machine.reset()``""" + Example: ``machine.reset()`` + """ ... def freq() -> int: - """CPU周波数をヘルツ単位で取得します。 + """Get the CPU frequency in hertz. -Example: ``machine.freq()`` + Example: ``machine.freq()`` -:return: The CPU frequency.""" + :return: The CPU frequency. + """ ... def disable_irq() -> Any: - """割り込み要求を無効にします。 + """Disable interrupt requests. -Example: ``interrupt_state = machine.disable_irq()`` + Example: ``interrupt_state = machine.disable_irq()`` -:return: the previous IRQ state which should be considered an opaque value + :return: the previous IRQ state which should be considered an opaque value -The return value should be passed to the ``enable_irq`` function to restore -interrupts to their original state.""" + The return value should be passed to the ``enable_irq`` function to restore + interrupts to their original state. + """ ... def enable_irq(state: Any) -> None: - """割り込み要求を再度有効にします。 + """Re-enable interrupt requests. -Example: ``machine.enable_irq(interrupt_state)`` + Example: ``machine.enable_irq(interrupt_state)`` -:param state: ``disable_irq`` 関数の最も最近の呼び出しから返された値。""" + :param state: The value that was returned from the most recent call to the ``disable_irq`` function. + """ ... -def time_pulse_us(pin: MicroBitDigitalPin, pulse_level: int, timeout_us: int=1000000) -> int: - """端子のパルス時間を計測します。 +def time_pulse_us( + pin: MicroBitDigitalPin, pulse_level: int, timeout_us: int = 1000000 +) -> int: + """Time a pulse on a pin. -Example: ``time_pulse_us(pin0, 1)`` + Example: ``time_pulse_us(pin0, 1)`` -If the current input value of the pin is different to ``pulse_level``, the -function first waits until the pin input becomes equal to -``pulse_level``, then times the duration that the pin is equal to -``pulse_level``. If the pin is already equal to ``pulse_level`` then timing -starts straight away. + If the current input value of the pin is different to ``pulse_level``, the + function first waits until the pin input becomes equal to + ``pulse_level``, then times the duration that the pin is equal to + ``pulse_level``. If the pin is already equal to ``pulse_level`` then timing + starts straight away. -:param pin: (ピン) 計測対象の端子 -:param pulse_level: 低パルスの時間計測で 0、高パルスの時間計測で 1 を指定 -:param timeout_us: マイクロ秒単位のタイムアウト時間 -:return: The duration of the pulse in microseconds, or -1 for a timeout waiting for the level to match ``pulse_level``, or -2 on timeout waiting for the pulse to end""" + :param pin: The pin to use + :param pulse_level: 0 to time a low pulse or 1 to time a high pulse + :param timeout_us: A microsecond timeout + :return: The duration of the pulse in microseconds, or -1 for a timeout waiting for the level to match ``pulse_level``, or -2 on timeout waiting for the pulse to end + """ ... class mem: - """``mem8``、``mem16``、``mem32`` メモリビューのクラス。""" + """The class for the ``mem8``, ``mem16`` and ``mem32`` memory views.""" def __getitem__(self, address: int) -> int: - """メモリにある値を参照します。 + """Access a value from memory. -:param address: メモリのアドレス。 -:return: The value at that address as an integer.""" + :param address: The memory address. + :return: The value at that address as an integer. + """ ... - def __setitem__(self, address: int, value: int) -> None: - """指定アドレスに値を設定します。 + """Set a value at the given address. -:param address: メモリのアドレス。 -:param value: 設定する整数値。""" + :param address: The memory address. + :param value: The integer value to set. + """ ... + mem8: mem -"""メモリの8ビット(バイト)ビュー。""" +"""8-bit (byte) view of memory.""" + mem16: mem -"""メモリの16ビットビュー。""" +"""16-bit view of memory.""" + mem32: mem -"""メモリの32ビットビュー。""" \ No newline at end of file +"""32-bit view of memory.""" diff --git a/lang/ja/typeshed/stdlib/math.pyi b/lang/ja/typeshed/stdlib/math.pyi index 7753a13..f82d4de 100644 --- a/lang/ja/typeshed/stdlib/math.pyi +++ b/lang/ja/typeshed/stdlib/math.pyi @@ -1,246 +1,273 @@ -"""数学関数。""" +"""Mathematical functions. +""" + from typing import Tuple def acos(x: float) -> float: - """逆余弦を算出します。 + """Calculate the inverse cosine. -Example: ``math.acos(1)`` + Example: ``math.acos(1)`` -:param x: 数値 -:return: The inverse cosine of ``x``""" + :param x: A number + :return: The inverse cosine of ``x`` + """ ... def asin(x: float) -> float: - """逆正弦を算出します。 + """Calculate the inverse sine. -Example: ``math.asin(0)`` + Example: ``math.asin(0)`` -:param x: 数値 -:return: The inverse sine of ``x``""" + :param x: A number + :return: The inverse sine of ``x`` + """ ... def atan(x: float) -> float: - """逆正接を算出します。 + """Calculate the inverse tangent. -Example: ``math.atan(0)`` + Example: ``math.atan(0)`` -:param x: 数値 -:return: The inverse tangent of ``x``""" + :param x: A number + :return: The inverse tangent of ``x`` + """ ... def atan2(y: float, x: float) -> float: - """``y/x`` の逆正接の主値を算出します。 + """Calculate the principal value of the inverse tangent of ``y/x``. -Example: ``math.atan2(0, -1)`` + Example: ``math.atan2(0, -1)`` -:param y: 数値 -:param x: 数値 -:return: The principal value of the inverse tangent of ``y/x``""" + :param y: A number + :param x: A number + :return: The principal value of the inverse tangent of ``y/x`` + """ ... def ceil(x: float) -> float: - """正の無限大方向に数値を丸めます。 + """Round a number towards positive infinity. -Example: ``math.ceil(0.1)`` + Example: ``math.ceil(0.1)`` -:param x: 数値 -:return: ``x`` rounded towards positive infinity.""" + :param x: A number + :return: ``x`` rounded towards positive infinity. + """ ... def copysign(x: float, y: float) -> float: - """``y`` の符号で ``x`` を算出します。 + """Calculate ``x`` with the sign of ``y``. -Example: ``math.copysign(1, -1)`` + Example: ``math.copysign(1, -1)`` -:param x: 数値 -:param y: 戻り値の符号の元になる値 -:return: ``x`` with the sign of ``y``""" + :param x: A number + :param y: The source of the sign for the return value + :return: ``x`` with the sign of ``y`` + """ ... def cos(x: float) -> float: - """``x`` の余弦を算出します。 + """Calculate the cosine of ``x``. -Example: ``math.cos(0)`` + Example: ``math.cos(0)`` -:param x: 数値 -:return: The cosine of ``x``""" + :param x: A number + :return: The cosine of ``x`` + """ ... def degrees(x: float) -> float: - """ラジアンを度に変換します。 (゜(度)) + """Convert radians to degrees. -Example: ``math.degrees(2 * math.pi)`` + Example: ``math.degrees(2 * math.pi)`` -:param x: ラジアン単位の値 -:return: The value converted to degrees""" + :param x: A value in radians + :return: The value converted to degrees""" ... def exp(x: float) -> float: - """``x`` の指数を算出します。 + """Calculate the exponential of ``x``. -Example: ``math.exp(1)`` + Example: ``math.exp(1)`` -:param x: 数値 -:return: The exponential of ``x``.""" + :param x: A number + :return: The exponential of ``x``. + """ ... def fabs(x: float) -> float: - """``x`` の絶対値を返します。 + """Return the absolute value of ``x``. -Example: ``math.fabs(-0.1)`` + Example: ``math.fabs(-0.1)`` -:param x: 数値 -:return: The absolute value of ``x``""" + :param x: A number + :return: The absolute value of ``x`` + """ ... def floor(x: float) -> int: - """負の無限大方向に数値を丸めます。 + """Round a number towards negative infinity. -Example: ``math.floor(0.9)`` + Example: ``math.floor(0.9)`` -:param x: 数値 -:return: ``x`` rounded towards negative infinity.""" + :param x: A number + :return: ``x`` rounded towards negative infinity. + """ ... def fmod(x: float, y: float) -> float: - """``x/y`` の剰余を算出します。 + """Calculate the remainder of ``x/y``. -Example: ``math.fmod(10, 3)`` + Example: ``math.fmod(10, 3)`` -:param x: 分子の値 -:param y: 分母の値""" + :param x: The numerator + :param y: The denominator + """ ... def frexp(x: float) -> Tuple[float, int]: - """浮動小数点数を仮数部と指数部に分解します。 + """Decomposes a floating-point number into its mantissa and exponent. -Example: ``mantissa, exponent = math.frexp(2)`` + Example: ``mantissa, exponent = math.frexp(2)`` -The returned value is the tuple ``(m, e)`` such that ``x == m * 2**e`` -exactly. If ``x == 0`` then the function returns ``(0.0, 0)``, otherwise -the relation ``0.5 <= abs(m) < 1`` holds. + The returned value is the tuple ``(m, e)`` such that ``x == m * 2**e`` + exactly. If ``x == 0`` then the function returns ``(0.0, 0)``, otherwise + the relation ``0.5 <= abs(m) < 1`` holds. -:param x: 浮動小数点数 -:return: A tuple of length two containing its mantissa then exponent""" + :param x: A floating-point number + :return: A tuple of length two containing its mantissa then exponent + """ ... def isfinite(x: float) -> bool: - """有限数かどうかを確認します。 + """Check if a value is finite. -Example: ``math.isfinite(float('inf'))`` + Example: ``math.isfinite(float('inf'))`` -:param x: 数値。 -:return: ``True`` if ``x`` is finite, ``False`` otherwise.""" + :param x: A number. + :return: ``True`` if ``x`` is finite, ``False`` otherwise. + """ ... def isinf(x: float) -> bool: - """無限数かどうかを確認します。 + """Check if a value is infinite. -Example: ``math.isinf(float('-inf'))`` + Example: ``math.isinf(float('-inf'))`` -:param x: 数値。 -:return: ``True`` if ``x`` is infinite, ``False`` otherwise.""" + :param x: A number. + :return: ``True`` if ``x`` is infinite, ``False`` otherwise. + """ ... def isnan(x: float) -> bool: - """非数(NaN: Not-a-Number)かどうかを確認します。 + """Check if a value is not-a-number (NaN). -Example: ``math.isnan(float('nan'))`` + Example: ``math.isnan(float('nan'))`` -:param x: 数値 -:return: ``True`` if ``x`` is not-a-number (NaN), ``False`` otherwise.""" + :param x: A number + :return: ``True`` if ``x`` is not-a-number (NaN), ``False`` otherwise.""" ... def ldexp(x: float, exp: int) -> float: - """``x * (2**exp)`` を算出します。 + """Calculate ``x * (2**exp)``. -Example: ``math.ldexp(0.5, 2)`` + Example: ``math.ldexp(0.5, 2)`` -:param x: 数値 -:param exp: 整数の指数 -:return: ``x * (2**exp)``""" + :param x: A number + :param exp: Integer exponent + :return: ``x * (2**exp)`` + """ ... -def log(x: float, base: float=e) -> float: - """``x`` の対数を指定された底(デフォルトは自然対数)で算出します。 +def log(x: float, base: float = e) -> float: + """Calculate the logarithm of ``x`` to the given base (defaults to natural logorithm). -Example: ``math.log(math.e)`` + Example: ``math.log(math.e)`` -With one argument, return the natural logarithm of x (to base e). + With one argument, return the natural logarithm of x (to base e). -With two arguments, return the logarithm of x to the given base, calculated as ``log(x)/log(base)``. + With two arguments, return the logarithm of x to the given base, calculated as ``log(x)/log(base)``. -:param x: 数値 -:param base: 使用する底 -:return: The natural logarithm of ``x``""" + :param x: A number + :param base: The base to use + :return: The natural logarithm of ``x`` + """ ... def modf(x: float) -> Tuple[float, float]: - """``x`` の整数部分と小数部分を返します。 + """Calculate the fractional and integral parts of ``x``. -Example: ``fractional, integral = math.modf(1.5)`` + Example: ``fractional, integral = math.modf(1.5)`` -:param x: 数値 -:return: A tuple of two floats representing the fractional then integral parts of ``x``. + :param x: A number + :return: A tuple of two floats representing the fractional then integral parts of ``x``. -Both the fractional and integral values have the same sign as ``x``.""" + Both the fractional and integral values have the same sign as ``x``. + """ ... def pow(x: float, y: float) -> float: - """``x`` の ``y`` 乗を返します。 + """Returns ``x`` to the power of ``y``. -Example: ``math.pow(4, 0.5)`` + Example: ``math.pow(4, 0.5)`` -:param x: 数値 -:param y: 指数 -:return: ``x`` to the power of ``y``""" + :param x: A number + :param y: The exponent + :return: ``x`` to the power of ``y`` + """ ... def radians(x: float) -> float: - """度をラジアンに変換します。 + """Convert a degrees to radians. -Example: ``math.radians(360)`` + Example: ``math.radians(360)`` -:param x: 度単位の角度 -:return: The value converted to radians""" + :param x: A value in degrees + :return: The value converted to radians + """ ... def sin(x: float) -> float: - """``x`` の正弦を算出します。 + """Calculate the sine of ``x``. -Example: ``math.sin(math.pi/2)`` + Example: ``math.sin(math.pi/2)`` -:param x: 数値 -:return: The sine of ``x``""" + :param x: A number + :return: The sine of ``x`` + """ ... def sqrt(x: float) -> float: - """``x`` の平方根を算出します。 + """Calculate the square root of ``x``. -Example: ``math.sqrt(4)`` + Example: ``math.sqrt(4)`` -:param x: 数値 -:return: The square root of ``x``""" + :param x: A number + :return: The square root of ``x`` + """ ... def tan(x: float) -> float: - """``x`` の正接を算出します。 + """Calculate the tangent of ``x``. -Example: ``math.tan(0)`` + Example: ``math.tan(0)`` -:param x: 数値 -:return: The tangent of ``x``.""" + :param x: A number + :return: The tangent of ``x``. + """ ... def trunc(x: float) -> int: - """0 方向に数値を丸めます。 + """Round a number towards 0. -Example: ``math.trunc(-0.9)`` + Example: ``math.trunc(-0.9)`` -:param x: 数値 -:return: ``x`` rounded towards zero.""" + :param x: A number + :return: ``x`` rounded towards zero. + """ ... + e: float -"""自然対数の底""" +"""Base of the natural logarithm""" + pi: float -"""円の円周と直径の比""" \ No newline at end of file +"""The ratio of a circle's circumference to its diameter""" diff --git a/lang/ja/typeshed/stdlib/microbit/__init__.pyi b/lang/ja/typeshed/stdlib/microbit/__init__.pyi index 06c42bb..f12158f 100644 --- a/lang/ja/typeshed/stdlib/microbit/__init__.pyi +++ b/lang/ja/typeshed/stdlib/microbit/__init__.pyi @@ -1,6 +1,11 @@ -"""端子、イメージ、サウンド、温度と音量。""" +"""Pins, images, sounds, temperature and volume. +""" + from typing import Any, Callable, List, Optional, Tuple, Union, overload + from _typeshed import ReadableBuffer + +# V2 only from . import accelerometer as accelerometer from . import audio as audio from . import compass as compass @@ -11,696 +16,831 @@ from . import speaker as speaker from . import spi as spi from . import uart as uart -def run_every(callback: Optional[Callable[[], None]]=None, days: int=0, h: int=0, min: int=0, s: int=0, ms: int=0) -> Callable[[Callable[[], None]], Callable[[], None]]: - """time 引数で指定した間隔で関数を実行するようスケジュールします。 **V2** のみで使えます。 +def run_every( + callback: Optional[Callable[[], None]] = None, + days: int = 0, + h: int = 0, + min: int = 0, + s: int = 0, + ms: int = 0, +) -> Callable[[Callable[[], None]], Callable[[], None]]: + """Schedule to run a function at the interval specified by the time arguments **V2 only**. -Example: ``run_every(my_logging, min=5)`` + Example: ``run_every(my_logging, min=5)`` -``run_every`` can be used in two ways: + ``run_every`` can be used in two ways: -As a Decorator - placed on top of the function to schedule. For example:: + As a Decorator - placed on top of the function to schedule. For example:: - @run_every(h=1, min=20, s=30, ms=50) - def my_function(): - # Do something here + @run_every(h=1, min=20, s=30, ms=50) + def my_function(): + # Do something here -As a Function - passing the callback as a positional argument. For example:: + As a Function - passing the callback as a positional argument. For example:: - def my_function(): - # Do something here - run_every(my_function, s=30) + def my_function(): + # Do something here + run_every(my_function, s=30) -Each argument corresponds to a different time unit and they are additive. -So ``run_every(min=1, s=30)`` schedules the callback every minute and a half. + Each argument corresponds to a different time unit and they are additive. + So ``run_every(min=1, s=30)`` schedules the callback every minute and a half. -When an exception is thrown inside the callback function it deschedules the -function. To avoid this you can catch exceptions with ``try/except``. + When an exception is thrown inside the callback function it deschedules the + function. To avoid this you can catch exceptions with ``try/except``. -:param callback: 指定した間隔で呼び出す関数。デコレータとして使う場合は省略してください。 -:param days: スケジューリングのための日数を設定します。 -:param h: スケジューリングのための時間を設定します。 -:param min: スケジューリングのための分を設定します。 -:param s: スケジューリングのための秒を設定します。 -:param ms: スケジューリングのためのミリ秒を設定します。""" + :param callback: Function to call at the provided interval. Omit when using as a decorator. + :param days: Sets the day mark for the scheduling. + :param h: Sets the hour mark for the scheduling. + :param min: Sets the minute mark for the scheduling. + :param s: Sets the second mark for the scheduling. + :param ms: Sets the millisecond mark for the scheduling. + """ def panic(n: int) -> None: - """パニックモードに入ります。 + """Enter a panic mode. -Example: ``panic(127)`` + Example: ``panic(127)`` -:param n: 状態を示す 255 以下の任意の整数。 + :param n: An arbitrary integer <= 255 to indicate a status. -Requires restart.""" + Requires restart. + """ def reset() -> None: - """ボードを再起動します。""" + """Restart the board.""" + @overload def scale(value: float, from_: Tuple[float, float], to: Tuple[int, int]) -> int: - """ある整数区間から別の整数区間に値を変換します。 + """Converts a value from a range to an integer range. -Example: ``volume = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255))`` + Example: ``volume = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255))`` -For example, to convert an accelerometer X value to a speaker volume. + For example, to convert an accelerometer X value to a speaker volume. -If one of the numbers in the ``to`` parameter is a floating point -(i.e a decimal number like ``10.0``), this function will return a -floating point number. + If one of the numbers in the ``to`` parameter is a floating point + (i.e a decimal number like ``10.0``), this function will return a + floating point number. - temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0)) + temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0)) -:param value: 変換する数値。 -:param from_: 変換元の区間を定義するためのタプル。 -:param to: 変換先の区間を定義するためのタプル。 -:return: The ``value`` converted to the ``to`` range.""" + :param value: A number to convert. + :param from_: A tuple to define the range to convert from. + :param to: A tuple to define the range to convert to. + :return: The ``value`` converted to the ``to`` range. + """ @overload def scale(value: float, from_: Tuple[float, float], to: Tuple[float, float]) -> float: - """ある浮動小数点数区間から別の浮動小数点数区間に値を変換します。 + """Converts a value from a range to a floating point range. -Example: ``temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0))`` + Example: ``temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0))`` -For example, to convert temperature from a Celsius scale to Fahrenheit. + For example, to convert temperature from a Celsius scale to Fahrenheit. -If one of the numbers in the ``to`` parameter is a floating point -(i.e a decimal number like ``10.0``), this function will return a -floating point number. -If they are both integers (i.e ``10``), it will return an integer:: + If one of the numbers in the ``to`` parameter is a floating point + (i.e a decimal number like ``10.0``), this function will return a + floating point number. + If they are both integers (i.e ``10``), it will return an integer:: - returns_int = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255)) + returns_int = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255)) -:param value: 変換する数値。 -:param from_: 変換元の区間を定義するためのタプル。 -:param to: 変換先の区間を定義するためのタプル。 -:return: The ``value`` converted to the ``to`` range.""" + :param value: A number to convert. + :param from_: A tuple to define the range to convert from. + :param to: A tuple to define the range to convert to. + :return: The ``value`` converted to the ``to`` range. + """ def sleep(n: float) -> None: - """``n`` ミリ秒待機します。 + """Wait for ``n`` milliseconds. -Example: ``sleep(1000)`` + Example: ``sleep(1000)`` -:param n: ミリ秒単位の待機時間 + :param n: The number of milliseconds to wait -One second is 1000 milliseconds, so:: + One second is 1000 milliseconds, so:: - microbit.sleep(1000) + microbit.sleep(1000) -will pause the execution for one second.""" + will pause the execution for one second. + """ def running_time() -> int: - """ボードの実行時間を取得します。 + """Get the running time of the board. -:return: The number of milliseconds since the board was switched on or restarted.""" + :return: The number of milliseconds since the board was switched on or restarted. + """ def temperature() -> int: - """micro:bitの温度を摂氏で取得します。 (温度)""" + """Get the temperature of the micro:bit in degrees Celsius.""" def set_volume(v: int) -> None: - """音量を設定します。 + """Sets the volume. -Example: ``set_volume(127)`` + Example: ``set_volume(127)`` -:param v: 0(下限)から 255(上限)までの間の値。 + :param v: a value between 0 (low) and 255 (high). -Out of range values will be clamped to 0 or 255. + Out of range values will be clamped to 0 or 255. -**V2** only.""" + **V2** only. + """ ... class Button: - """ボタン ``button_a`` と ``button_b`` のクラス。""" + """The class for the buttons ``button_a`` and ``button_b``.""" def is_pressed(self) -> bool: - """ボタンが押されているかどうかを確認します。 + """Check if the button is pressed. -:return: ``True`` if the specified button ``button`` is pressed, and ``False`` otherwise.""" + :return: ``True`` if the specified button ``button`` is pressed, and ``False`` otherwise. + """ ... - def was_pressed(self) -> bool: - """デバイスが起動されてから、もしくは前回このメソッドが呼び出されてからボタンが押されたかどうかを確認します。 + """Check if the button was pressed since the device started or the last time this method was called. -Calling this method will clear the press state so -that the button must be pressed again before this method will return -``True`` again. + Calling this method will clear the press state so + that the button must be pressed again before this method will return + ``True`` again. -:return: ``True`` if the specified button ``button`` was pressed, and ``False`` otherwise""" + :return: ``True`` if the specified button ``button`` was pressed, and ``False`` otherwise + """ ... - def get_presses(self) -> int: - """ボタンを押した回数の合計を取得し、返す前に回数をゼロにリセットします。 + """Get the running total of button presses, and resets this total + to zero before returning. -:return: The number of presses since the device started or the last time this method was called""" + :return: The number of presses since the device started or the last time this method was called + """ ... + button_a: Button -"""左のボタン ``Button`` オブジェクト。""" +"""The left button ``Button`` object.""" + button_b: Button -"""右のボタン ``Button`` オブジェクト。""" +"""The right button ``Button`` object.""" class MicroBitDigitalPin: - """デジタル端子。 + """A digital pin. + + Some pins support analog and touch features using the ``MicroBitAnalogDigitalPin`` and ``MicroBitTouchPin`` subclasses. + """ -Some pins support analog and touch features using the ``MicroBitAnalogDigitalPin`` and ``MicroBitTouchPin`` subclasses.""" NO_PULL: int PULL_UP: int PULL_DOWN: int - def read_digital(self) -> int: - """端子のデジタル値を取得します。 + """Get the digital value of the pin. -Example: ``value = pin0.read_digital()`` + Example: ``value = pin0.read_digital()`` -:return: 1 if the pin is high, and 0 if it's low.""" + :return: 1 if the pin is high, and 0 if it's low. + """ ... - def write_digital(self, value: int) -> None: - """端子のデジタル値を設定します。 + """Set the digital value of the pin. -Example: ``pin0.write_digital(1)`` + Example: ``pin0.write_digital(1)`` -:param value: 端子をハイにするには 1 、ローにするには 0 を指定""" + :param value: 1 to set the pin high or 0 to set the pin low""" ... - def set_pull(self, value: int) -> None: - """プル状態を ``PULL_UP``、``PULL_DOWN``、``NO_PULL`` の3つの値のいずれかに設定します。 + """Set the pull state to one of three possible values: ``PULL_UP``, ``PULL_DOWN`` or ``NO_PULL``. -Example: ``pin0.set_pull(pin0.PULL_UP)`` + Example: ``pin0.set_pull(pin0.PULL_UP)`` -:param value: ``pin0.PULL_UP`` などの関連する端子のプル状態。""" + :param value: The pull state from the relevant pin, e.g. ``pin0.PULL_UP``. + """ ... - def get_pull(self) -> int: - """端子のプル状態を取得します。 + """Get the pull state on a pin. -Example: ``pin0.get_pull()`` + Example: ``pin0.get_pull()`` -:return: ``NO_PULL``, ``PULL_DOWN``, or ``PULL_UP`` + :return: ``NO_PULL``, ``PULL_DOWN``, or ``PULL_UP`` -These are set using the ``set_pull()`` method or automatically configured -when a pin mode requires it.""" + These are set using the ``set_pull()`` method or automatically configured + when a pin mode requires it. + """ ... - def get_mode(self) -> str: - """端子のモードを返します。 + """Returns the pin mode. -Example: ``pin0.get_mode()`` + Example: ``pin0.get_mode()`` -When a pin is used for a specific function, like -writing a digital value, or reading an analog value, the pin mode -changes. + When a pin is used for a specific function, like + writing a digital value, or reading an analog value, the pin mode + changes. -:return: ``"unused"``, ``"analog"``, ``"read_digital"``, ``"write_digital"``, ``"display"``, ``"button"``, ``"music"``, ``"audio"``, ``"touch"``, ``"i2c"``, or ``"spi"``""" + :return: ``"unused"``, ``"analog"``, ``"read_digital"``, ``"write_digital"``, ``"display"``, ``"button"``, ``"music"``, ``"audio"``, ``"touch"``, ``"i2c"``, or ``"spi"`` + """ ... - def write_analog(self, value: int) -> None: - """PWM 信号を端子に出力します。時間幅周期は ``value`` に比例します。 - -Example: ``pin0.write_analog(254)`` + """Output a PWM signal on the pin, with the duty cycle proportional to ``value``. -:param value: 0(時間幅周期 0%)から 1023(時間幅周期 100%)までの整数または浮動小数点数。""" + Example: ``pin0.write_analog(254)`` + :param value: An integer or a floating point number between 0 (0% duty cycle) and 1023 (100% duty). + """ def set_analog_period(self, period: int) -> None: - """出力されるPWM信号の周期を ``period`` にミリ秒単位で設定します。 + """Set the period of the PWM signal being output to ``period`` in milliseconds. -Example: ``pin0.set_analog_period(10)`` - -:param period: 周期をミリ秒単位で指定。有効な最小値は1ms。""" + Example: ``pin0.set_analog_period(10)`` + :param period: The period in milliseconds with a minimum valid value of 1ms. + """ def set_analog_period_microseconds(self, period: int) -> None: - """出力されるPWM信号の周期を ``period`` にマイクロ秒単位で設定します。 + """Set the period of the PWM signal being output to ``period`` in microseconds. -Example: ``pin0.set_analog_period_microseconds(512)`` + Example: ``pin0.set_analog_period_microseconds(512)`` -:param period: 周期をマイクロ秒単位で指定。有効な最小値は256µs。""" + :param period: The period in microseconds with a minimum valid value of 256µs. + """ class MicroBitAnalogDigitalPin(MicroBitDigitalPin): - """アナログとデジタル機能を備えた端子。""" + """A pin with analog and digital features.""" def read_analog(self) -> int: - """端子にかかっている電圧を読み取ります。 + """Read the voltage applied to the pin. -Example: ``pin0.read_analog()`` + Example: ``pin0.read_analog()`` -:return: An integer between 0 (meaning 0V) and 1023 (meaning 3.3V).""" + :return: An integer between 0 (meaning 0V) and 1023 (meaning 3.3V). + """ class MicroBitTouchPin(MicroBitAnalogDigitalPin): - """アナログ、デジタル、タッチ機能を備えた端子。""" + """A pin with analog, digital and touch features.""" + CAPACITIVE: int RESISTIVE: int - def is_touched(self) -> bool: - """端子にタッチしているかどうかを確認します。 + """Check if the pin is being touched. -Example: ``pin0.is_touched()`` + Example: ``pin0.is_touched()`` -The default touch mode for the pins on the edge connector is ``resistive``. -The default for the logo pin **V2** is ``capacitive``. + The default touch mode for the pins on the edge connector is ``resistive``. + The default for the logo pin **V2** is ``capacitive``. -**Resistive touch** -This test is done by measuring how much resistance there is between the -pin and ground. A low resistance gives a reading of ``True``. To get -a reliable reading using a finger you may need to touch the ground pin -with another part of your body, for example your other hand. + **Resistive touch** + This test is done by measuring how much resistance there is between the + pin and ground. A low resistance gives a reading of ``True``. To get + a reliable reading using a finger you may need to touch the ground pin + with another part of your body, for example your other hand. -**Capacitive touch** -This test is done by interacting with the electric field of a capacitor -using a finger as a conductor. `Capacitive touch -`_ -does not require you to make a ground connection as part of a circuit. + **Capacitive touch** + This test is done by interacting with the electric field of a capacitor + using a finger as a conductor. `Capacitive touch + `_ + does not require you to make a ground connection as part of a circuit. -:return: ``True`` if the pin is being touched with a finger, otherwise return ``False``.""" + :return: ``True`` if the pin is being touched with a finger, otherwise return ``False``. + """ ... - def set_touch_mode(self, value: int) -> None: - """端子のタッチモードを設定します。 + """Set the touch mode for the pin. -Example: ``pin0.set_touch_mode(pin0.CAPACITIVE)`` + Example: ``pin0.set_touch_mode(pin0.CAPACITIVE)`` -The default touch mode for the pins on the edge connector is -``resistive``. The default for the logo pin **V2** is ``capacitive``. + The default touch mode for the pins on the edge connector is + ``resistive``. The default for the logo pin **V2** is ``capacitive``. -:param value: 関連する端子の ``CAPACITIVE`` または ``RESISTIVE``。""" + :param value: ``CAPACITIVE`` or ``RESISTIVE`` from the relevant pin. + """ ... + pin0: MicroBitTouchPin -"""デジタル、アナログ、タッチ機能を備えた端子。""" +"""Pin with digital, analog and touch features.""" + pin1: MicroBitTouchPin -"""デジタル、アナログ、タッチ機能を備えた端子。""" +"""Pin with digital, analog and touch features.""" + pin2: MicroBitTouchPin -"""デジタル、アナログ、タッチ機能を備えた端子。""" +"""Pin with digital, analog and touch features.""" + pin3: MicroBitAnalogDigitalPin -"""デジタルとアナログ機能を備えた端子。""" +"""Pin with digital and analog features.""" + pin4: MicroBitAnalogDigitalPin -"""デジタルとアナログ機能を備えた端子。""" +"""Pin with digital and analog features.""" + pin5: MicroBitDigitalPin -"""デジタル機能を備えた端子。""" +"""Pin with digital features.""" + pin6: MicroBitDigitalPin -"""デジタル機能を備えた端子。""" +"""Pin with digital features.""" + pin7: MicroBitDigitalPin -"""デジタル機能を備えた端子。""" +"""Pin with digital features.""" + pin8: MicroBitDigitalPin -"""デジタル機能を備えた端子。""" +"""Pin with digital features.""" + pin9: MicroBitDigitalPin -"""デジタル機能を備えた端子。""" +"""Pin with digital features.""" + pin10: MicroBitAnalogDigitalPin -"""デジタルとアナログ機能を備えた端子。""" +"""Pin with digital and analog features.""" + pin11: MicroBitDigitalPin -"""デジタル機能を備えた端子。""" +"""Pin with digital features.""" + pin12: MicroBitDigitalPin -"""デジタル機能を備えた端子。""" +"""Pin with digital features.""" + pin13: MicroBitDigitalPin -"""デジタル機能を備えた端子。""" +"""Pin with digital features.""" + pin14: MicroBitDigitalPin -"""デジタル機能を備えた端子。""" +"""Pin with digital features.""" + pin15: MicroBitDigitalPin -"""デジタル機能を備えた端子。""" +"""Pin with digital features.""" + pin16: MicroBitDigitalPin -"""デジタル機能を備えた端子。""" +"""Pin with digital features.""" + pin19: MicroBitDigitalPin -"""デジタル機能を備えた端子。""" +"""Pin with digital features.""" + pin20: MicroBitDigitalPin -"""デジタル機能を備えた端子。""" +"""Pin with digital features.""" + pin_logo: MicroBitTouchPin -"""micro:bitの前面にあるタッチセンサー機能のあるロゴの端子です。デフォルトでは静電容量方式タッチモードになっています。""" +"""A touch sensitive logo pin on the front of the micro:bit, which by default is set to capacitive touch mode.""" + pin_speaker: MicroBitAnalogDigitalPin -"""micro:bitスピーカーをアドレスするための端子。 +"""A pin to address the micro:bit speaker. This API is intended only for use in Pulse-Width Modulation pin operations e.g. pin_speaker.write_analog(128). """ class Image: - """micro:bitのLEDディスプレイに表示するイメージ。 + """An image to show on the micro:bit LED display. -Given an image object it's possible to display it via the ``display`` API:: + Given an image object it's possible to display it via the ``display`` API:: + + display.show(Image.HAPPY) + """ - display.show(Image.HAPPY)""" HEART: Image - """「ハート」イメージ。""" + """Heart image.""" + HEART_SMALL: Image - """「小さいハート」イメージ。""" + """Small heart image.""" + HAPPY: Image - """「うれしい顔」イメージ。""" + """Happy face image.""" + SMILE: Image - """「笑顔」イメージ。""" + """Smiling mouth image.""" + SAD: Image - """「かなしい顔」イメージ。""" + """Sad face image.""" + CONFUSED: Image - """「こまり顔」イメージ。""" + """Confused face image.""" + ANGRY: Image - """「おこり顔」イメージ。""" + """Angry face image.""" + ASLEEP: Image - """「ねてる顔」イメージ。""" + """Sleeping face image.""" + SURPRISED: Image - """「びっくり顔」イメージ。""" + """Surprised face image.""" + SILLY: Image - """「へん顔」イメージ。""" + """Silly face image.""" + FABULOUS: Image - """「サングラスの笑顔」イメージ。""" + """Sunglasses face image.""" + MEH: Image - """「ふーん」イメージ""" + """Unimpressed face image.""" + YES: Image - """「チェック」イメージ。""" + """Tick image.""" + NO: Image - """「バツ」イメージ。""" + """Cross image.""" + CLOCK12: Image - """「12時を指す線」イメージ。""" + """Image with line pointing to 12 o'clock.""" + CLOCK11: Image - """「11時を指す線」イメージ。""" + """Image with line pointing to 11 o'clock.""" + CLOCK10: Image - """「10時を指す線」イメージ。""" + """Image with line pointing to 10 o'clock.""" + CLOCK9: Image - """「9時を指す線」イメージ。""" + """Image with line pointing to 9 o'clock.""" + CLOCK8: Image - """「8時を指す線」イメージ。""" + """Image with line pointing to 8 o'clock.""" + CLOCK7: Image - """「7時を指す線」イメージ。""" + """Image with line pointing to 7 o'clock.""" + CLOCK6: Image - """「6時を指す線」イメージ。""" + """Image with line pointing to 6 o'clock.""" + CLOCK5: Image - """「5時を指す線」イメージ。""" + """Image with line pointing to 5 o'clock.""" + CLOCK4: Image - """「4時を指す線」イメージ。""" + """Image with line pointing to 4 o'clock.""" + CLOCK3: Image - """「3時を指す線」イメージ。""" + """Image with line pointing to 3 o'clock.""" + CLOCK2: Image - """「2時を指す線」イメージ。""" + """Image with line pointing to 2 o'clock.""" + CLOCK1: Image - """「1時を指す線」イメージ。""" + """Image with line pointing to 1 o'clock.""" + ARROW_N: Image - """「北を指す矢印」イメージ。""" + """Image of arrow pointing north.""" + ARROW_NE: Image - """「北東を指す矢印」イメージ。""" + """Image of arrow pointing north east.""" + ARROW_E: Image - """「西を指す矢印」イメージ。""" + """Image of arrow pointing east.""" + ARROW_SE: Image - """「南東を指す矢印」イメージ。""" + """Image of arrow pointing south east.""" + ARROW_S: Image - """「南を指す矢印」イメージ。""" + """Image of arrow pointing south.""" + ARROW_SW: Image - """「南西を指す矢印」イメージ。""" + """Image of arrow pointing south west.""" + ARROW_W: Image - """「西を指す矢印」イメージ。""" + """Image of arrow pointing west.""" + ARROW_NW: Image - """「北西を指す矢印」イメージ。""" + """Image of arrow pointing north west.""" + TRIANGLE: Image - """「上向きの三角形」イメージ""" + """Image of a triangle pointing up.""" + TRIANGLE_LEFT: Image - """「左向き三角」イメージ。""" + """Image of a triangle in the left corner.""" + CHESSBOARD: Image - """チェス盤パターンで交互に点灯するLED。""" + """Alternate LEDs lit in a chessboard pattern.""" + DIAMOND: Image - """「ダイヤモンド」イメージ。""" + """Diamond image.""" + DIAMOND_SMALL: Image - """「小さいダイヤモンド」イメージ。""" + """Small diamond image.""" + SQUARE: Image - """「四角」イメージ。""" + """Square image.""" + SQUARE_SMALL: Image - """「小さい四角」イメージ。""" + """Small square image.""" + RABBIT: Image - """「うさぎ」イメージ。""" + """Rabbit image.""" + COW: Image - """「うし」イメージ。""" + """Cow image.""" + MUSIC_CROTCHET: Image - """「4分音符」イメージ。""" + """Crotchet note image.""" + MUSIC_QUAVER: Image - """「8分音符」イメージ。""" + """Quaver note image.""" + MUSIC_QUAVERS: Image - """「連結した8分音符」イメージ。""" + """Pair of quavers note image.""" + PITCHFORK: Image - """「くまで」イメージ。""" + """Pitchfork image.""" + XMAS: Image - """「クリスマスツリー」イメージ。""" + """Christmas tree image.""" + PACMAN: Image - """「パックマン」イメージ。""" + """Pac-Man arcade character image.""" + TARGET: Image - """「まと」イメージ。""" + """Target image.""" + TSHIRT: Image - """「Tシャツ」イメージ。""" + """T-shirt image.""" + ROLLERSKATE: Image - """「ローラースケート」イメージ。""" + """Rollerskate image.""" + DUCK: Image - """「あひる」イメージ。""" + """Duck image.""" + HOUSE: Image - """「家」イメージ。""" + """House image.""" + TORTOISE: Image - """「かめ」イメージ。""" + """Tortoise image.""" + BUTTERFLY: Image - """「ちょうちょ」イメージ。""" + """Butterfly image.""" + STICKFIGURE: Image - """「棒人間」イメージ。""" + """Stick figure image.""" + GHOST: Image - """「おばけ」イメージ。""" + """Ghost image.""" + SWORD: Image - """「剣」イメージ。""" + """Sword image.""" + GIRAFFE: Image - """「きりん」イメージ。""" + """Giraffe image.""" + SKULL: Image - """「がいこつ」イメージ。""" + """Skull image.""" + UMBRELLA: Image - """「かさ」イメージ。""" + """Umbrella image.""" + SNAKE: Image - """「へび」イメージ。""" + """Snake image.""" + SCISSORS: Image - """「はさみ」イメージ。""" + """Scissors image.""" + ALL_CLOCKS: List[Image] - """すべての時計イメージを順番に並べたリスト。""" - ALL_ARROWS: List[Image] - """すべての矢印イメージを順番に並べたリスト。""" + """A list containing all the CLOCK_ images in sequence.""" + ALL_ARROWS: List[Image] + """A list containing all the ARROW_ images in sequence.""" @overload def __init__(self, string: str) -> None: - """LEDの点灯パターンを示す文字列からイメージを作成します。 + """Create an image from a string describing which LEDs are lit. -``string`` has to consist of digits 0-9 arranged into lines, -describing the image, for example:: + ``string`` has to consist of digits 0-9 arranged into lines, + describing the image, for example:: - image = Image("90009:" - "09090:" - "00900:" - "09090:" - "90009") + 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 newlines (\\n) insead of the colons. + 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 newlines (\\n) insead of the colons. -:param string: イメージについて記述する文字列。""" + :param string: The string describing the image. + """ ... - @overload - def __init__(self, width: int=5, height: int=5, buffer: ReadableBuffer=None) -> None: - """``width`` 列と ``height`` 行からなる空のイメージを作成します。 + def __init__( + self, width: int = 5, height: int = 5, buffer: ReadableBuffer = None + ) -> None: + """Create an empty image with ``width`` columns and ``height`` rows. -:param width: イメージの幅を指定するオプション -:param height: イメージの高さを指定するオプション -:param buffer: イメージを初期化するために、整数値(0~9)を ``width``×``height`` 個並べた配列またはバイト列を指定します + :param width: Optional width of the image + :param height: Optional height of the image + :param buffer: Optional array or bytes of ``width``×``height`` integers in range 0-9 to initialize the image -Examples:: + Examples:: - Image(2, 2, b'\x08\x08\x08\x08') - Image(2, 2, bytearray([9,9,9,9])) + Image(2, 2, b'\x08\x08\x08\x08') + Image(2, 2, bytearray([9,9,9,9])) -These create 2 x 2 pixel images at full brightness.""" + These create 2 x 2 pixel images at full brightness. + """ ... - def width(self) -> int: - """列数を取得します。 + """Get the number of columns. -:return: The number of columns in the image""" + :return: The number of columns in the image + """ ... - def height(self) -> int: - """行数を取得します。 + """Get the number of rows. -:return: The number of rows in the image""" + :return: The number of rows in the image + """ ... - def set_pixel(self, x: int, y: int, value: int) -> None: - """1ピクセルの明るさを設定します。 + """Set the brightness of a pixel. -Example: ``my_image.set_pixel(0, 0, 9)`` + Example: ``my_image.set_pixel(0, 0, 9)`` -:param x: 列数 -:param y: 行数 -:param value: 明るさを 0(暗い)から 9(明るい)までの整数値で指定します + :param x: The column number + :param y: The row number + :param value: The brightness as an integer 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``.""" + 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: - """1ピクセルの明るさを取得します。 + """Get the brightness of a pixel. -Example: ``my_image.get_pixel(0, 0)`` + Example: ``my_image.get_pixel(0, 0)`` -:param x: 列数 -:param y: 行数 -:return: The brightness as an integer between 0 and 9.""" + :param x: The column number + :param y: The row number + :return: The brightness as an integer between 0 and 9. + """ ... - def shift_left(self, n: int) -> Image: - """画像を左にシフトした新しいイメージを作成します。 + """Create a new image by shifting the picture left. -Example: ``Image.HEART_SMALL.shift_left(1)`` + Example: ``Image.HEART_SMALL.shift_left(1)`` -:param n: シフトする列数 -:return: The shifted image""" + :param n: The number of columns to shift by + :return: The shifted image + """ ... - def shift_right(self, n: int) -> Image: - """画像を右にシフトした新しいイメージを作成します。 + """Create a new image by shifting the picture right. -Example: ``Image.HEART_SMALL.shift_right(1)`` + Example: ``Image.HEART_SMALL.shift_right(1)`` -:param n: シフトする列数 -:return: The shifted image""" + :param n: The number of columns to shift by + :return: The shifted image + """ ... - def shift_up(self, n: int) -> Image: - """画像を上にシフトした新しいイメージを作成します。 + """Create a new image by shifting the picture up. -Example: ``Image.HEART_SMALL.shift_up(1)`` + Example: ``Image.HEART_SMALL.shift_up(1)`` -:param n: シフトする行数 -:return: The shifted image""" + :param n: The number of rows to shift by + :return: The shifted image + """ ... - def shift_down(self, n: int) -> Image: - """画像を下にシフトした新しいイメージを作成します。 + """Create a new image by shifting the picture down. -Example: ``Image.HEART_SMALL.shift_down(1)`` + Example: ``Image.HEART_SMALL.shift_down(1)`` -:param n: シフトする行数 -:return: The shifted image""" + :param n: The number of rows to shift by + :return: The shifted image + """ ... - def crop(self, x: int, y: int, w: int, h: int) -> Image: - """画像をトリミングした新しいイメージを作成します。 + """Create a new image by cropping the picture. -Example: ``Image.HEART.crop(1, 1, 3, 3)`` + Example: ``Image.HEART.crop(1, 1, 3, 3)`` -:param x: トリミングするオフセット列 -:param y: トリミングするオフセット行 -:param w: トリミングする幅 -:param h: トリミングする高さ -:return: The new image""" + :param x: The crop offset column + :param y: The crop offset row + :param w: The crop width + :param h: The crop height + :return: The new image + """ ... - def copy(self) -> Image: - """イメージ全体のコピーを作成します。 + """Create an exact copy of the image. -Example: ``Image.HEART.copy()`` + Example: ``Image.HEART.copy()`` -:return: The new image""" + :return: The new image + """ ... - def invert(self) -> Image: - """元イメージのピクセルの明るさを反転した新しいイメージ作成します。 + """Create a new image by inverting the brightness of the pixels in the + source image. -Example: ``Image.SMALL_HEART.invert()`` + Example: ``Image.SMALL_HEART.invert()`` -:return: The new image.""" + :return: The new image. + """ ... - def fill(self, value: int) -> None: - """イメージのすべてのピクセルの明るさを設定します。 + """Set the brightness of all the pixels in the image. -Example: ``my_image.fill(5)`` + Example: ``my_image.fill(5)`` -:param value: 0(暗い)から 9(明るい)までの数値で新しい明るさを指定します。 + :param value: The new brightness as a number 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``.""" + 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: - """このイメージに別のイメージから領域をコピーします。 - -Example: ``my_image.blit(Image.HEART, 1, 1, 3, 3, 1, 1)`` - -:param src: 元イメージ -:param x: 元イメージの開始列オフセット -:param y: 元イメージの開始行オフセット -:param w: コピーする列数 -:param h: コピーする行数 -:param xdest: このイメージで変更する列オフセット -:param ydest: このイメージで変更する行オフセット - -Pixels outside the source image are treated as having a brightness 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 blit( + self, + src: Image, + x: int, + y: int, + w: int, + h: int, + xdest: int = 0, + ydest: int = 0, + ) -> None: + """Copy an area from another image into this image. + + Example: ``my_image.blit(Image.HEART, 1, 1, 3, 3, 1, 1)`` + + :param src: The source image + :param x: The starting column offset in the source image + :param y: The starting row offset in the source image + :param w: The number of columns to copy + :param h: The number of rows to copy + :param xdest: The column offset to modify in this image + :param ydest: The row offset to modify in this image + + Pixels outside the source image are treated as having a brightness 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: - """2つのイメージの各ピクセルの明るさを足した新しいイメージを作成します。 + """Create a new image by adding the brightness values from the two + images for each pixel. -Example: ``Image.HEART + Image.HAPPY`` + Example: ``Image.HEART + Image.HAPPY`` -:param other: 加算するイメージ。""" + :param other: The image to add. + """ ... - def __sub__(self, other: Image) -> Image: - """このイメージから他のイメージの明るさの値を引いた新しいイメージを作成します。 + """Create a new image by subtracting the brightness values of the + other image from this image. -Example: ``Image.HEART - Image.HEART_SMALL`` + Example: ``Image.HEART - Image.HEART_SMALL`` -:param other: 減算するイメージ。""" + :param other: The image to subtract. + """ ... - def __mul__(self, n: float) -> Image: - """各ピクセルの明るさを ``n`` 倍した新しいイメージを作成します。 + """Create a new image by multiplying the brightness of each pixel by + ``n``. -Example: ``Image.HEART * 0.5`` + Example: ``Image.HEART * 0.5`` -:param n: 乗算する値。""" + :param n: The value to multiply by. + """ ... - def __truediv__(self, n: float) -> Image: - """各ピクセルの明るさを ``n`` で割った新しいイメージを作成します。 + """Create a new image by dividing the brightness of each pixel by + ``n``. -Example: ``Image.HEART / 2`` + Example: ``Image.HEART / 2`` -:param n: 除算する値。""" + :param n: The value to divide by. + """ ... class SoundEvent: LOUD: SoundEvent - """拍手や叫び声などで ``quiet`` から ``loud`` へのサウンドイベントの変化を表します。""" + """Represents the transition of sound events, from ``quiet`` to ``loud`` like clapping or shouting.""" + QUIET: SoundEvent - """発話やBGMなどで ``loud`` から ``quiet`` へのサウンドイベントの変化を表します。""" + """Represents the transition of sound events, from ``loud`` to ``quiet`` like speaking or background music.""" class Sound: - """内蔵のサウンドは ``audio.play(Sound.NAME)`` で呼び出すことができます。""" + """The built-in sounds can be called using ``audio.play(Sound.NAME)``.""" + GIGGLE: Sound - """「くすくす笑う」サウンド。""" + """Giggling sound.""" + HAPPY: Sound - """「ハッピー」サウンド。""" + """Happy sound.""" + HELLO: Sound - """「ハロー」サウンド""" + """Greeting sound.""" + MYSTERIOUS: Sound - """「ミステリアス」サウンド。""" + """Mysterious sound.""" + SAD: Sound - """「悲しい」サウンド。""" + """Sad sound.""" + SLIDE: Sound - """「するする動く」サウンド。""" + """Sliding sound.""" + SOARING: Sound - """「舞い上がる」サウンド。""" + """Soaring sound.""" + SPRING: Sound - """「バネ」サウンド。""" + """Spring sound.""" + TWINKLE: Sound - """「キラキラ」サウンド。""" + """Twinkling sound.""" + YAWN: Sound - """「あくび」サウンド。""" \ No newline at end of file + """Yawning sound.""" diff --git a/lang/ja/typeshed/stdlib/microbit/accelerometer.pyi b/lang/ja/typeshed/stdlib/microbit/accelerometer.pyi index 8f689c7..bac82c0 100644 --- a/lang/ja/typeshed/stdlib/microbit/accelerometer.pyi +++ b/lang/ja/typeshed/stdlib/microbit/accelerometer.pyi @@ -1,103 +1,115 @@ -"""micro:bitの加速度測定とジェスチャー認識をします。""" +"""Measure the acceleration of the micro:bit and recognise gestures. +""" + from typing import Tuple def get_x() -> int: - """``x`` 軸の加速度測定値をミリg単位で取得します。 + """Get the acceleration measurement in the ``x`` axis in milli-g. -Example: ``accelerometer.get_x()`` + Example: ``accelerometer.get_x()`` -:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" + :return: A positive or negative integer depending on direction in the range +/- 2000mg. + """ ... def get_y() -> int: - """``y`` 軸の加速度測定値をミリg単位で取得します。 + """Get the acceleration measurement in the ``y`` axis in milli-g. -Example: ``accelerometer.get_y()`` + Example: ``accelerometer.get_y()`` -:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" + :return: A positive or negative integer depending on direction in the range +/- 2000mg. + """ ... def get_z() -> int: - """``z`` 軸の加速度測定値をミリg単位で取得します。 + """Get the acceleration measurement in the ``z`` axis in milli-g. -Example: ``accelerometer.get_z()`` + Example: ``accelerometer.get_z()`` -:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" + :return: A positive or negative integer depending on direction in the range +/- 2000mg. + """ ... def get_values() -> Tuple[int, int, int]: - """すべての軸の加速度測定値をタプルとして一度に取得します。 + """Get the acceleration measurements in all axes at once as a tuple. -Example: ``x, y, z = accelerometer.get_values()`` + Example: ``x, y, z = accelerometer.get_values()`` -:return: a three-element tuple of integers ordered as X, Y, Z, each value a positive or negative integer depending on direction in the range +/- 2000mg""" + :return: a three-element tuple of integers ordered as X, Y, Z, each value a positive or negative integer depending on direction in the range +/- 2000mg + """ ... def get_strength() -> int: - """すべての軸を合成した加速度測定値を正の整数値で得ます。これは X軸、Y軸、Z軸のピタゴラス和になります。 + """Get the acceleration measurement of all axes combined, as a positive integer. This is the Pythagorean sum of the X, Y and Z axes. -Example: ``accelerometer.get_strength()`` + Example: ``accelerometer.get_strength()`` -:return: The combined acceleration strength of all the axes, in milli-g.""" + :return: The combined acceleration strength of all the axes, in milli-g. + """ ... def current_gesture() -> str: - """現在のジェスチャーの名前を取得します。 + """Get the name of the current gesture. -Example: ``accelerometer.current_gesture()`` + Example: ``accelerometer.current_gesture()`` -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. + 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. -:return: The current gesture""" + :return: The current gesture + """ ... def is_gesture(name: str) -> bool: - """指定した名前のジェスチャーが現在アクティブであるかどうかを確認します。 + """Check if the named gesture is currently active. -Example: ``accelerometer.is_gesture('shake')`` + Example: ``accelerometer.is_gesture('shake')`` -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. + 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. -:param name: ジェスチャー名。 -:return: ``True`` if the gesture is active, ``False`` otherwise.""" + :param name: The gesture name. + :return: ``True`` if the gesture is active, ``False`` otherwise. + """ ... def was_gesture(name: str) -> bool: - """直前の呼び出し以降に、指定した名前のジェスチャーがアクティブになったかどうかを確認します。 + """Check if the named gesture was active since the last call. -Example: ``accelerometer.was_gesture('shake')`` + Example: ``accelerometer.was_gesture('shake')`` -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. + 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. -:param name: ジェスチャー名。 -:return: ``True`` if the gesture was active since the last call, ``False`` otherwise.""" + :param name: The gesture name. + :return: ``True`` if the gesture was active since the last call, ``False`` otherwise. + """ def get_gestures() -> Tuple[str, ...]: - """ジェスチャー履歴のタプルを返します。 + """Return a tuple of the gesture history. -Example: ``accelerometer.get_gestures()`` + Example: ``accelerometer.get_gestures()`` -Clears the gesture history before returning. + Clears the gesture history before returning. -Gestures are not updated in the background so there needs to be constant -calls to some accelerometer method to do the gesture detection. Usually -gestures can be detected using a loop with a small :func:`microbit.sleep` delay. + Gestures are not updated in the background so there needs to be constant + calls to some accelerometer method to do the gesture detection. Usually + gestures can be detected using a loop with a small :func:`microbit.sleep` delay. -:return: The history as a tuple, most recent last.""" + :return: The history as a tuple, most recent last. + """ ... def set_range(value: int) -> None: - """加速度センサーの感度範囲を g (標準重力)で設定します。設定値は、ハードウェアがサポートする最も近い値、すなわち ``2``、``4``、``8`` g のいずれかに丸められます。 + """Set the accelerometer sensitivity range, in g (standard gravity), to the closest values supported by the hardware, so it rounds to either ``2``, ``4``, or ``8`` g. -Example: ``accelerometer.set_range(8)`` + Example: ``accelerometer.set_range(8)`` -:param value: 加速度センサーの新しい感度範囲。``g`` 単位の整数値で指定します。""" \ No newline at end of file + :param value: New range for the accelerometer, an integer in ``g``. + """ diff --git a/lang/ja/typeshed/stdlib/microbit/audio.pyi b/lang/ja/typeshed/stdlib/microbit/audio.pyi index 309077d..3b1e327 100644 --- a/lang/ja/typeshed/stdlib/microbit/audio.pyi +++ b/lang/ja/typeshed/stdlib/microbit/audio.pyi @@ -1,124 +1,160 @@ -"""micro:bitでサウンドを再生します(V1との互換のために ``audio`` をインポートしてください)。""" +"""Play sounds using the micro:bit (import ``audio`` for V1 compatibility). +""" + from ..microbit import MicroBitDigitalPin, Sound, pin0 from typing import ClassVar, Iterable, Union -def play(source: Union[Iterable[AudioFrame], Sound, SoundEffect], wait: bool=True, pin: MicroBitDigitalPin=pin0, return_pin: Union[MicroBitDigitalPin, None]=None) -> None: - """内蔵サウンド、サウンド効果、カスタム化したオーディオフレームのいずれかを再生します。 +def play( + source: Union[Iterable[AudioFrame], Sound, SoundEffect], + wait: bool = True, + pin: MicroBitDigitalPin = pin0, + return_pin: Union[MicroBitDigitalPin, None] = None, +) -> None: + """Play a built-in sound, sound effect or custom audio frames. -Example: ``audio.play(Sound.GIGGLE)`` + Example: ``audio.play(Sound.GIGGLE)`` -:param source: ``Sound.GIGGLE`` などの内蔵の``Sound``、``SoundEffect``、``AudioFrame`` オブジェクトのイテラブルであるサンプルデータのいずれか。 -:param wait: ``wait`` が ``True`` の場合、サウンドの再生が終わるまでこの関数がブロックします。 -:param pin: (ピン) 出力端子をデフォルトの ``pin0`` から変えるためのオプション引数です。音を鳴らしたくない場合は ``pin=None`` を指定します。 -:param return_pin: グランドではなく外部スピーカーに接続する差動エッジコネクタの端子 -を指定します。**V2** ではこの指定を無視します。""" + :param source: A built-in ``Sound`` such as ``Sound.GIGGLE``, a ``SoundEffect`` or sample data as an iterable of ``AudioFrame`` objects. + :param wait: If ``wait`` is ``True``, this function will block until the sound is complete. + :param pin: An optional argument to specify the output pin can be used to override the default of ``pin0``. If we do not want any sound to play we can use ``pin=None``. + :param return_pin: Specifies a differential edge connector pin to connect to an external speaker instead of ground. This is ignored for the **V2** revision. + """ def is_playing() -> bool: - """オーディオが再生中であるかどうかを確認します。 + """Check whether a sound is playing. -Example: ``audio.is_playing()`` + Example: ``audio.is_playing()`` -:return: ``True`` if audio is playing, otherwise ``False``.""" + :return: ``True`` if audio is playing, otherwise ``False``.""" ... def stop() -> None: - """すべてのオーディオ再生を停止します。 + """Stop all audio playback. -Example: ``audio.stop()``""" + Example: ``audio.stop()`` + """ ... class SoundEffect: - """コンストラクタや属性で設定したパラメータのセットで構成されるサウンド効果。""" + """A sound effect, composed by a set of parameters configured via the constructor or attributes.""" + WAVEFORM_SINE: ClassVar[int] - """``waveform`` パラメータに指定できる「サイン波」オプション。""" + """Sine wave option used for the ``waveform`` parameter.""" + WAVEFORM_SAWTOOTH: ClassVar[int] - """``waveform`` パラメータに指定できる「のこぎり波」オプション。""" + """Sawtooth wave option used for the ``waveform`` parameter.""" + WAVEFORM_TRIANGLE: ClassVar[int] - """``waveform`` パラメータに指定できる「三角波」オプション。""" + """Triangle wave option used for the ``waveform`` parameter.""" + WAVEFORM_SQUARE: ClassVar[int] - """``waveform`` パラメータに指定できる「矩形波」オプション。""" + """Square wave option used for the ``waveform`` parameter.""" + WAVEFORM_NOISE: ClassVar[int] - """``waveform`` パラメータに指定できる「ノイズ」オプション。""" + """Noise option used for the ``waveform`` parameter.""" + SHAPE_LINEAR: ClassVar[int] - """``shape`` パラメータに指定できる「リニア補間」オプション。""" + """Linear interpolation option used for the ``shape`` parameter.""" + SHAPE_CURVE: ClassVar[int] - """``shape`` パラメータに指定できる「カーブ補間」オプション。""" + """Curve interpolation option used for the ``shape`` parameter.""" + SHAPE_LOG: ClassVar[int] - """``shape`` パラメータに指定できる「対数補間」オプション。""" + """Logarithmic interpolation option used for the ``shape`` parameter.""" + FX_NONE: ClassVar[int] - """``fx`` パラメータに指定できる「効果なし」オプション。""" + """No effect option used for the ``fx`` parameter.""" + FX_TREMOLO: ClassVar[int] - """``fx`` パラメータに指定できる「トレモロ効果」オプション。""" + """Tremolo effect option used for the ``fx`` parameter.""" + FX_VIBRATO: ClassVar[int] - """``fx`` パラメータに指定できる「ビブラート効果」オプション。""" + """Vibrato effect option used for the ``fx`` parameter.""" + FX_WARBLE: ClassVar[int] - """``fx`` パラメータに指定できる「ワブル効果」オプション。""" + """Warble effect option used for the ``fx`` parameter.""" + freq_start: int - """開始周波数。単位はヘルツ(Hz)で、``0``から``9999``の範囲の数値です。""" + """Start frequency in Hertz (Hz), a number between ``0`` and ``9999``""" + freq_end: int - """終了周波数。単位はヘルツ(Hz)で、``0``から``9999``の範囲の数値です。""" + """End frequency in Hertz (Hz), a number between ``0`` and ``9999``""" + duration: int - """サウンドの長さ。``0`` から``9999``の範囲の数値です。""" - vol_start: int - """開始音量。``0``から``255``の範囲の数値です。""" - vol_end: int - """終了音量。``0``から``255``の範囲の数値です。""" - waveform: int - """波形の種類。次の値のいずれか: ``WAVEFORM_SINE``、 ``WAVEFORM_SAWTOOTH``、``WAVEFORM_TRIANGLE``、 ``WAVEFORM_SQUARE``、``WAVEFORM_NOISE`` (ランダムに生成したノイズ)""" - fx: int - """サウンドに追加する効果。次の値のいずれか: ``FX_TREMOLO``、``FX_VIBRATO``、``FX_WARBLE``、``FX_NONE``""" - shape: int - """開始周波数と終了周波数の補間曲線の種類で、波形の違いにより周波数の変化率が異なります。次の値のうちのいずれか: ``SHAPE_LINEAR``、``SHAPE_CURVE``、``SHAPE_LOG``""" + """Duration of the sound in milliseconds, a number between ``0`` and ``9999``""" - def __init__(self, freq_start: int=500, freq_end: int=2500, duration: int=500, vol_start: int=255, vol_end: int=0, waveform: int=WAVEFORM_SQUARE, fx: int=FX_NONE, shape: int=SHAPE_LOG): - """新しいサウンド効果を作成します。 + vol_start: int + """Start volume value, a number between ``0`` and ``255``""" -Example: ``my_effect = SoundEffect(duration=1000)`` + vol_end: int + """End volume value, a number between ``0`` and ``255``""" -All the parameters are optional, with default values as shown above, and -they can all be modified via attributes of the same name. For example, we -can first create an effect ``my_effect = SoundEffect(duration=1000)``, -and then change its attributes ``my_effect.duration = 500``. + waveform: int + """Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise)""" -:param freq_start: 開始周波数。単位はヘルツ(Hz)で、``0``から``9999``の範囲の数値です。 -:param freq_end: 終了周波数。単位はヘルツ(Hz)で、``0``から``9999``の範囲の数値です。 -:param duration: サウンドの長さ。単位はミリ秒で、``0`` から``9999``の範囲の数値です。 -:param vol_start: 開始音量。``0``から``255``の範囲の数値です。 -:param vol_end: 終了音量。``0``から``255``の範囲の数値です。 -:param waveform: 波形の種類。次の値のいずれか: ``WAVEFORM_SINE``、 ``WAVEFORM_SAWTOOTH``、``WAVEFORM_TRIANGLE``、 ``WAVEFORM_SQUARE``、``WAVEFORM_NOISE`` (ランダムに生成したノイズ)。 -:param fx: サウンドに追加する効果。次の値のいずれか: ``FX_TREMOLO``、``FX_VIBRATO``、``FX_WARBLE``、``FX_NONE`` -:param shape: 開始周波数と終了周波数の補間曲線の種類で、波形の違いにより周波数の変化率が異なります。次の値のうちのいずれか: ``SHAPE_LINEAR``、``SHAPE_CURVE``、``SHAPE_LOG``""" + fx: int + """Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``""" + shape: int + """The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``""" + + def __init__( + self, + freq_start: int = 500, + freq_end: int = 2500, + duration: int = 500, + vol_start: int = 255, + vol_end: int = 0, + waveform: int = WAVEFORM_SQUARE, + fx: int = FX_NONE, + shape: int = SHAPE_LOG, + ): + """Create a new sound effect. + + Example: ``my_effect = SoundEffect(duration=1000)`` + + All the parameters are optional, with default values as shown above, and + they can all be modified via attributes of the same name. For example, we + can first create an effect ``my_effect = SoundEffect(duration=1000)``, + and then change its attributes ``my_effect.duration = 500``. + + :param freq_start: Start frequency in Hertz (Hz), a number between ``0`` and ``9999``. + :param freq_end: End frequency in Hertz (Hz), a number between ``0`` and ``9999``. + :param duration: Duration of the sound in milliseconds, a number between ``0`` and ``9999``. + :param vol_start: Start volume value, a number between ``0`` and ``255``. + :param vol_end: End volume value, a number between ``0`` and ``255``. + :param waveform: Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise). + :param fx: Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``. + :param shape: The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``. + """ def copy(self) -> SoundEffect: - """この ``SoundEffect`` のコピーを作成します。 + """Create a copy of this ``SoundEffect``. -Example: ``sound_2 = sound_1.copy()`` + Example: ``sound_2 = sound_1.copy()`` -:return: A copy of the SoundEffect.""" + :return: A copy of the SoundEffect. + """ class AudioFrame: - """``AudioFrame`` オブジェクトは32個のサンプルからなるリストです。それぞのサンプルは符号なしバイト(0〜255の整数)です。 + """An ``AudioFrame`` object is a list of 32 samples each of which is a unsigned byte + (whole number between 0 and 255). -It takes just over 4 ms to play a single frame. + It takes just over 4 ms to play a single frame. -Example:: + Example:: - frame = AudioFrame() - for i in range(len(frame)): - frame[i] = 252 - i * 8""" + frame = AudioFrame() + for i in range(len(frame)): + frame[i] = 252 - i * 8 + """ def copyfrom(self, other: AudioFrame) -> None: - """この ``AudioFrame`` のデータを、別の ``AudioFrame`` インスタンスのデータで上書きします。 - -Example: ``my_frame.copyfrom(source_frame)`` - -:param other: コピーするデータを持つ ``AudioFrame`` インスタンス。""" - - def __len__(self) -> int: - ... + """Overwrite the data in this ``AudioFrame`` with the data from another ``AudioFrame`` instance. - def __setitem__(self, key: int, value: int) -> None: - ... + Example: ``my_frame.copyfrom(source_frame)`` - def __getitem__(self, key: int) -> int: - ... \ No newline at end of file + :param other: ``AudioFrame`` instance from which to copy the data. + """ + def __len__(self) -> int: ... + def __setitem__(self, key: int, value: int) -> None: ... + def __getitem__(self, key: int) -> int: ... diff --git a/lang/ja/typeshed/stdlib/microbit/compass.pyi b/lang/ja/typeshed/stdlib/microbit/compass.pyi index ccbd0f8..c74a47b 100644 --- a/lang/ja/typeshed/stdlib/microbit/compass.pyi +++ b/lang/ja/typeshed/stdlib/microbit/compass.pyi @@ -1,70 +1,78 @@ -"""内蔵のコンパスを使います。 (方位磁針(コンパス))""" +"""Use the built-in compass. +""" def calibrate() -> None: - """調整処理を開始します。 + """Starts the calibration process. -Example: ``compass.calibrate()`` + Example: ``compass.calibrate()`` -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.""" + 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: - """コンパスが調整されているかどうかを確認します。 + """Check is the compass is calibrated. -Example: ``compass.is_calibrated()`` + Example: ``compass.is_calibrated()`` -:return: ``True`` if the compass has been successfully calibrated, ``False`` otherwise.""" + :return: ``True`` if the compass has been successfully calibrated, ``False`` otherwise. + """ ... def clear_calibration() -> None: - """調整を取り消し、コンパスを未調整状態にします。 + """Undoes the calibration, making the compass uncalibrated again. -Example: ``compass.clear_calibration()``""" + Example: ``compass.clear_calibration()`` + """ ... def get_x() -> int: - """``x`` 軸の磁場強度を取得します。 + """Get the magnetic field strength on the ``x`` axis. -Example: ``compass.get_x()`` + Example: ``compass.get_x()`` -Call ``calibrate`` first or the results will be inaccurate. + Call ``calibrate`` first or the results will be inaccurate. -:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" + :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. + """ ... def get_y() -> int: - """``y`` 軸の磁場強度を取得します。 + """Get the magnetic field strength on the ``y`` axis. -Example: ``compass.get_y()`` + Example: ``compass.get_y()`` -Call ``calibrate`` first or the results will be inaccurate. + Call ``calibrate`` first or the results will be inaccurate. -:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" + :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. + """ ... def get_z() -> int: - """``z`` 軸の磁場強度を取得します。 + """Get the magnetic field strength on the ``z`` axis. -Example: ``compass.get_z()`` + Example: ``compass.get_z()`` -Call ``calibrate`` first or the results will be inaccurate. + Call ``calibrate`` first or the results will be inaccurate. -:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" + :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. + """ ... def heading() -> int: - """コンパスの方位を取得します。 + """Get the compass heading. -Example: ``compass.heading()`` + Example: ``compass.heading()`` -:return: An integer in the range from 0 to 360, representing the angle in degrees, clockwise, with north as 0.""" + :return: An integer in the range from 0 to 360, representing the angle in degrees, clockwise, with north as 0. + """ ... def get_field_strength() -> int: - """デバイスのまわりの磁場の強さを取得します。 + """Get the magnitude of the magnetic field around the device. -Example: ``compass.get_field_strength()`` + Example: ``compass.get_field_strength()`` -:return: An integer indication of the magnitude of the magnetic field in nano tesla.""" - ... \ No newline at end of file + :return: An integer indication of the magnitude of the magnetic field in nano tesla.""" + ... diff --git a/lang/ja/typeshed/stdlib/microbit/display.pyi b/lang/ja/typeshed/stdlib/microbit/display.pyi index 8cd651f..aa4013e 100644 --- a/lang/ja/typeshed/stdlib/microbit/display.pyi +++ b/lang/ja/typeshed/stdlib/microbit/display.pyi @@ -1,92 +1,115 @@ -"""5×5 LED ディスプレイ上にテキスト、イメージ、アニメーションを表示します。""" +"""Show text, images and animations on the 5×5 LED display. +""" + from ..microbit import Image from typing import Union, overload, Iterable def get_pixel(x: int, y: int) -> int: - """``x`` 列 ``y`` 行の LEDの明るさを取得します。 + """Get the brightness of the LED at column ``x`` and row ``y``. -Example: ``display.get_pixel(0, 0)`` + Example: ``display.get_pixel(0, 0)`` -:param x: ディスプレイの列 (0..4) -:param y: ディスプレイの行 (0..4) -:return: A number between 0 (off) and 9 (bright)""" + :param x: The display column (0..4) + :param y: The display row (0..4) + :return: A number between 0 (off) and 9 (bright) + """ ... def set_pixel(x: int, y: int, value: int) -> None: - """``x`` 列 ``y`` 行の LEDの明るさを設定します。 + """Set the brightness of the LED at column ``x`` and row ``y``. -Example: ``display.set_pixel(0, 0, 9)`` + Example: ``display.set_pixel(0, 0, 9)`` -:param x: ディスプレイの列 (0..4) -:param y: ディスプレイの行 (0..4) -:param value: 0(オフ)から 9(明るい)までの明るさ""" + :param x: The display column (0..4) + :param y: The display row (0..4) + :param value: The brightness between 0 (off) and 9 (bright) + """ ... def clear() -> None: - """すべての LED の明るさを 0(オフ)に設定します。 + """Set the brightness of all LEDs to 0 (off). -Example: ``display.clear()``""" + Example: ``display.clear()`` + """ ... -def show(image: Union[str, float, int, Image, Iterable[Image]], delay: int=400, wait: bool=True, loop: bool=False, clear: bool=False) -> None: - """イメージ、文字、数字をLEDディスプレイに表示します。 +def show( + image: Union[str, float, int, Image, Iterable[Image]], + delay: int = 400, + wait: bool = True, + loop: bool = False, + clear: bool = False, +) -> None: + """Shows images, letters or digits on the LED display. -Example: ``display.show(Image.HEART)`` + Example: ``display.show(Image.HEART)`` -When ``image`` is an image or a list of images then each image is displayed in turn. -If ``image`` is a string or number, each letter or digit is displayed in turn. + When ``image`` is an image or a list of images then each image is displayed in turn. + If ``image`` is a string or number, each letter or digit is displayed in turn. -:param image: 表示する文字列、数値、イメージ、イメージのリスト。 -:param delay: それぞれの文字、数字、イメージは ``delay`` ミリ秒間隔で表示されます。 -:param wait: ``wait`` が ``True`` である場合、アニメーションが終了するまで関数がブロックし、 そうでない場合にはバックグラウンドで実行されます。 -:param loop: ``loop`` が ``True`` である場合、アニメーションを永遠に繰り返します。 -:param clear: ``clear`` が ``True`` である場合、シーケンスの終了後にディスプレイをクリアします。 + :param image: A string, number, image or list of images to show. + :param delay: Each letter, digit or image is shown with ``delay`` milliseconds between them. + :param wait: If ``wait`` is ``True``, this function will block until the animation is finished, otherwise the animation will happen in the background. + :param loop: If ``loop`` is ``True``, the animation will repeat forever. + :param clear: If ``clear`` is ``True``, the display will be cleared after the sequence has finished. -The ``wait``, ``loop`` and ``clear`` arguments must be specified using their keyword.""" + The ``wait``, ``loop`` and ``clear`` arguments must be specified using their keyword. + """ ... -def scroll(text: Union[str, float, int], delay: int=150, wait: bool=True, loop: bool=False, monospace: bool=False) -> None: - """LEDディスプレィ上に数値やテキストをスクロール表示します。 - -Example: ``display.scroll('micro:bit')`` - -:param text: スクロールする文字列。``text`` が整数か浮動小数点数であれば、まず ``str()`` を使って文字列に変換します。 -:param delay: ``delay`` パラメータはテキストのスクロール速度を制御します。 -:param wait: ``wait`` が ``True`` である場合、アニメーションが終了するまで関数がブロックし、 そうでない場合にはバックグラウンドで実行されます。 -:param loop: ``loop`` が ``True`` である場合、アニメーションを永遠に繰り返します。 -:param monospace: ``monospace`` が ``True`` である場合、文字の幅が 5 ピクセルになり、そうでない場合にはスクロール時の文字間の幅が 1 ピクセルになります。 - -The ``wait``, ``loop`` and ``monospace`` arguments must be specified -using their keyword.""" +def scroll( + text: Union[str, float, int], + delay: int = 150, + wait: bool = True, + loop: bool = False, + monospace: bool = False, +) -> None: + """Scrolls a number or text on the LED display. + + Example: ``display.scroll('micro:bit')`` + + :param text: The string to scroll. If ``text`` is an integer or float it is first converted to a string using ``str()``. + :param delay: The ``delay`` parameter controls how fast the text is scrolling. + :param wait: If ``wait`` is ``True``, this function will block until the animation is finished, otherwise the animation will happen in the background. + :param loop: If ``loop`` is ``True``, the animation will repeat forever. + :param monospace: 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. + + The ``wait``, ``loop`` and ``monospace`` arguments must be specified + using their keyword. + """ ... def on() -> None: - """ディスプレイをオンにします。 + """Turn on the LED display. -Example: ``display.on()``""" + Example: ``display.on()`` + """ ... def off() -> None: - """LEDディスプレイをオフにします(ディスプレイを無効にすることにより、GPIO端子を他の目的に再利用できるようになります)。 + """Turn off the LED display (disabling the display allows you to re-use the GPIO pins for other purposes). -Example: ``display.off()``""" + Example: ``display.off()`` + """ ... def is_on() -> bool: - """LEDディスプレイが有効であるかどうかを確認します。 + """Check whether the LED display is enabled. -Example: ``display.is_on()`` + Example: ``display.is_on()`` -:return: ``True`` if the display is on, otherwise returns ``False``.""" + :return: ``True`` if the display is on, otherwise returns ``False``. + """ ... def read_light_level() -> int: - """ディスプレイのまわりの光量を読み取ります。 + """Read the light level. -Example: ``display.read_light_level()`` + Example: ``display.read_light_level()`` -Uses the display's LEDs in reverse-bias mode to sense the amount of light -falling on the display. + Uses the display's LEDs in reverse-bias mode to sense the amount of light + falling on the display. -:return: An integer between 0 and 255 representing the light level, with larger meaning more light.""" - ... \ No newline at end of file + :return: An integer between 0 and 255 representing the light level, with larger meaning more light. + """ + ... diff --git a/lang/ja/typeshed/stdlib/microbit/i2c.pyi b/lang/ja/typeshed/stdlib/microbit/i2c.pyi index 4d57a54..df26efa 100644 --- a/lang/ja/typeshed/stdlib/microbit/i2c.pyi +++ b/lang/ja/typeshed/stdlib/microbit/i2c.pyi @@ -1,49 +1,57 @@ -"""I²C バスプロトコルでデバイスと通信します。""" +"""Communicate with devices using the I²C bus protocol. +""" + from _typeshed import ReadableBuffer from ..microbit import MicroBitDigitalPin, pin19, pin20 from typing import List -def init(freq: int=100000, sda: MicroBitDigitalPin=pin20, scl: MicroBitDigitalPin=pin19) -> None: - """ペリフェラルを再初期化します。 +def init( + freq: int = 100000, sda: MicroBitDigitalPin = pin20, scl: MicroBitDigitalPin = pin19 +) -> None: + """Re-initialize a peripheral. -Example: ``i2c.init()`` + Example: ``i2c.init()`` -:param freq: クロック周波数 -:param sda: ``sda`` 端子(デフォルトは 20) -:param scl: ``scl`` 端子(デフォルトは 19) + :param freq: clock frequency + :param sda: ``sda`` pin (default 20) + :param scl: ``scl`` pin (default 19) -On a micro:bit V1 board, changing the I²C pins from defaults will make -the accelerometer and compass stop working, as they are connected -internally to those pins. This warning does not apply to the **V2** -revision of the micro:bit as this has `separate I²C lines `_ -for the motion sensors and the edge connector.""" + On a micro:bit V1 board, changing the I²C pins from defaults will make + the accelerometer and compass stop working, as they are connected + internally to those pins. This warning does not apply to the **V2** + revision of the micro:bit as this has `separate I²C lines `_ + for the motion sensors and the edge connector. + """ ... def scan() -> List[int]: - """バスをスキャンしてデバイスを探します。 + """Scan the bus for devices. -Example: ``i2c.scan()`` + Example: ``i2c.scan()`` -:return: A list of 7-bit addresses corresponding to those devices that responded to the scan.""" + :return: A list of 7-bit addresses corresponding to those devices that responded to the scan. + """ ... -def read(addr: int, n: int, repeat: bool=False) -> bytes: - """デバイスからバイト列を読み取ります。 +def read(addr: int, n: int, repeat: bool = False) -> bytes: + """Read bytes from a device. -Example: ``i2c.read(0x50, 64)`` + Example: ``i2c.read(0x50, 64)`` -:param addr: デバイスの7ビットアドレス -:param n: 読み取るバイト数 -:param repeat: ``True`` にすると、ストップビットが送られません。 -:return: The bytes read""" + :param addr: The 7-bit address of the device + :param n: The number of bytes to read + :param repeat: If ``True``, no stop bit will be sent + :return: The bytes read + """ ... -def write(addr: int, buf: ReadableBuffer, repeat: bool=False) -> None: - """デバイスにバイト列を書き込みます。 +def write(addr: int, buf: ReadableBuffer, repeat: bool = False) -> None: + """Write bytes to a device. -Example: ``i2c.write(0x50, bytes([1, 2, 3]))`` + Example: ``i2c.write(0x50, bytes([1, 2, 3]))`` -:param addr: デバイスの7ビットアドレス -:param buf: 書き込むバイトを含むバッファ -:param repeat: ``True`` にすると、ストップビットが送られません。""" - ... \ No newline at end of file + :param addr: The 7-bit address of the device + :param buf: A buffer containing the bytes to write + :param repeat: If ``True``, no stop bit will be sent + """ + ... diff --git a/lang/ja/typeshed/stdlib/microbit/microphone.pyi b/lang/ja/typeshed/stdlib/microbit/microphone.pyi index b714ccf..68e8f3a 100644 --- a/lang/ja/typeshed/stdlib/microbit/microphone.pyi +++ b/lang/ja/typeshed/stdlib/microbit/microphone.pyi @@ -1,62 +1,70 @@ -"""内蔵マイクを使って音に応答します(V2 のみ)。""" +"""Respond to sound using the built-in microphone (V2 only). +""" + from typing import Optional, Tuple from ..microbit import SoundEvent def current_event() -> Optional[SoundEvent]: - """記録されている最新のサウンドイベントを取得します。 + """Get the last recorded sound event -Example: ``microphone.current_event()`` + Example: ``microphone.current_event()`` -:return: The event, ``SoundEvent('loud')`` or ``SoundEvent('quiet')``.""" + :return: The event, ``SoundEvent('loud')`` or ``SoundEvent('quiet')``. + """ ... def was_event(event: SoundEvent) -> bool: - """直前の呼び出しから少なくとも一度はサウンドイベントが発生したかどうかを確認します。 + """Check if a sound was heard at least once since the last call. -Example: ``microphone.was_event(SoundEvent.LOUD)`` + Example: ``microphone.was_event(SoundEvent.LOUD)`` -This call clears the sound history before returning. + This call clears the sound history before returning. -:param event: ``SoundEvent.LOUD`` や ``SoundEvent.QUIET`` などのイベント -:return: ``True`` if sound was heard at least once since the last call, otherwise ``False``.""" + :param event: The event to check for, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET`` + :return: ``True`` if sound was heard at least once since the last call, otherwise ``False``. + """ ... def is_event(event: SoundEvent) -> bool: - """直近に検出されたサウンドイベントを確認します。 + """Check the most recent sound event detected. -Example: ``microphone.is_event(SoundEvent.LOUD)`` + Example: ``microphone.is_event(SoundEvent.LOUD)`` -This call does not clear the sound event history. + This call does not clear the sound event history. -:param event: ``SoundEvent.LOUD`` や ``SoundEvent.QUIET`` など、確認するサウンドイベント -:return: ``True`` if sound was the most recent heard, ``False`` otherwise.""" + :param event: The event to check for, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET`` + :return: ``True`` if sound was the most recent heard, ``False`` otherwise. + """ ... def get_events() -> Tuple[SoundEvent, ...]: - """サウンドイベント履歴をタプルとして取得します。 + """Get the sound event history as a tuple. -Example: ``microphone.get_events()`` + Example: ``microphone.get_events()`` -This call clears the sound history before returning. + This call clears the sound history before returning. -:return: A tuple of the event history with the most recent event last.""" + :return: A tuple of the event history with the most recent event last. + """ ... def set_threshold(event: SoundEvent, value: int) -> None: - """サウンドイベントのしきい値を設定します。 + """Set the threshold for a sound event. -Example: ``microphone.set_threshold(SoundEvent.LOUD, 250)`` + Example: ``microphone.set_threshold(SoundEvent.LOUD, 250)`` -A high threshold means the event will only trigger if the sound is very loud (>= 250 in the example). + A high threshold means the event will only trigger if the sound is very loud (>= 250 in the example). -:param event: ``SoundEvent.LOUD`` や ``SoundEvent.QUIET`` などのサウンドイベント。 -:param value: 0~255の範囲で指定するしきい値レベル。""" + :param event: A sound event, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET``. + :param value: The threshold level in the range 0-255. + """ ... def sound_level() -> int: - """音圧レベルを取得します。 + """Get the sound pressure level. -Example: ``microphone.sound_level()`` + Example: ``microphone.sound_level()`` -:return: A representation of the sound pressure level in the range 0 to 255.""" - ... \ No newline at end of file + :return: A representation of the sound pressure level in the range 0 to 255. + """ + ... diff --git a/lang/ja/typeshed/stdlib/microbit/speaker.pyi b/lang/ja/typeshed/stdlib/microbit/speaker.pyi index f0878b4..5a74a4d 100644 --- a/lang/ja/typeshed/stdlib/microbit/speaker.pyi +++ b/lang/ja/typeshed/stdlib/microbit/speaker.pyi @@ -1,15 +1,18 @@ -"""内蔵スピーカーを制御します(V2のみ)。""" +"""Control the built-in speaker (V2 only). +""" def off() -> None: - """スピーカーをオフにします。 + """Turn the speaker off. -Example: ``speaker.off()`` + Example: ``speaker.off()`` -This does not disable sound output to an edge connector pin.""" + This does not disable sound output to an edge connector pin. + """ ... def on() -> None: - """スピーカーをオンにします。 + """Turn the speaker on. -Example: ``speaker.on()``""" - ... \ No newline at end of file + Example: ``speaker.on()`` + """ + ... diff --git a/lang/ja/typeshed/stdlib/microbit/spi.pyi b/lang/ja/typeshed/stdlib/microbit/spi.pyi index 3fd049c..09c4046 100644 --- a/lang/ja/typeshed/stdlib/microbit/spi.pyi +++ b/lang/ja/typeshed/stdlib/microbit/spi.pyi @@ -1,47 +1,60 @@ -"""シリアルペリフェラルインターフェイス(SPI)バスを使ってデバイスと通信します。""" +"""Communicate with devices using the serial peripheral interface (SPI) bus. +""" + from _typeshed import ReadableBuffer, WriteableBuffer from ..microbit import pin13, pin14, pin15, MicroBitDigitalPin -def init(baudrate: int=1000000, bits: int=8, mode: int=0, sclk: MicroBitDigitalPin=pin13, mosi: MicroBitDigitalPin=pin15, miso: MicroBitDigitalPin=pin14) -> None: - """SPI通信を初期化します。 - -Example: ``spi.init()`` - -For correct communication, the parameters have to be the same on both communicating devices. - -:param baudrate: 通信速度。 -:param bits: 送信時のビット幅。現在のところは ``bits=8`` だけをサポート。しかし、これは将来的に変更するかもしれません。 -:param mode: クロックの極性と位相の組み合わせを決定します - `オンラインの表を参照 `_ 。 -:param sclk: sclk 端子(デフォルトは 13) -:param mosi: mosi 端子(デフォルトは 15) -:param miso: miso 端子(デフォルトは 14)""" +def init( + baudrate: int = 1000000, + bits: int = 8, + mode: int = 0, + sclk: MicroBitDigitalPin = pin13, + mosi: MicroBitDigitalPin = pin15, + miso: MicroBitDigitalPin = pin14, +) -> None: + """Initialize SPI communication. + + Example: ``spi.init()`` + + For correct communication, the parameters have to be the same on both communicating devices. + + :param baudrate: The speed of communication. + :param bits: The width in bits of each transfer. Currently only ``bits=8`` is supported. However, this may change in the future. + :param mode: Determines the combination of clock polarity and phase - `see online table `_. + :param sclk: sclk pin (default 13) + :param mosi: mosi pin (default 15) + :param miso: miso pin (default 14) + """ ... -def read(nbytes: int, out: int=0) -> bytes: - """バイト列を読み取ります。 +def read(nbytes: int, out: int = 0) -> bytes: + """Read at most ``nbytes`` while continuously writing the single byte given by ``out``. -Example: ``spi.read(64)`` + Example: ``spi.read(64)`` -:param nbytes: 読み取る最大バイト数。 -:param out: The byte value to write (default 0). -:return: The bytes read.""" + :param nbytes: Maximum number of bytes to read. + :param out: The byte value to write (default 0). + :return: The bytes read. + """ ... def write(buffer: ReadableBuffer) -> None: - """デバイスにバイト列を書き込みます。 + """Write bytes to the bus. -Example: ``spi.write(bytes([1, 2, 3]))`` + Example: ``spi.write(bytes([1, 2, 3]))`` -:param buffer: データの読み取り元のバッファ。""" + :param buffer: A buffer to read data from. + """ ... def write_readinto(out: WriteableBuffer, in_: ReadableBuffer) -> None: - """``out`` バッファをバスに書き込み、任意のレスポンスを ``in_`` バッファに読み取ります。 + """Write the ``out`` buffer to the bus and read any response into the ``in_`` buffer. -Example: ``spi.write_readinto(out_buffer, in_buffer)`` + Example: ``spi.write_readinto(out_buffer, in_buffer)`` -The length of the buffers should be the same. The buffers can be the same object. + The length of the buffers should be the same. The buffers can be the same object. -:param out: レスポンスの書き込みバッファ。 -:param in_: データの読み取り元のバッファ。""" - ... \ No newline at end of file + :param out: The buffer to write any response to. + :param in_: The buffer to read data from. + """ + ... diff --git a/lang/ja/typeshed/stdlib/microbit/uart.pyi b/lang/ja/typeshed/stdlib/microbit/uart.pyi index f94f28a..2ab650f 100644 --- a/lang/ja/typeshed/stdlib/microbit/uart.pyi +++ b/lang/ja/typeshed/stdlib/microbit/uart.pyi @@ -1,79 +1,96 @@ -"""シリアルインタフェースを使ってデバイスと通信します。""" +"""Communicate with a device using a serial interface. +""" + from _typeshed import WriteableBuffer from ..microbit import MicroBitDigitalPin from typing import Optional, Union -ODD: int -"""奇数パリティ""" -EVEN: int -"""偶数パリティ""" - -def init(baudrate: int=9600, bits: int=8, parity: Optional[int]=None, stop: int=1, tx: Optional[MicroBitDigitalPin]=None, rx: Optional[MicroBitDigitalPin]=None) -> None: - """シリアル通信を初期化します。 - -Example: ``uart.init(115200, tx=pin0, rx=pin1)`` -:param baudrate: 通信速度。 -:param bits: 送信するビット幅。micro:bitは8だけをサポートしています。 -:param parity: パリティのチェック方法。``None``、``uart.ODD``、``uart.EVEN`` のいずれかを指定できます。 -:param stop: ストップビットの数はmicro:bitでは1にする必要があります。 -:param tx: 送信端子。 -:param rx: 受信端子。 - -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. +ODD: int +"""Odd parity""" -For more details see `the online documentation `_.""" +EVEN: int +"""Even parity""" + +def init( + baudrate: int = 9600, + bits: int = 8, + parity: Optional[int] = None, + stop: int = 1, + tx: Optional[MicroBitDigitalPin] = None, + rx: Optional[MicroBitDigitalPin] = None, +) -> None: + """Initialize serial communication. + + Example: ``uart.init(115200, tx=pin0, rx=pin1)`` + + :param baudrate: The speed of communication. + :param bits: The size of bytes being transmitted. micro:bit only supports 8. + :param parity: How parity is checked, ``None``, ``uart.ODD`` or ``uart.EVEN``. + :param stop: The number of stop bits, has to be 1 for micro:bit. + :param tx: Transmitting pin. + :param rx: Receiving pin. + + 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. + + For more details see `the online documentation `_. + """ ... def any() -> bool: - """受信待ちのデータがあるかを確認します。 + """Check if any data is waiting. -Example: ``uart.any()`` + Example: ``uart.any()`` -:return: ``True`` if any data is waiting, else ``False``.""" + :return: ``True`` if any data is waiting, else ``False``. + """ ... -def read(nbytes: Optional[int]=None) -> Optional[bytes]: - """バイト列を読み取ります。 +def read(nbytes: Optional[int] = None) -> Optional[bytes]: + """Read bytes. -Example: ``uart.read()`` + Example: ``uart.read()`` -:param nbytes: ``nbytes`` が指定されていれば、そのバイト数まで読み込みます。指定されていなければ、できるだけ多く読み取ります -:return: A bytes object or ``None`` on timeout""" + :param nbytes: If ``nbytes`` is specified then read at most that many bytes, otherwise read as many bytes as possible + :return: A bytes object or ``None`` on timeout + """ ... -def readinto(buf: WriteableBuffer, nbytes: Optional[int]=None) -> Optional[int]: - """``buf`` にバイト列を読み取ります。 +def readinto(buf: WriteableBuffer, nbytes: Optional[int] = None) -> Optional[int]: + """Read bytes into the ``buf``. -Example: ``uart.readinto(input_buffer)`` + Example: ``uart.readinto(input_buffer)`` -:param buf: 書き込みバッファ。 -:param nbytes: ``nbytes`` が指定されていれば、そのバイト数まで読み込みます。指定されていなければ、``len(buf)`` を読み取ります。 -:return: number of bytes read and stored into ``buf`` or ``None`` on timeout.""" + :param buf: The buffer to write to. + :param nbytes: If ``nbytes`` is specified then read at most that many bytes, otherwise read ``len(buf)`` bytes. + :return: number of bytes read and stored into ``buf`` or ``None`` on timeout. + """ ... def readline() -> Optional[bytes]: - """改行文字で終わる行を読みます。 + """Read a line, ending in a newline character. -Example: ``uart.readline()`` + Example: ``uart.readline()`` -:return: The line read or ``None`` on timeout. The newline character is included in the returned bytes.""" + :return: The line read or ``None`` on timeout. The newline character is included in the returned bytes. + """ ... def write(buf: Union[bytes, str]) -> Optional[int]: - """バスにバッファを書き込みます。 + """Write a buffer to the bus. -Example: ``uart.write('hello world')`` + Example: ``uart.write('hello world')`` -:param buf: バイト列オブジェクトまたは文字列。 -:return: The number of bytes written, or ``None`` on timeout. + :param buf: A bytes object or a string. + :return: The number of bytes written, or ``None`` on timeout. -Examples:: + Examples:: - uart.write('hello world') - uart.write(b'hello world') - uart.write(bytes([1, 2, 3]))""" - ... \ No newline at end of file + uart.write('hello world') + uart.write(b'hello world') + uart.write(bytes([1, 2, 3])) + """ + ... diff --git a/lang/ja/typeshed/stdlib/micropython.pyi b/lang/ja/typeshed/stdlib/micropython.pyi index 7c013bf..7a6079f 100644 --- a/lang/ja/typeshed/stdlib/micropython.pyi +++ b/lang/ja/typeshed/stdlib/micropython.pyi @@ -1,131 +1,144 @@ -"""MicroPythonの内部。""" +"""MicroPython internals.""" + from typing import Any, TypeVar, overload -_T = TypeVar('_T') + +_T = TypeVar("_T") def const(expr: _T) -> _T: - """コンパイルが最適化できるように、式が定数であることを宣言するために使います。 + """Used to declare that the expression is a constant so that the compiler can + optimise it. -The use of this function should be as follows:: + The use of this function should be as follows:: - from micropython import const - CONST_X = const(123) - CONST_Y = const(2 * CONST_X + 1) + from micropython import const + CONST_X = const(123) + CONST_Y = const(2 * CONST_X + 1) -Constants declared this way are still accessible as global variables from -outside the module they are declared in. On the other hand, if a constant -begins with an underscore then it is hidden, it is not available as a -global variable, and does not take up any memory during execution. + Constants declared this way are still accessible as global variables from + outside the module they are declared in. On the other hand, if a constant + begins with an underscore then it is hidden, it is not available as a + global variable, and does not take up any memory during execution. -:param expr: 定数式。""" + :param expr: A constant expression. + """ ... @overload def opt_level() -> int: - """スクリプトの現在のコンパイル最適化レベルを取得します。 + """Get the current optimisation level for the compilation of scripts. -Example: ``micropython.opt_level()`` + Example: ``micropython.opt_level()`` -The optimisation level controls the following compilation features: + The optimisation level controls the following compilation features: -- Assertions: at level 0 assertion statements are enabled and compiled - into the bytecode; at levels 1 and higher assertions are not compiled. + - Assertions: at level 0 assertion statements are enabled and compiled + into the bytecode; at levels 1 and higher assertions are not compiled. -- Built-in ``__debug__`` variable: at level 0 this variable expands to - True; at levels 1 and higher it expands to False. + - Built-in ``__debug__`` variable: at level 0 this variable expands to + True; at levels 1 and higher it expands to False. -- Source-code line numbers: at levels 0, 1 and 2 source-code line number - are stored along with the bytecode so that exceptions can report the - line number they occurred at; at levels 3 and higher line numbers are - not stored. + - Source-code line numbers: at levels 0, 1 and 2 source-code line number + are stored along with the bytecode so that exceptions can report the + line number they occurred at; at levels 3 and higher line numbers are + not stored. -:return: An integer representing the current level.""" + :return: An integer representing the current level. + """ ... @overload def opt_level(level: int) -> None: - """スクリプトの後続のコンパイル最適化レベルを設定します。 + """Sets the optimisation level for subsequent compilation of scripts. -Example: ``micropython.opt_level(1)`` + Example: ``micropython.opt_level(1)`` -The optimisation level controls the following compilation features: + The optimisation level controls the following compilation features: -- Assertions: at level 0 assertion statements are enabled and compiled - into the bytecode; at levels 1 and higher assertions are not compiled. + - Assertions: at level 0 assertion statements are enabled and compiled + into the bytecode; at levels 1 and higher assertions are not compiled. -- Built-in ``__debug__`` variable: at level 0 this variable expands to - True; at levels 1 and higher it expands to False. + - Built-in ``__debug__`` variable: at level 0 this variable expands to + True; at levels 1 and higher it expands to False. -- Source-code line numbers: at levels 0, 1 and 2 source-code line number - are stored along with the bytecode so that exceptions can report the - line number they occurred at; at levels 3 and higher line numbers are - not stored. + - Source-code line numbers: at levels 0, 1 and 2 source-code line number + are stored along with the bytecode so that exceptions can report the + line number they occurred at; at levels 3 and higher line numbers are + not stored. -The default optimisation level is usually level 0. + The default optimisation level is usually level 0. -:param level: 最適化レベルを示す整数値。""" + :param level: An integer optimisation level. + """ ... -def mem_info(verbose: Any=None) -> None: - """現在使っているメモリに関する情報を表示します。 +def mem_info(verbose: Any = None) -> None: + """Print information about currently used memory. -Example: ``micropython.mem_info()`` + Example: ``micropython.mem_info()`` -:param verbose: ``verbose`` 引数を指定すると、詳しい情報を表示します。""" + :param verbose: If the ``verbose`` argument is given then extra information is printed. + """ ... -def qstr_info(verbose: Any=None) -> None: - """現在インターンされている文字列に関する情報を表示します。 +def qstr_info(verbose: Any = None) -> None: + """Print information about currently interned strings. -Example: ``micropython.qstr_info()`` + Example: ``micropython.qstr_info()`` -:param verbose: ``verbose`` 引数を指定すると、詳しい情報を表示します。 + :param verbose: If the ``verbose`` argument is given then extra information is printed. -The information that is printed is implementation dependent, but currently -includes the number of interned strings and the amount of RAM they use. In -verbose mode it prints out the names of all RAM-interned strings.""" + The information that is printed is implementation dependent, but currently + includes the number of interned strings and the amount of RAM they use. In + verbose mode it prints out the names of all RAM-interned strings. + """ ... def stack_use() -> int: - """現在使われているスタックのサイズを表す整数を返します。 + """Return an integer representing the current amount of stack that is being + used. -Example: ``micropython.stack_use()`` + Example: ``micropython.stack_use()`` -The absolute value of this is not particularly useful, rather it -should be used to compute differences in stack usage at different points. + The absolute value of this is not particularly useful, rather it + should be used to compute differences in stack usage at different points. -:return: An integer representing current stack use.""" + :return: An integer representing current stack use. + """ ... def heap_lock() -> None: - """ヒープをロックします。 + """Lock the heap. -Example: ``micropython.heap_lock()`` + Example: ``micropython.heap_lock()`` -When locked no memory allocation can occur and a ``MemoryError`` will be -raised if any heap allocation is attempted.""" + When locked no memory allocation can occur and a ``MemoryError`` will be + raised if any heap allocation is attempted. + """ ... def heap_unlock() -> None: - """ヒープのロックを解除します。 + """Unlock the heap. -Example: ``micropython.heap_unlock()`` + Example: ``micropython.heap_unlock()`` -When locked no memory allocation can occur and a ``MemoryError`` will be -raised if any heap allocation is attempted.""" + When locked no memory allocation can occur and a ``MemoryError`` will be + raised if any heap allocation is attempted. + """ ... def kbd_intr(chr: int) -> None: - """``KeyboardInterrupt`` 例外を発生させる文字を設定します。 + """Set the character that will raise a ``KeyboardInterrupt`` exception. -Example: ``micropython.kbd_intr(-1)`` + Example: ``micropython.kbd_intr(-1)`` -:param chr: 割り込みを発生させる文字コード。あるいは、Ctrl-Cのキャプチャを無効にするには-1を指定します。 + :param chr: Character code to raise the interrupt or -1 to disable capture of Ctrl-C. -By default this is set to 3 during script execution, corresponding to Ctrl-C. -Passing -1 to this function will disable capture of Ctrl-C, and passing 3 -will restore it. + By default this is set to 3 during script execution, corresponding to Ctrl-C. + Passing -1 to this function will disable capture of Ctrl-C, and passing 3 + will restore it. -This function can be used to prevent the capturing of Ctrl-C on the -incoming stream of characters that is usually used for the REPL, in case -that stream is used for other purposes.""" - ... \ No newline at end of file + This function can be used to prevent the capturing of Ctrl-C on the + incoming stream of characters that is usually used for the REPL, in case + that stream is used for other purposes. + """ + ... diff --git a/lang/ja/typeshed/stdlib/music.pyi b/lang/ja/typeshed/stdlib/music.pyi index 7a84637..5f4778b 100644 --- a/lang/ja/typeshed/stdlib/music.pyi +++ b/lang/ja/typeshed/stdlib/music.pyi @@ -1,128 +1,167 @@ -"""メロディーの作成と再生。""" +"""Create and play melodies. +""" from typing import Optional, Tuple, Union, List + from .microbit import MicroBitDigitalPin, pin0 + DADADADUM: Tuple[str, ...] -"""メロディ: ベートーヴェンの交響曲第5番ハ短調の冒頭。""" +"""Melody: the opening to Beethoven’s 5th Symphony in C minor.""" + ENTERTAINER: Tuple[str, ...] -"""メロディ: スコット・ジョプリンのラグタイム・クラシック『ジ・エンターテイナー 』の冒頭。""" +"""Melody: the opening fragment of Scott Joplin’s Ragtime classic “The Entertainer”.""" + PRELUDE: Tuple[str, ...] -"""メロディ: J・S・バッハの前奏曲とフーガ計48曲の前奏曲第1番ハ長調の冒頭。""" +"""Melody: the opening of the first Prelude in C Major of J.S.Bach’s 48 Preludes and Fugues.""" + ODE: Tuple[str, ...] -"""メロディ: ベートーヴェンの交響曲第9番ニ短調より『歓喜の歌』のテーマ。""" +"""Melody: the “Ode to Joy” theme from Beethoven’s 9th Symphony in D minor.""" + NYAN: Tuple[str, ...] -"""メロディ: Nyan Cat テーマ (http://www.nyan.cat/)。 +"""Melody: the Nyan Cat theme (http://www.nyan.cat/). The composer is unknown. This is fair use for educational porpoises (as they say in New York).""" + RINGTONE: Tuple[str, ...] -"""メロディ: 携帯電話の着信音のようなもの。 +"""Melody: something that sounds like a mobile phone ringtone. To be used to indicate an incoming message. """ + FUNK: Tuple[str, ...] -"""メロディ: スパイと犯罪の黒幕用のファンキーなベースライン。""" +"""Melody: a funky bass line for secret agents and criminal masterminds.""" + BLUES: Tuple[str, ...] -"""メロディ: ブギー・ウーギーの 12 小節のブルース・ウォーキング・ベース。""" +"""Melody: a boogie-woogie 12-bar blues walking bass.""" + BIRTHDAY: Tuple[str, ...] -"""メロディ:『ハッピーバースディトゥユー ...』 +"""Melody: “Happy Birthday to You…” For copyright status see: http://www.bbc.co.uk/news/world-us-canada-34332853 """ + WEDDING: Tuple[str, ...] -"""メロディ: ワグナーのオペラ『ローエングリン』より婚礼の合唱。""" +"""Melody: the bridal chorus from Wagner’s opera “Lohengrin”.""" + FUNERAL: Tuple[str, ...] -"""メロディ: フレデリック・ショパンのピアノソナタ第2番変ロ短調 作品35(別名『葬送』)。""" +"""Melody: the “funeral march” otherwise known as Frédéric Chopin’s Piano Sonata No. 2 in B♭ minor, Op. 35.""" + PUNCHLINE: Tuple[str, ...] -"""メロディ: ジョークが言われたことを意味する楽しい音楽。""" +"""Melody: a fun fragment that signifies a joke has been made.""" + PYTHON: Tuple[str, ...] -"""メロディ: ジョン・フィリップ・スーザの『自由の鐘』(『空飛ぶモンティ・パイソン』のテーマともいう)(プログラミング言語Pythonの名前の由来となった)。""" +"""Melody: John Philip Sousa’s march “Liberty Bell” aka, the theme for “Monty Python’s Flying Circus” (after which the Python programming language is named).""" + BADDY: Tuple[str, ...] -"""メロディ: 無声映画時代の悪役の登場。""" +"""Melody: silent movie era entrance of a baddy.""" + CHASE: Tuple[str, ...] -"""メロディ: 無声映画時代のチェイスシーン。""" +"""Melody: silent movie era chase scene.""" + BA_DING: Tuple[str, ...] -"""メロディ: 何かが起こったことを示す短い信号。""" +"""Melody: a short signal to indicate something has happened.""" + WAWAWAWAA: Tuple[str, ...] -"""メロディ: 非常に悲しいトロンボーン。""" +"""Melody: a very sad trombone.""" + JUMP_UP: Tuple[str, ...] -"""メロディ: ゲームでの使用で、上方向の動きを示します。""" +"""Melody: for use in a game, indicating upward movement.""" + JUMP_DOWN: Tuple[str, ...] -"""メロディ: ゲームでの使用で、下向きの動きを示します。""" +"""Melody: for use in a game, indicating downward movement.""" + POWER_UP: Tuple[str, ...] -"""メロディ: アチーブメントを達成したことを示すファンファーレ。""" +"""Melody: a fanfare to indicate an achievement unlocked.""" + POWER_DOWN: Tuple[str, ...] -"""メロディ: アチーブメントを達成しなかったことを示すファンファーレ。""" +"""Melody: a sad fanfare to indicate an achievement lost.""" -def set_tempo(ticks: int=4, bpm: int=120) -> None: - """再生するためのおおよそのテンポを設定します。 +def set_tempo(ticks: int = 4, bpm: int = 120) -> None: + """Sets the approximate tempo for playback. -Example: ``music.set_tempo(bpm=120)`` + Example: ``music.set_tempo(bpm=120)`` -:param ticks: 1ビートを構成するティック数。 -:param bpm: 毎分のビート数を決定する整数。 + :param ticks: The number of ticks constituting a beat. + :param bpm: An integer determining how many beats per minute. -Suggested default values allow the following useful behaviour: + Suggested default values allow the following useful behaviour: -- music.set_tempo() – reset the tempo to default of ticks = 4, bpm = 120 -- music.set_tempo(ticks=8) – change the “definition” of a beat -- music.set_tempo(bpm=180) – just change the tempo + - music.set_tempo() – reset the tempo to default of ticks = 4, bpm = 120 + - music.set_tempo(ticks=8) – change the “definition” of a beat + - music.set_tempo(bpm=180) – just change the tempo -To work out the length of a tick in milliseconds is very simple arithmetic: -60000/bpm/ticks_per_beat. For the default values that’s -60000/120/4 = 125 milliseconds or 1 beat = 500 milliseconds.""" + To work out the length of a tick in milliseconds is very simple arithmetic: + 60000/bpm/ticks_per_beat. For the default values that’s + 60000/120/4 = 125 milliseconds or 1 beat = 500 milliseconds. + """ ... def get_tempo() -> Tuple[int, int]: - """現在のテンポを整数のタプル ``(ticks, bpm)`` として取得します。 + """Gets the current tempo as a tuple of integers: ``(ticks, bpm)``. -Example: ``ticks, beats = music.get_tempo()`` + Example: ``ticks, beats = music.get_tempo()`` -:return: The temp as a tuple with two integer values, the ticks then the beats per minute.""" + :return: The temp as a tuple with two integer values, the ticks then the beats per minute. + """ ... -def play(music: Union[str, List[str], Tuple[str, ...]], pin: Optional[MicroBitDigitalPin]=pin0, wait: bool=True, loop: bool=False) -> None: - """ミュージックを再生します。 +def play( + music: Union[str, List[str], Tuple[str, ...]], + pin: Optional[MicroBitDigitalPin] = pin0, + wait: bool = True, + loop: bool = False, +) -> None: + """Plays music. -Example: ``music.play(music.NYAN)`` + Example: ``music.play(music.NYAN)`` -:param music: `特別な表記 `_ で指定されたミュージック -:param pin: (ピン) 外部スピーカー用出力端子(デフォルトは ``pin0``)。音を鳴らしたくない場合は ``None`` を指定します。 -:param wait: ``wait`` を ``True`` に設定した場合、この関数がブロックします。 -:param loop: ``loop`` が ``True`` の場合、曲は ``stop`` が呼び出されるか、ブロックコールが中断されるまで繰り返し再生されます。 + :param music: music specified in `a special notation `_ + :param pin: the output pin for use with an external speaker (default ``pin0``), ``None`` for no sound. + :param wait: If ``wait`` is set to ``True``, this function is blocking. + :param loop: If ``loop`` is set to ``True``, the tune repeats until ``stop`` is called or the blocking call is interrupted. -Many built-in melodies are defined in this module.""" + Many built-in melodies are defined in this module. + """ ... -def pitch(frequency: int, duration: int=-1, pin: Optional[MicroBitDigitalPin]=pin0, wait: bool=True) -> None: - """音符を再生します。 +def pitch( + frequency: int, + duration: int = -1, + pin: Optional[MicroBitDigitalPin] = pin0, + wait: bool = True, +) -> None: + """Play a note. -Example: ``music.pitch(185, 1000)`` + Example: ``music.pitch(185, 1000)`` -:param frequency: 周波数を示す整数値 -:param duration: 持続時間をミリ秒単位で指定します。負の場合、次の呼び出しか ``stop`` の呼び出しまで再生が続きます。 -:param pin: オプションの出力端子(デフォルトは ``pin0``)。 -:param wait: ``wait`` を ``True`` に設定した場合、この関数がブロックします。 + :param frequency: An integer frequency + :param duration: A millisecond duration. If negative then sound is continuous until the next call or a call to ``stop``. + :param pin: Optional output pin (default ``pin0``). + :param wait: If ``wait`` is set to ``True``, this function is blocking. -For example, if the frequency is set to 440 and the length to -1000 then we hear a standard concert A for one second. + For example, if the frequency is set to 440 and the length to + 1000 then we hear a standard concert A for one second. -You can only play one pitch on one pin at any one time.""" + You can only play one pitch on one pin at any one time. + """ ... -def stop(pin: Optional[MicroBitDigitalPin]=pin0) -> None: - """内蔵スピーカーやサウンドを出力する端子から鳴らしているすべてのミュージック再生を停止します。 +def stop(pin: Optional[MicroBitDigitalPin] = pin0) -> None: + """Stops all music playback on the built-in speaker and any pin outputting sound. -Example: ``music.stop()`` + Example: ``music.stop()`` -:param pin: オプションの引数には、たとえば ``music.stop(pin1)`` などの端子を指定できます。""" + :param pin: An optional argument can be provided to specify a pin, e.g. ``music.stop(pin1)``. + """ def reset() -> None: - """ティック、bpm、持続時間、オクターブをデフォルト値にリセットします。 + """Resets ticks, bpm, duration and octave to their default values. -Example: ``music.reset()`` + Example: ``music.reset()`` -Values: -- ``ticks = 4`` -- ``bpm = 120`` -- ``duration = 4`` -- ``octave = 4``""" - ... \ No newline at end of file + Values: + - ``ticks = 4`` + - ``bpm = 120`` + - ``duration = 4`` + - ``octave = 4`` + """ + ... diff --git a/lang/ja/typeshed/stdlib/neopixel.pyi b/lang/ja/typeshed/stdlib/neopixel.pyi index 8dadfad..2d5a749 100644 --- a/lang/ja/typeshed/stdlib/neopixel.pyi +++ b/lang/ja/typeshed/stdlib/neopixel.pyi @@ -1,81 +1,82 @@ -"""個別にアドレス可能な RGB/RGBW LED ストリップ。""" +"""Individually addressable RGB and RGBW LED strips. +""" from .microbit import MicroBitDigitalPin from typing import Tuple class NeoPixel: + def __init__(self, pin: MicroBitDigitalPin, n: int, bpp: int = 3) -> None: + """Initialise a new strip of neopixel LEDs controlled via a pin. - def __init__(self, pin: MicroBitDigitalPin, n: int, bpp: int=3) -> None: - """端子を介して制御するネオピクセルLEDの新しいストリップを初期化します。 + Example: ``np = neopixel.NeoPixel(pin0, 8)`` -Example: ``np = neopixel.NeoPixel(pin0, 8)`` + To support RGBW neopixels, a third argument can be passed to + ``NeoPixel`` to indicate the number of bytes per pixel (``bpp``). + For RGBW, this is is 4 rather than the default of 3 for RGB and GRB. -To support RGBW neopixels, a third argument can be passed to -``NeoPixel`` to indicate the number of bytes per pixel (``bpp``). -For RGBW, this is is 4 rather than the default of 3 for RGB and GRB. + Each pixel is addressed by a position (starting from 0). Neopixels are + given RGB (red, green, blue) / RGBW (red, green, blue, white) values + between 0-255 as a tuple. For example, in RGB, ``(255,255,255)`` is + white. In RGBW, ``(255,255,255,0)`` or ``(0,0,0,255)`` is white. -Each pixel is addressed by a position (starting from 0). Neopixels are -given RGB (red, green, blue) / RGBW (red, green, blue, white) values -between 0-255 as a tuple. For example, in RGB, ``(255,255,255)`` is -white. In RGBW, ``(255,255,255,0)`` or ``(0,0,0,255)`` is white. + See `the online docs `_ for warnings and other advice. -See `the online docs `_ for warnings and other advice. - -:param pin: ネオピクセルストリップを制御する端子。 -:param n: ストリップ内のネオピクセルの数。 -:param bpp: ピクセルあたりのバイト数。RGBW ネオピクセルに対応するには、RGBやGRBのデフォルト値の3ではなく、4 を指定します。""" + :param pin: The pin controlling the neopixel strip. + :param n: The number of neopixels in the strip. + :param bpp: Bytes per pixel. For RGBW neopixel support, pass 4 rather than the default of 3 for RGB and GRB. + """ ... - def clear(self) -> None: - """すべてのピクセルをクリアします。 + """Clear all the pixels. -Example: ``np.clear()``""" + Example: ``np.clear()`` + """ ... - def show(self) -> None: - """ピクセルを表示します。 + """Show the pixels. -Example: ``np.show()`` + Example: ``np.show()`` -Must be called for any updates to become visible.""" + Must be called for any updates to become visible. + """ ... - def write(self) -> None: - """ピクセルを表示します(micro:bit V2 のみ)。 + """Show the pixels (micro:bit V2 only). -Example: ``np.write()`` + Example: ``np.write()`` -Must be called for any updates to become visible. + Must be called for any updates to become visible. -Equivalent to ``show``.""" + Equivalent to ``show``. + """ ... - def fill(self, colour: Tuple[int, ...]) -> None: - """指定した RGB/RGBW 値をすべてのピクセルに設定します(micro:bit V2 のみ)。 + """Colour all pixels a given RGB/RGBW value (micro:bit V2 only). -Example: ``np.fill((0, 0, 255))`` + Example: ``np.fill((0, 0, 255))`` -:param colour: ピクセルあたりのバイト数(bpp)と同じ長さのタプル。 + :param colour: A tuple of the same length as the number of bytes per pixel (bpp). -Use in conjunction with ``show()`` to update the neopixels.""" + Use in conjunction with ``show()`` to update the neopixels. + """ ... - def __setitem__(self, key: int, value: Tuple[int, ...]) -> None: - """ピクセルの色を設定します。 + """Set a pixel colour. -Example: ``np[0] = (255, 0, 0)`` - -:param key: ピクセル番号。 -:param value: 色。""" + Example: ``np[0] = (255, 0, 0)`` + :param key: The pixel number. + :param value: The colour. + """ def __getitem__(self, key: int) -> Tuple[int, ...]: - """ピクセルの色を取得します。 - -Example: ``r, g, b = np[0]`` + """Get a pixel colour. -:param key: ピクセル番号。 -:return: The colour tuple.""" + Example: ``r, g, b = np[0]`` + :param key: The pixel number. + :return: The colour tuple. + """ def __len__(self) -> int: - """このピクセルストリップの長さを取得します。 + """Get length of this pixel strip. -Example: ``len(np)``""" \ No newline at end of file + Example: ``len(np)`` + """ diff --git a/lang/ja/typeshed/stdlib/os.pyi b/lang/ja/typeshed/stdlib/os.pyi index a9f2217..2f2db77 100644 --- a/lang/ja/typeshed/stdlib/os.pyi +++ b/lang/ja/typeshed/stdlib/os.pyi @@ -1,63 +1,73 @@ -"""ファイルシステムにアクセスします。""" +"""Access the file system. +""" + from typing import Tuple from typing import List def listdir() -> List[str]: - """ファイルすべての名前のリストを取得します。 + """List files. -Example: ``os.listdir()`` + Example: ``os.listdir()`` -:return: A list of the names of all the files contained within the local -persistent on-device file system.""" + :return: A list of the names of all the files contained within the local + persistent on-device file system. + """ ... def remove(filename: str) -> None: - """ファイルを削除します。 + """Remove (delete) a file. -Example: ``os.remove('data.txt')`` + Example: ``os.remove('data.txt')`` -:param filename: 削除するファイルの名前。 + :param filename: The file to delete. -If the file does not exist an ``OSError`` exception will occur.""" + If the file does not exist an ``OSError`` exception will occur. + """ ... def size(filename: str) -> int: - """ファイルのサイズを返します。 + """Returns the size of a file. -Example: ``os.size('data.txt')`` + Example: ``os.size('data.txt')`` -:param filename: ファイル -:return: The size in bytes. + :param filename: The file + :return: The size in bytes. -If the file does not exist an ``OSError`` exception will occur.""" + If the file does not exist an ``OSError`` exception will occur. + """ class uname_result(Tuple[str, str, str, str, str]): - """``os.uname()`` の結果""" + """Result of ``os.uname()``""" sysname: str - """オペレーティングシステム名。""" + """Operating system name.""" + nodename: str - """ネットワーク上のマシンの名前(実装定義)。""" + """Name of machine on network (implementation-defined).""" + release: str - """オペレーティングシステムのリリース。""" + """Operating system release.""" + version: str - """オペレーティングシステムのバージョン。""" + """Operating system version.""" + machine: str - """ハードウェア識別子。""" + """Hardware identifier.""" def uname() -> uname_result: - """現在のオペレーティングシステムを識別する情報を返します。 + """Returns information identifying the current operating system. -Example: ``os.uname()`` + Example: ``os.uname()`` -The return value is an object with five attributes: + The return value is an object with five attributes: -- ``sysname`` - operating system name -- ``nodename`` - name of machine on network (implementation-defined) -- ``release`` - operating system release -- ``version`` - operating system version -- ``machine`` - hardware identifier + - ``sysname`` - operating system name + - ``nodename`` - name of machine on network (implementation-defined) + - ``release`` - operating system release + - ``version`` - operating system version + - ``machine`` - hardware identifier -There is no underlying operating system in MicroPython. As a result the -information returned by the ``uname`` function is mostly useful for -versioning details.""" - ... \ No newline at end of file + There is no underlying operating system in MicroPython. As a result the + information returned by the ``uname`` function is mostly useful for + versioning details. + """ + ... diff --git a/lang/ja/typeshed/stdlib/radio.pyi b/lang/ja/typeshed/stdlib/radio.pyi index 83ee371..8dd0267 100644 --- a/lang/ja/typeshed/stdlib/radio.pyi +++ b/lang/ja/typeshed/stdlib/radio.pyi @@ -1,129 +1,152 @@ -"""内蔵の無線通信を使ったmicro:bit間の通信。""" +"""Communicate between micro:bits with the built-in radio. +""" + from _typeshed import WriteableBuffer from typing import Optional, Tuple + RATE_1MBIT: int -"""1 MBit/秒のスループットを示すために使われる定数。""" +"""Constant used to indicate a throughput of 1 MBit a second.""" + RATE_2MBIT: int -"""2 MBit/秒のスループットを示すために使われる定数。""" +"""Constant used to indicate a throughput of 2 MBit a second.""" def on() -> None: - """無線通信をオンにします。 + """Turns the radio on. -Example: ``radio.on()`` + Example: ``radio.on()`` -This needs to be explicitly called since the radio draws power and takes -up memory that you may otherwise need.""" + This needs to be explicitly called since the radio draws power and takes + up memory that you may otherwise need. + """ ... def off() -> None: - """無線通信をオフにして、電力とメモリを節約します。 + """Turns off the radio, saving power and memory. -Example: ``radio.off()``""" + Example: ``radio.off()`` + """ ... -def config(length: int=32, queue: int=3, channel: int=7, power: int=6, address: int=1969383796, group: int=0, data_rate: int=RATE_1MBIT) -> None: - """無線通信を設定します。 - -Example: ``radio.config(group=42)`` - -The default configuration is suitable for most use. - -:param length: (デフォルト=32)\u3000無線を介して送信されるメッセージのバイト単位の最大長を設定します。 -最大で 251 バイト(S0、長さ、S1 プリアンブルは254 から 3 を引いたバイト数)に設定できます。 -:param queue: (デフォルト=3)\u3000受信メッセージキューに格納できるメッセージの数を指定します。 -着信メッセージのキューに空きがない場合、着信メッセージは捨てられます。 -:param channel: (デフォルト=7)\u3000無線が同調されている任意の「チャネル」を定義するもので、0 から 83 までの整数値を設定できます。メッセージはこのチャネル経由で送信され、このチャネル経由で受信したメッセージだけが受信メッセージキューに入れられます。各ステップは 1MHz 幅で、2400MHz を基準にしています。 -:param power: (デフォルト=6)\u3000メッセージをブロードキャストするときに使用される信号の強度を示すもので、0 から 7 までの整数値(指定の値を含む。)を設定できです。 -値が高いほど信号は強くなりますが、デバイスが消費する電力が大きくなります。指定の番号は次のリストの dBm(デシベルミリワット)値の位置に変換されます: -30, -20, -16, -12, -8, -4, 0, 4 。 -:param address: (デフォルト=0x75626974)\u300032 ビットのアドレスとして表される任意の名前であり、ハードウェアレベルで着信パケットをフィルタリングするために使用されます。フィルタリングはユーザーが設定したアドレスと一致するもののみを維持します。 -他のmicro:bit関連のプラットフォームで使われるデフォルトは、ここで使われるデフォルト設定となっています。 -:param group: (デフォルト=0)\u30008ビットの値(0〜255)であり、 ``address`` フィルタしたメッセージで使います。 -概念的に「address」は自宅/事務所の住所のようなものであり、「group」はその住所のメッセージを受け取人のようなものです。 -:param data_rate: (デフォルト=``radio.RATE_1MBIT``)\u3000データスループットが起こる速度を示しています。 -``radio`` モジュールに定義されている定数 ``RATE_250KBIT``、``RATE_1MBIT``、``RATE_2MBIT`` のいずれかを指定します。 - -If ``config`` is not called then the defaults described above are assumed.""" +def config( + length: int = 32, + queue: int = 3, + channel: int = 7, + power: int = 6, + address: int = 0x75626974, + group: int = 0, + data_rate: int = RATE_1MBIT, +) -> None: + """Configures the radio. + + Example: ``radio.config(group=42)`` + + The default configuration is suitable for most use. + + :param length: (default=32) defines the maximum length, in bytes, of a message sent via the radio. + It can be up to 251 bytes long (254 - 3 bytes for S0, LENGTH and S1 preamble). + :param queue: (default=3) specifies the number of messages that can be stored on the incoming message queue. + If there are no spaces left on the queue for incoming messages, then the incoming message is dropped. + :param channel: (default=7) an integer value from 0 to 83 (inclusive) that defines an arbitrary "channel" to which the radio is tuned. + Messages will be sent via this channel and only messages received via this channel will be put onto the incoming message queue. Each step is 1MHz wide, based at 2400MHz. + :param power: (default=6) is an integer value from 0 to 7 (inclusive) to indicate the strength of signal used when broadcasting a message. + The higher the value the stronger the signal, but the more power is consumed by the device. The numbering translates to positions in the following list of dBm (decibel milliwatt) values: -30, -20, -16, -12, -8, -4, 0, 4. + :param address: (default=0x75626974) an arbitrary name, expressed as a 32-bit address, that's used to filter incoming packets at the hardware level, keeping only those that match the address you set. + The default used by other micro:bit related platforms is the default setting used here. + :param group: (default=0) an 8-bit value (0-255) used with the ``address`` when filtering messages. + Conceptually, "address" is like a house/office address and "group" is like the person at that address to which you want to send your message. + :param data_rate: (default=``radio.RATE_1MBIT``) indicates the speed at which data throughput takes place. + Can be one of the following constants defined in the ``radio`` module: ``RATE_250KBIT``, ``RATE_1MBIT`` or ``RATE_2MBIT``. + + If ``config`` is not called then the defaults described above are assumed. + """ ... def reset() -> None: - """設定をデフォルト値にリセットします。 + """Reset the settings to their default values. -Example: ``radio.reset()`` + Example: ``radio.reset()`` -The defaults as as per the ``config`` function above.""" + The defaults as as per the ``config`` function above. + """ ... def send_bytes(message: bytes) -> None: - """バイト列を含んだメッセージを送信します。 + """Sends a message containing bytes. -Example: ``radio.send_bytes(b'hello')`` + Example: ``radio.send_bytes(b'hello')`` -:param message: 送信するバイト列。""" + :param message: The bytes to send. + """ ... def receive_bytes() -> Optional[bytes]: - """メッセージキューにある次の着信メッセージを受信します。 + """Receive the next incoming message on the message queue. -Example: ``radio.receive_bytes()`` + Example: ``radio.receive_bytes()`` -:return: The message bytes if any, otherwise ``None``.""" + :return: The message bytes if any, otherwise ``None``. + """ ... def receive_bytes_into(buffer: WriteableBuffer) -> Optional[int]: - """メッセージキューにある次の着信メッセージをバッファにコピーします。 + """Copy the next incoming message on the message queue into a buffer. -Example: ``radio.receive_bytes_info(buffer)`` + Example: ``radio.receive_bytes_info(buffer)`` -:param buffer: メッセージを格納するバッファ。メッセージがバッファより大きい場合、メッセージの収まらない部分が切り捨てられます。 -:return: ``None`` if there are no pending messages, otherwise it returns the length of the message (which might be more than the length of the buffer).""" + :param buffer: The target buffer. The message is truncated if larger than the buffer. + :return: ``None`` if there are no pending messages, otherwise it returns the length of the message (which might be more than the length of the buffer). + """ ... def send(message: str) -> None: - """メッセージ文字列を送信します。 + """Sends a message string. -Example: ``radio.send('hello')`` + Example: ``radio.send('hello')`` -This is the equivalent of ``radio.send_bytes(bytes(message, 'utf8'))`` but with ``b'\x01\x00\x01'`` -prepended to the front (to make it compatible with other platforms that target the micro:bit). + This is the equivalent of ``radio.send_bytes(bytes(message, 'utf8'))`` but with ``b'\x01\x00\x01'`` + prepended to the front (to make it compatible with other platforms that target the micro:bit). -:param message: 送信する文字列。""" + :param message: The string to send. + """ ... def receive() -> Optional[str]: - """``receive_bytes`` と同じように動作しますが、送信されてきたものはすべて返します。 + """Works in exactly the same way as ``receive_bytes`` but returns whatever was sent. -Example: ``radio.receive()`` + Example: ``radio.receive()`` -Equivalent to ``str(receive_bytes(), 'utf8')`` but with a check that the the first -three bytes are ``b'\x01\x00\x01'`` (to make it compatible with other platforms that -may target the micro:bit). + Equivalent to ``str(receive_bytes(), 'utf8')`` but with a check that the the first + three bytes are ``b'\x01\x00\x01'`` (to make it compatible with other platforms that + may target the micro:bit). -:return: The message with the prepended bytes stripped and converted to a string. + :return: The message with the prepended bytes stripped and converted to a string. -A ``ValueError`` exception is raised if conversion to string fails.""" + A ``ValueError`` exception is raised if conversion to string fails. + """ ... def receive_full() -> Optional[Tuple[bytes, int, int]]: - """メッセージキューにある次の受信メッセージを表す3つの値をタプルで返します。 + """Returns a tuple containing three values representing the next incoming message on the message queue. -Example: ``radio.receive_full()`` + Example: ``radio.receive_full()`` -If there are no pending messages then ``None`` is returned. + If there are no pending messages then ``None`` is returned. -The three values in the tuple represent: + The three values in the tuple represent: -- the next incoming message on the message queue as bytes. -- the RSSI (signal strength): a value between 0 (strongest) and -255 (weakest) as measured in dBm. -- a microsecond timestamp: the value returned by ``time.ticks_us()`` when the message was received. + - the next incoming message on the message queue as bytes. + - the RSSI (signal strength): a value between 0 (strongest) and -255 (weakest) as measured in dBm. + - a microsecond timestamp: the value returned by ``time.ticks_us()`` when the message was received. -For example:: + For example:: - details = radio.receive_full() - if details: - msg, rssi, timestamp = details + details = radio.receive_full() + if details: + msg, rssi, timestamp = details -This function is useful for providing information needed for triangulation -and/or trilateration with other micro:bit devices. + This function is useful for providing information needed for triangulation + and/or trilateration with other micro:bit devices. -:return: ``None`` if there is no message, otherwise a tuple of length three with the bytes, strength and timestamp values.""" - ... \ No newline at end of file + :return: ``None`` if there is no message, otherwise a tuple of length three with the bytes, strength and timestamp values. + """ + ... diff --git a/lang/ja/typeshed/stdlib/random.pyi b/lang/ja/typeshed/stdlib/random.pyi index 50560b1..a2c2ef3 100644 --- a/lang/ja/typeshed/stdlib/random.pyi +++ b/lang/ja/typeshed/stdlib/random.pyi @@ -1,80 +1,93 @@ -"""乱数を生成します。""" +"""Generate random numbers. +""" from typing import TypeVar, Sequence, Union, overload def getrandbits(n: int) -> int: - """``n`` 乱数ビット数を持つ整数を生成します。 + """Generate an integer with ``n`` random bits. -Example: ``random.getrandbits(1)`` + Example: ``random.getrandbits(1)`` -:param n: 1~30の値(指定の値を含みます)。""" + :param n: A value between 1-30 (inclusive). + """ ... def seed(n: int) -> None: - """乱数ジェネレータを初期化します。 + """Initialize the random number generator. -Example: ``random.seed(0)`` + Example: ``random.seed(0)`` -:param n: 整数シード + :param n: The integer seed -This will give you reproducibly deterministic randomness from a given starting -state (``n``).""" + This will give you reproducibly deterministic randomness from a given starting + state (``n``). + """ ... def randint(a: int, b: int) -> int: - """``a`` から ``b`` の区間内のランダムな整数値を返します(指定の値を含みます)。 + """Choose a random integer between ``a`` and ``b`` inclusive. -Example: ``random.randint(0, 9)`` + Example: ``random.randint(0, 9)`` -:param a: (A) 乱数区間の開始値(指定の値を含みます) -:param b: 乱数区間の終了値(指定の値を含みます) + :param a: Start value for the range (inclusive) + :param b: End value for the range (inclusive) -Alias for ``randrange(a, b + 1)``.""" + Alias for ``randrange(a, b + 1)``. + """ ... @overload def randrange(stop: int) -> int: - """0 から ``stop`` 未満までの間で無作為に選択された整数を返します。 + """Choose a randomly selected integer between zero and up to (but not + including) ``stop``. -Example: ``random.randrange(10)`` + Example: ``random.randrange(10)`` -:param stop: 乱数区間の終了値(指定の値を含みません)""" + :param stop: End value for the range (exclusive) + """ ... @overload -def randrange(start: int, stop: int, step: int=1) -> int: - """``range(start, stop, step)`` から無作為に選択された整数を返します。 +def randrange(start: int, stop: int, step: int = 1) -> int: + """ + Choose a randomly selected element from ``range(start, stop, step)``. -Example: ``random.randrange(0, 10)`` + Example: ``random.randrange(0, 10)`` -:param start: 乱数区間の開始値(指定の値を含みます) -:param stop: 乱数区間の終了値(指定の値を含みません) -:param step: ステップ値。""" + :param start: The start of the range (inclusive) + :param stop: The end of the range (exclusive) + :param step: The step. + """ ... -_T = TypeVar('_T') + +_T = TypeVar("_T") def choice(seq: Sequence[_T]) -> _T: - """空でないシーケンス ``seq`` からランダムな要素を返します。 + """Choose a random element from the non-empty sequence ``seq``. -Example: ``random.choice([Image.HAPPY, Image.SAD])`` + Example: ``random.choice([Image.HAPPY, Image.SAD])`` -:param seq: シーケンス。 + :param seq: A sequence. -If ``seq`` is empty, raises ``IndexError``.""" + If ``seq`` is empty, raises ``IndexError``. + """ ... def random() -> float: - """0.0 以上、1.0 未満の区間から無作為に選択された浮動小数点数を生成します。 + """Generate a random floating point number in the range [0.0, 1.0). -Example: ``random.random()`` + Example: ``random.random()`` -:return: The random floating point number""" + :return: The random floating point number + """ ... def uniform(a: float, b: float) -> float: - """``a`` から ``b`` の区間内のランダムな浮動小数点数を返します(指定の値を含みます)。 + """ + Return a random floating point number between ``a`` and ``b`` inclusive. -Example: ``random.uniform(0, 9)`` + Example: ``random.uniform(0, 9)`` -:param a: (A) 乱数区間の開始値(指定の値を含みます) -:param b: 乱数区間の終了値(指定の値を含みます)""" - ... \ No newline at end of file + :param a: Start value for the range (inclusive) + :param b: End value for the range (inclusive) + """ + ... diff --git a/lang/ja/typeshed/stdlib/speech.pyi b/lang/ja/typeshed/stdlib/speech.pyi index 25b5f53..349d188 100644 --- a/lang/ja/typeshed/stdlib/speech.pyi +++ b/lang/ja/typeshed/stdlib/speech.pyi @@ -1,79 +1,106 @@ -"""micro:bit に話させたり、歌わせたり、その他の音声のようなサウンドを作らせたりします。""" +"""Make the micro:bit talk, sing and make other speech like sounds. +""" + from typing import Optional from .microbit import MicroBitDigitalPin, pin0 def translate(words: str) -> str: - """英単語の並びを音素に変換します。 + """Translate English words to phonemes. -Example: ``speech.translate('hello world')`` + Example: ``speech.translate('hello world')`` -:param words: 英単語の並びの文字列。 -:return: A string containing a best guess at the appropriate phonemes to pronounce. -The output is generated from this `text to phoneme translation table `_. + :param words: A string of English words. + :return: A string containing a best guess at the appropriate phonemes to pronounce. + The output is generated from this `text to phoneme translation table `_. -This function should be used to generate a first approximation of phonemes -that can be further hand-edited to improve accuracy, inflection and -emphasis. + This function should be used to generate a first approximation of phonemes + that can be further hand-edited to improve accuracy, inflection and + emphasis. -See `the online documentation `_ for detailed information.""" + See `the online documentation `_ for detailed information. + """ ... -def pronounce(phonemes: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: Optional[MicroBitDigitalPin]=pin0) -> None: - """音素を発声します。 - -Example: ``speech.pronounce(' /HEHLOW WERLD')`` - -:param phonemes: 発音する音素の文字列 -:param pitch: 音声の音高を表す数値 -:param speed: 音声の速度を表す数値 -:param mouth: 音声の口の動きを表す数値 -:param throat: 音声の喉の動きを表す数値 -:param pin: (ピン) 出力端子をデフォルトの ``pin0`` から変えるためのオプション引数。 -音を鳴らしたくない場合は ``pin=None`` を指定します。micro:bit V2 のみで使えます。 - -Override the optional pitch, speed, mouth and throat settings to change the -timbre (quality) of the voice. - -See `the online documentation `_ for detailed information.""" +def pronounce( + phonemes: str, + pitch: int = 64, + speed: int = 72, + mouth: int = 128, + throat: int = 128, + pin: Optional[MicroBitDigitalPin] = pin0, +) -> None: + """Pronounce phonemes. + + Example: ``speech.pronounce(' /HEHLOW WERLD')`` + + :param phonemes: The string of phonemes to pronounce + :param pitch: A number representing the pitch of the voice + :param speed: A number representing the speed of the voice + :param mouth: A number representing the mouth of the voice + :param throat: A number representing the throat of the voice + :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. + If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. + + Override the optional pitch, speed, mouth and throat settings to change the + timbre (quality) of the voice. + + See `the online documentation `_ for detailed information. + """ ... -def say(words: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: MicroBitDigitalPin=pin0) -> None: - """英単語の並びを発声します。 - -Example: ``speech.say('hello world')`` - -:param words: 発声する言葉の文字列。 -:param pitch: 音声の音高を表す数値 -:param speed: 音声の速度を表す数値 -:param mouth: 音声の口の動きを表す数値 -:param throat: 音声の喉の動きを表す数値 -:param pin: (ピン) 出力端子をデフォルトの ``pin0`` から変えるためのオプション引数。 -音を鳴らしたくない場合は ``pin=None`` を指定します。micro:bit V2 のみで使えます。 - -The result is semi-accurate for English. Override the optional pitch, speed, -mouth and throat settings to change the timbre (quality) of the voice. - -This is a short-hand equivalent of: -``speech.pronounce(speech.translate(words))`` - -See `the online documentation `_ for detailed information.""" +def say( + words: str, + pitch: int = 64, + speed: int = 72, + mouth: int = 128, + throat: int = 128, + pin: MicroBitDigitalPin = pin0, +) -> None: + """Say English words. + + Example: ``speech.say('hello world')`` + + :param words: The string of words to say. + :param pitch: A number representing the pitch of the voice + :param speed: A number representing the speed of the voice + :param mouth: A number representing the mouth of the voice + :param throat: A number representing the throat of the voice + :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. + If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. + + The result is semi-accurate for English. Override the optional pitch, speed, + mouth and throat settings to change the timbre (quality) of the voice. + + This is a short-hand equivalent of: + ``speech.pronounce(speech.translate(words))`` + + See `the online documentation `_ for detailed information. + """ ... -def sing(phonemes: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: MicroBitDigitalPin=pin0) -> None: - """音素を歌います。 - -Example: ``speech.sing(' /HEHLOW WERLD')`` - -:param phonemes: 歌う言葉の文字列。 -:param pitch: 音声の音高を表す数値 -:param speed: 音声の速度を表す数値 -:param mouth: 音声の口の動きを表す数値 -:param throat: 音声の喉の動きを表す数値 -:param pin: (ピン) 出力端子をデフォルトの ``pin0`` から変えるためのオプション引数。 -音を鳴らしたくない場合は ``pin=None`` を指定します。micro:bit V2 のみで使えます。 - -Override the optional pitch, speed, mouth and throat settings to change -the timbre (quality) of the voice. - -See `the online documentation `_ for detailed information.""" - ... \ No newline at end of file +def sing( + phonemes: str, + pitch: int = 64, + speed: int = 72, + mouth: int = 128, + throat: int = 128, + pin: MicroBitDigitalPin = pin0, +) -> None: + """Sing phonemes. + + Example: ``speech.sing(' /HEHLOW WERLD')`` + + :param phonemes: The string of words to sing. + :param pitch: A number representing the pitch of the voice + :param speed: A number representing the speed of the voice + :param mouth: A number representing the mouth of the voice + :param throat: A number representing the throat of the voice + :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. + If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. + + Override the optional pitch, speed, mouth and throat settings to change + the timbre (quality) of the voice. + + See `the online documentation `_ for detailed information. + """ + ... diff --git a/lang/ja/typeshed/stdlib/struct.pyi b/lang/ja/typeshed/stdlib/struct.pyi index 987f964..53b3e0b 100644 --- a/lang/ja/typeshed/stdlib/struct.pyi +++ b/lang/ja/typeshed/stdlib/struct.pyi @@ -1,56 +1,65 @@ -"""プリミティブデータ型のパックとアンパック。""" +"""Pack and unpack primitive data types. +""" + from _typeshed import ReadableBuffer, WriteableBuffer from typing import Any, Tuple, Union def calcsize(fmt: str) -> int: - """指定した ``fmt`` で格納するために必要なバイト数を取得します。 + """Get the number of bytes needed to store the given ``fmt``. -Example: ``struct.calcsize('hf')`` + Example: ``struct.calcsize('hf')`` -:param fmt: フォーマット文字列。 -:return The number of bytes needed to store such a value.""" + :param fmt: A format string. + :return The number of bytes needed to store such a value. + """ ... def pack(fmt: str, v1: Any, *vn: Any) -> bytes: - """フォーマット文字列にしたがって複数の値をパックします。 + """Pack values according to a format string. -Example: ``struct.pack('hf', 1, 3.1415)`` + Example: ``struct.pack('hf', 1, 3.1415)`` -:param fmt: フォーマット文字列。 -:param v1: 先頭の値。 -:param *vn: 残りの値。 -:return A bytes object encoding the values.""" + :param fmt: The format string. + :param v1: The first value. + :param *vn: The remaining values. + :return A bytes object encoding the values. + """ ... -def pack_into(fmt: str, buffer: WriteableBuffer, offset: int, v1: Any, *vn: Any) -> None: - """フォーマット文字列にしたがって複数の値をパックします。 +def pack_into( + fmt: str, buffer: WriteableBuffer, offset: int, v1: Any, *vn: Any +) -> None: + """Pack values according to a format string. -Example: ``struct.pack_info('hf', buffer, 1, 3.1415)`` + Example: ``struct.pack_info('hf', buffer, 1, 3.1415)`` -:param fmt: フォーマット文字列。 -:param buffer: 書き込み先のバッファ。 -:param offset: バッファのオフセット。負の場合はバッファの最後からのオフセットになります。 -:param v1: 先頭の値。 -:param *vn: 残りの値。""" + :param fmt: The format string. + :param buffer: The target buffer to write into. + :param offset: The offset into the buffer. May be negative to count from the end of the buffer. + :param v1: The first value. + :param *vn: The remaining values. + """ ... def unpack(fmt: str, data: ReadableBuffer) -> Tuple[Any, ...]: - """フォーマット文字列にしたがってデータをアンパックします。 + """Unpack data according to a format string. -Example: ``v1, v2 = struct.unpack('hf', buffer)`` + Example: ``v1, v2 = struct.unpack('hf', buffer)`` -:param fmt: フォーマット文字列。 -:param data: データ。 -:return: A tuple of the unpacked values.""" + :param fmt: The format string. + :param data: The data. + :return: A tuple of the unpacked values. + """ ... -def unpack_from(fmt: str, buffer: ReadableBuffer, offset: int=0) -> Tuple: - """フォーマット文字列にしたがってバッファからデータをアンパックします。 +def unpack_from(fmt: str, buffer: ReadableBuffer, offset: int = 0) -> Tuple: + """Unpack data from a buffer according to a format string. -Example: ``v1, v2 = struct.unpack_from('hf', buffer)`` + Example: ``v1, v2 = struct.unpack_from('hf', buffer)`` -:param fmt: フォーマット文字列。 -:param buffer: 読み込み元のバッファ。 -:param offset: バッファのオフセット。負の場合はバッファの最後からのオフセットになります。 -:return: A tuple of the unpacked values.""" - ... \ No newline at end of file + :param fmt: The format string. + :param buffer: The source buffer to read from. + :param offset: The offset into the buffer. May be negative to count from the end of the buffer. + :return: A tuple of the unpacked values. + """ + ... diff --git a/lang/ja/typeshed/stdlib/sys.pyi b/lang/ja/typeshed/stdlib/sys.pyi index 136e7d3..320bac9 100644 --- a/lang/ja/typeshed/stdlib/sys.pyi +++ b/lang/ja/typeshed/stdlib/sys.pyi @@ -1,36 +1,43 @@ -"""システム固有関数。""" +"""System specific functions""" + from typing import Any, Dict, List, NoReturn, TextIO, Tuple -def exit(retval: object=...) -> NoReturn: - """与えた終了コードで現在のプログラムを終了します。 +def exit(retval: object = ...) -> NoReturn: + """Terminate current program with a given exit code. -Example: ``sys.exit(1)`` + Example: ``sys.exit(1)`` -This function raises a ``SystemExit`` exception. If an argument is given, its -value given as an argument to ``SystemExit``. + This function raises a ``SystemExit`` exception. If an argument is given, its + value given as an argument to ``SystemExit``. -:param retval: 終了コードまたはメッセージ。""" + :param retval: The exit code or message. + """ ... def print_exception(exc: Exception) -> None: - """例外をトレースバック付きで出力します。 + """ + Print an exception with a traceback. + + Example: ``sys.print_exception(e)`` -Example: ``sys.print_exception(e)`` + :param exc: The exception to print -:param exc: 表示する例外 + This is simplified version of a function which appears in the + ``traceback`` module in CPython. + """ -This is simplified version of a function which appears in the -``traceback`` module in CPython.""" argv: List[str] -"""現在のプログラム開始時の引数の変更可能なリスト。""" +"""A mutable list of arguments the current program was started with.""" + byteorder: str -"""システムのバイト順(``"little"`` または ``"big"``)。""" +"""The byte order of the system (``"little"`` or ``"big"``).""" class _implementation: name: str version: Tuple[int, int, int] + implementation: _implementation -"""現在の Python 処理系に関する情報を持つオブジェクト。 +"""Object with information about the current Python implementation. For MicroPython, it has following attributes: @@ -44,9 +51,13 @@ minimal ports). CPython mandates more attributes for this object, but the actual useful bare minimum is implemented in MicroPython. """ + maxsize: int """ -現在のプラットフォームでネイティブ整数型が保持できる最大値、またはプラットフォームの最大値より小さい場合は MicroPython 整数型で表現可能な最大値(MicroPython ポートで 長整数をサポートしないとした場合)。 +Maximum value which a native integer type can hold on the current platform, +or maximum value representable by MicroPython integer type, if it's smaller +than platform max value (that is the case for MicroPython ports without +long int support). This attribute is useful for detecting "bitness" of a platform (32-bit vs 64-bit, etc.). It's recommended to not compare this attribute to some @@ -66,14 +77,17 @@ value directly, but instead count number of bits in it:: # (e.g. 31) due to peculiarities described above, so use "> 16", # "> 32", "> 64" style of comparisons. """ + modules: Dict[str, Any] -"""読み込まれたモジュールの辞書。 +"""Dictionary of loaded modules. On some ports, it may not include builtin modules.""" + path: List[str] -"""インポートするモジュールを検索するディレクトリの変更可能なリスト。""" +"""A mutable list of directories to search for imported modules.""" + platform: str -"""MicroPython が実行されているプラ\u200b\u200bットフォーム。 +"""The platform that MicroPython is running on. For OS/RTOS ports, this is usually an identifier of the OS, e.g. ``"linux"``. For baremetal ports it is an identifier of a board, e.g. ``"pyboard"`` for @@ -83,11 +97,13 @@ distinguish one board from another. If you need to check whether your program runs on MicroPython (vs other Python implementation), use ``sys.implementation`` instead. """ + version: str -"""この処理系が準拠するPython言語バージョンを表す文字列。""" +"""Python language version that this implementation conforms to, as a string.""" + version_info: Tuple[int, int, int] -"""この実装が準拠しているPython言語バージョンを表すintのタプル。 +"""Python language version that this implementation conforms to, as a tuple of ints. Only the first three version numbers (major, minor, micro) are supported and they can be referenced only by index, not by name. -""" \ No newline at end of file +""" diff --git a/lang/ja/typeshed/stdlib/time.pyi b/lang/ja/typeshed/stdlib/time.pyi index 9e894e8..598c483 100644 --- a/lang/ja/typeshed/stdlib/time.pyi +++ b/lang/ja/typeshed/stdlib/time.pyi @@ -1,111 +1,132 @@ -"""時間の測定とプログラムの遅延。""" +"""Measure time and add delays to programs. +""" + from typing import Union def sleep(seconds: Union[int, float]) -> None: - """指定した秒数だけ遅延します。 + """ + Delay a number of seconds. -Example: ``time.sleep(1)`` + Example: ``time.sleep(1)`` -:param seconds: スリープする秒数。 -秒より細かい精度で指定したい場合は浮動小数点数を使ってください。""" + :param seconds: The number of seconds to sleep for. + Use a floating-point number to sleep for a fractional number of seconds. + """ ... def sleep_ms(ms: int) -> None: - """指定したミリ秒だけ遅延します。 + """ + Delay for given number of milliseconds. -Example: ``time.sleep_ms(1_000_000)`` + Example: ``time.sleep_ms(1_000_000)`` -:param ms: 遅延するミリ秒数(>= 0)。""" + :param ms: The number of milliseconds delay (>= 0). + """ ... def sleep_us(us: int) -> None: - """指定したマイクロ秒だけ遅延します。 + """ + Delay for given number of microseconds. -Example: ``time.sleep_us(1000)`` + Example: ``time.sleep_us(1000)`` -:param us: 遅延するマイクロ秒数(>= 0)。""" + :param us: The number of microseconds delay (>= 0). + """ ... def ticks_ms() -> int: - """呼出し時点での稼働時間をミリ秒単位で取得します。稼働時間は最大値に達するとラップアラウンドします。 + """ + Get an increasing, millisecond counter with an arbitrary reference point, + that wraps around after some value. -Example: ``time.ticks_ms()`` + Example: ``time.ticks_ms()`` -:return: The counter value in milliseconds.""" + :return: The counter value in milliseconds. + """ ... def ticks_us() -> int: - """呼出し時点での稼働時間をマイクロ秒単位で取得します。稼働時間は最大値に達するとラップアラウンドします。 + """ + Get an increasing, microsecond counter with an arbitrary reference point, + that wraps around after some value. -Example: ``time.ticks_us()`` + Example: ``time.ticks_us()`` -:return: The counter value in microseconds.""" + :return: The counter value in microseconds. + """ ... def ticks_add(ticks: int, delta: int) -> int: - """与えた数をティック値からのオフセットとして加算した値を返します。引数の値は正でも負でもかまいません。 + """ + Offset ticks value by a given number, which can be either positive or + negative. -Example: ``time.ticks_add(time.ticks_ms(), 200)`` + Example: ``time.ticks_add(time.ticks_ms(), 200)`` -Given a ticks value, this function allows to calculate ticks -value delta ticks before or after it, following modular-arithmetic -definition of tick values. + Given a ticks value, this function allows to calculate ticks + value delta ticks before or after it, following modular-arithmetic + definition of tick values. -:param ticks: ティック値 -:param delta: 整数オフセット + :param ticks: A ticks value + :param delta: An integer offset -Example:: + Example:: - # Find out what ticks value there was 100ms ago - print(ticks_add(time.ticks_ms(), -100)) + # Find out what ticks value there was 100ms ago + print(ticks_add(time.ticks_ms(), -100)) - # Calculate deadline for operation and test for it - deadline = ticks_add(time.ticks_ms(), 200) - while ticks_diff(deadline, time.ticks_ms()) > 0: - do_a_little_of_something() + # Calculate deadline for operation and test for it + deadline = ticks_add(time.ticks_ms(), 200) + while ticks_diff(deadline, time.ticks_ms()) > 0: + do_a_little_of_something() - # Find out TICKS_MAX used by this port - print(ticks_add(0, -1))""" + # Find out TICKS_MAX used by this port + print(ticks_add(0, -1)) + """ ... def ticks_diff(ticks1: int, ticks2: int) -> int: - """``time.ticks_ms()`` や ``ticks_us()`` 関数の戻り値(ラップアラウンドする可能性のある符号付きの値)の間のティック値の差を計算します。 - -Example: ``time.ticks_diff(scheduled_time, now)`` - -:param ticks1: 引かられる方の値 -:param ticks2: 引く方の値 - -The argument order is the same as for subtraction operator, -``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. - -``ticks_diff()`` is designed to accommodate various usage -patterns, among them: - -Polling with timeout. In this case, the order of events is known, and you -will deal only with positive results of :func:`time.ticks_diff()`:: - - # Wait for GPIO pin to be asserted, but at most 500us - start = time.ticks_us() - while pin.value() == 0: - if time.ticks_diff(time.ticks_us(), start) > 500: - raise TimeoutError - - -Scheduling events. In this case, :func:`time.ticks_diff()` result may be -negative if an event is overdue:: - - # This code snippet is not optimized - now = time.ticks_ms() - scheduled_time = task.scheduled_time() - if ticks_diff(scheduled_time, now) > 0: - print("Too early, let's nap") - sleep_ms(ticks_diff(scheduled_time, now)) - task.run() - elif ticks_diff(scheduled_time, now) == 0: - print("Right at time!") - task.run() - elif ticks_diff(scheduled_time, now) < 0: - print("Oops, running late, tell task to run faster!") - task.run(run_faster=True)""" - ... \ No newline at end of file + """ + Measure ticks difference between values returned from + ``time.ticks_ms()`` or ``ticks_us()``, as a signed value + which may wrap around. + + Example: ``time.ticks_diff(scheduled_time, now)`` + + :param ticks1: The value to subtract from + :param ticks2: The value to subtract + + The argument order is the same as for subtraction operator, + ``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. + + ``ticks_diff()`` is designed to accommodate various usage + patterns, among them: + + Polling with timeout. In this case, the order of events is known, and you + will deal only with positive results of :func:`time.ticks_diff()`:: + + # Wait for GPIO pin to be asserted, but at most 500us + start = time.ticks_us() + while pin.value() == 0: + if time.ticks_diff(time.ticks_us(), start) > 500: + raise TimeoutError + + + Scheduling events. In this case, :func:`time.ticks_diff()` result may be + negative if an event is overdue:: + + # This code snippet is not optimized + now = time.ticks_ms() + scheduled_time = task.scheduled_time() + if ticks_diff(scheduled_time, now) > 0: + print("Too early, let's nap") + sleep_ms(ticks_diff(scheduled_time, now)) + task.run() + elif ticks_diff(scheduled_time, now) == 0: + print("Right at time!") + task.run() + elif ticks_diff(scheduled_time, now) < 0: + print("Oops, running late, tell task to run faster!") + task.run(run_faster=True) + """ + ... diff --git a/lang/ko/typeshed/stdlib/gc.pyi b/lang/ko/typeshed/stdlib/gc.pyi index 0efcfde..1370abf 100644 --- a/lang/ko/typeshed/stdlib/gc.pyi +++ b/lang/ko/typeshed/stdlib/gc.pyi @@ -1,68 +1,73 @@ -"""가비지 컬렉터 제어""" +"""Control the garbage collector""" + from typing import overload def enable() -> None: - """자동 가비지 컬렉션을 활성화합니다.""" + """Enable automatic garbage collection.""" ... def disable() -> None: - """자동 가비지 컬렉션을 비활성화합니다. + """Disable automatic garbage collection. -Heap memory can still be allocated, -and garbage collection can still be initiated manually using ``gc.collect``.""" + Heap memory can still be allocated, + and garbage collection can still be initiated manually using ``gc.collect``.""" def collect() -> None: - """가비지 컬렉션을 실행합니다.""" + """Run a garbage collection.""" ... def mem_alloc() -> int: - """할당된 힙 RAM의 바이트 수를 불러옵니다. + """Get the number of bytes of heap RAM that are allocated. -:return: The number of bytes allocated. + :return: The number of bytes allocated. -This function is MicroPython extension.""" + This function is MicroPython extension. + """ ... def mem_free() -> int: - """이용 가능한 힙 RAM의 바이트 수를 불러옵니다. 값을 알 수 없는 경우 -1을 반환합니다. + """Get the number of bytes of available heap RAM, or -1 if this amount is not known. -:return: The number of bytes free. + :return: The number of bytes free. -This function is MicroPython extension.""" + This function is MicroPython extension. + """ ... @overload def threshold() -> int: - """추가 GC 할당 임계값을 요청합니다. + """Query the additional GC allocation threshold. -:return: The GC allocation threshold. + :return: The GC allocation threshold. -This function is a MicroPython extension. CPython has a similar -function - ``set_threshold()``, but due to different GC -implementations, its signature and semantics are different.""" + This function is a MicroPython extension. CPython has a similar + function - ``set_threshold()``, but due to different GC + implementations, its signature and semantics are different. + """ ... @overload def threshold(amount: int) -> None: - """추가 GC 할당 임계값을 설정합니다. - -Normally, a collection is triggered only when a new allocation -cannot be satisfied, i.e. on an out-of-memory (OOM) condition. -If this function is called, in addition to OOM, a collection -will be triggered each time after ``amount`` bytes have been -allocated (in total, since the previous time such an amount of bytes -have been allocated). ``amount`` is usually specified as less than the -full heap size, with the intention to trigger a collection earlier than when the -heap becomes exhausted, and in the hope that an early collection will prevent -excessive memory fragmentation. This is a heuristic measure, the effect -of which will vary from application to application, as well as -the optimal value of the ``amount`` parameter. - -A value of -1 means a disabled allocation threshold. - -This function is a MicroPython extension. CPython has a similar -function - ``set_threshold()``, but due to different GC -implementations, its signature and semantics are different. - -:param amount: 가비지 컬렉션이 트리거되는 바이트 수입니다.""" - ... \ No newline at end of file + """Set the additional GC allocation threshold. + + Normally, a collection is triggered only when a new allocation + cannot be satisfied, i.e. on an out-of-memory (OOM) condition. + If this function is called, in addition to OOM, a collection + will be triggered each time after ``amount`` bytes have been + allocated (in total, since the previous time such an amount of bytes + have been allocated). ``amount`` is usually specified as less than the + full heap size, with the intention to trigger a collection earlier than when the + heap becomes exhausted, and in the hope that an early collection will prevent + excessive memory fragmentation. This is a heuristic measure, the effect + of which will vary from application to application, as well as + the optimal value of the ``amount`` parameter. + + A value of -1 means a disabled allocation threshold. + + This function is a MicroPython extension. CPython has a similar + function - ``set_threshold()``, but due to different GC + implementations, its signature and semantics are different. + + :param amount: The number of bytes after which a garbage collection should be triggered. + """ + ... diff --git a/lang/ko/typeshed/stdlib/log.pyi b/lang/ko/typeshed/stdlib/log.pyi index 3da3957..c9870fa 100644 --- a/lang/ko/typeshed/stdlib/log.pyi +++ b/lang/ko/typeshed/stdlib/log.pyi @@ -1,89 +1,104 @@ -"""micro:bit V2에 데이터를 기록합니다.""" +"""Log data to your micro:bit V2.""" + from typing import Literal, Mapping, Optional, Union, overload + MILLISECONDS = 1 -"""밀리초 타임스탬프 형식입니다.""" +"""Milliseconds timestamp format.""" + SECONDS = 10 -"""초 타임스탬프 형식입니다.""" +"""Seconds timestamp format.""" + MINUTES = 600 -"""분 타임스탬프 형식입니다.""" +"""Minutes timestamp format.""" + HOURS = 36000 -"""시간 타임스탬프 형식입니다.""" +"""Hours timestamp format.""" + DAYS = 864000 -"""일 타임스탬프 형식입니다.""" +"""Days timestamp format.""" -def set_labels(*labels: str, timestamp: Optional[Literal[1, 10, 36000, 864000]]=SECONDS) -> None: - """로그 파일 헤더를 설정합니다. +def set_labels( + *labels: str, timestamp: Optional[Literal[1, 10, 36000, 864000]] = SECONDS +) -> None: + """Set up the log file header. -Example: ``log.set_labels('X', 'Y', 'Z', timestamp=log.MINUTES)`` + Example: ``log.set_labels('X', 'Y', 'Z', timestamp=log.MINUTES)`` -Ideally this function should be called a single time, before any data is -logged, to configure the data table header once. + Ideally this function should be called a single time, before any data is + logged, to configure the data table header once. -If a log file already exists when the program starts, or if this function -is called multiple times, it will check the labels already defined in the -log file. If this function call contains any new labels not already -present, it will generate a new header row with the additional columns. + If a log file already exists when the program starts, or if this function + is called multiple times, it will check the labels already defined in the + log file. If this function call contains any new labels not already + present, it will generate a new header row with the additional columns. -By default the first column contains a timestamp for each row. The time -unit can be selected via the timestamp argument. + By default the first column contains a timestamp for each row. The time + unit can be selected via the timestamp argument. -:param *labels: (*레이블) 각각 로그 헤더의 항목에 해당하는 임의의 위치 인수 수입니다. -:param timestamp: (타임스탬프) 모든 행의 첫 번째에 자동으로 삽입될 타임스탬프 단위를 선택하십시오. 타임스탬프의 값은 ``log.MILLISECONDS``, ``log.SECONDS``, ``log.MINUTES``, ``log.HOURS``, ``log.DAYS``가 될 수 있고 비활성화하려면 ``None``값으로 설정하십시오. 타임스탬프의 기본값은 ``log.SECONDS``입니다.""" + :param *labels: Any number of positional arguments, each corresponding to an entry in the log header. + :param timestamp: Select the timestamp unit that will be automatically added as the first column in every row. Timestamp values can be one of ``log.MILLISECONDS``, ``log.SECONDS``, ``log.MINUTES``, ``log.HOURS``, ``log.DAYS`` or ``None`` to disable the timestamp. The default value is ``log.SECONDS``. + """ ... @overload -def add(data_dictionary: Optional[Mapping[str, Union[str, int, float]]]) -> None: - """헤더 및 값의 딕셔너리를 패스해 로그에 데이터 행을 추가합니다. +def add( + data_dictionary: Optional[Mapping[str, Union[str, int, float]]], +) -> None: + """Add a data row to the log by passing a dictionary of headers and values. -Example: ``log.add({ 'temp': temperature() })`` + Example: ``log.add({ 'temp': temperature() })`` -Each call to this function adds a row to the log. + Each call to this function adds a row to the log. -New labels not previously specified via the set_labels function, or by a -previous call to this function, will trigger a new header entry to be added -to the log with the extra labels. + New labels not previously specified via the set_labels function, or by a + previous call to this function, will trigger a new header entry to be added + to the log with the extra labels. -Labels previously specified and not present in a call to this function will -be skipped with an empty value in the log row. + Labels previously specified and not present in a call to this function will + be skipped with an empty value in the log row. -:param data_dictionary: (데이터 사전) 각 헤더에 대한 키가 있는 사전으로 기록할 데이터입니다.""" + :param data_dictionary: The data to log as a dictionary with a key for each header. + """ ... @overload def add(**kwargs: Union[str, int, float]) -> None: - """키워드 인자를 사용해 로그에 데이터 행을 추가합니다. + """Add a data row to the log using keyword arguments. -Example: ``log.add(temp=temperature())`` + Example: ``log.add(temp=temperature())`` -Each call to this function adds a row to the log. + Each call to this function adds a row to the log. -New labels not previously specified via the set_labels function, or by a -previous call to this function, will trigger a new header entry to be added -to the log with the extra labels. + New labels not previously specified via the set_labels function, or by a + previous call to this function, will trigger a new header entry to be added + to the log with the extra labels. -Labels previously specified and not present in a call to this function will -be skipped with an empty value in the log row.""" + Labels previously specified and not present in a call to this function will + be skipped with an empty value in the log row. + """ ... def delete(full=False): - """헤더를 포함한 로그의 내용을 삭제합니다. + """Deletes the contents of the log, including headers. -Example: ``log.delete()`` + Example: ``log.delete()`` -To add the log headers again the ``set_labels`` function should to be called after this function. + To add the log headers again the ``set_labels`` function should to be called after this function. -There are two erase modes; “full” completely removes the data from the physical storage, -and “fast” invalidates the data without removing it. + There are two erase modes; “full” completely removes the data from the physical storage, + and “fast” invalidates the data without removing it. -:param full: ``True``는 "전체" 지우기를 선택하고 ``False``는 "빠른" 지우기 방법을 선택합니다.""" + :param full: ``True`` selects a “full” erase and ``False`` selects the “fast” erase method. + """ ... def set_mirroring(serial: bool): - """직렬 출력에 대한 데이터 로깅 작업 미러링을 구성합니다. + """Configure mirroring of the data logging activity to the serial output. -Example: ``log.set_mirroring(True)`` + Example: ``log.set_mirroring(True)`` -Serial mirroring is disabled by default. When enabled, it will print to serial each row logged into the log file. + Serial mirroring is disabled by default. When enabled, it will print to serial each row logged into the log file. -:param serial: ``True``로 설정할 경우 시리얼 출력 인터페이스에 데이터를 미러링하는 것이 허용됩니다.""" - ... \ No newline at end of file + :param serial: ``True`` enables mirroring data to the serial output. + """ + ... diff --git a/lang/ko/typeshed/stdlib/machine.pyi b/lang/ko/typeshed/stdlib/machine.pyi index 97f92aa..2e82f5b 100644 --- a/lang/ko/typeshed/stdlib/machine.pyi +++ b/lang/ko/typeshed/stdlib/machine.pyi @@ -1,84 +1,97 @@ -"""로우 레벨 유틸리티입니다.""" +"""Low-level utilities. +""" from typing import Any from .microbit import MicroBitDigitalPin def unique_id() -> bytes: - """보드의 고유 식별자가 있는 바이트 문자열을 불러옵니다. + """Get a byte string with a unique identifier of a board. -Example: ``machine.unique_id()`` + Example: ``machine.unique_id()`` -:return: An identifier that varies from one board instance to another.""" + :return: An identifier that varies from one board instance to another. + """ ... def reset() -> None: - """외부 초기화 버튼을 누른 것과 유사한 방식으로 기기를 초기화합니다. + """Reset the device in a manner similar to pushing the external RESET button. -Example: ``machine.reset()``""" + Example: ``machine.reset()`` + """ ... def freq() -> int: - """헤르츠로 표시된 CPU 진동수를 불러옵니다. + """Get the CPU frequency in hertz. -Example: ``machine.freq()`` + Example: ``machine.freq()`` -:return: The CPU frequency.""" + :return: The CPU frequency. + """ ... def disable_irq() -> Any: - """인터럽트 요청을 비활성화합니다. + """Disable interrupt requests. -Example: ``interrupt_state = machine.disable_irq()`` + Example: ``interrupt_state = machine.disable_irq()`` -:return: the previous IRQ state which should be considered an opaque value + :return: the previous IRQ state which should be considered an opaque value -The return value should be passed to the ``enable_irq`` function to restore -interrupts to their original state.""" + The return value should be passed to the ``enable_irq`` function to restore + interrupts to their original state. + """ ... def enable_irq(state: Any) -> None: - """인터럽트 요청을 재활성화합니다. + """Re-enable interrupt requests. -Example: ``machine.enable_irq(interrupt_state)`` + Example: ``machine.enable_irq(interrupt_state)`` -:param state: ``disable_irq`` 함수에서 가장 최근에 호출된 값을 반환합니다.""" + :param state: The value that was returned from the most recent call to the ``disable_irq`` function. + """ ... -def time_pulse_us(pin: MicroBitDigitalPin, pulse_level: int, timeout_us: int=1000000) -> int: - """핀 펄스 시간을 측정합니다. +def time_pulse_us( + pin: MicroBitDigitalPin, pulse_level: int, timeout_us: int = 1000000 +) -> int: + """Time a pulse on a pin. -Example: ``time_pulse_us(pin0, 1)`` + Example: ``time_pulse_us(pin0, 1)`` -If the current input value of the pin is different to ``pulse_level``, the -function first waits until the pin input becomes equal to -``pulse_level``, then times the duration that the pin is equal to -``pulse_level``. If the pin is already equal to ``pulse_level`` then timing -starts straight away. + If the current input value of the pin is different to ``pulse_level``, the + function first waits until the pin input becomes equal to + ``pulse_level``, then times the duration that the pin is equal to + ``pulse_level``. If the pin is already equal to ``pulse_level`` then timing + starts straight away. -:param pin: (핀) 사용할 핀 -:param pulse_level: (펄스 레벨) 로우 펄스의 시간을 측정하려면 0, 하이 펄스는 1 -:param timeout_us: 마이크로초 시간 초과 -:return: The duration of the pulse in microseconds, or -1 for a timeout waiting for the level to match ``pulse_level``, or -2 on timeout waiting for the pulse to end""" + :param pin: The pin to use + :param pulse_level: 0 to time a low pulse or 1 to time a high pulse + :param timeout_us: A microsecond timeout + :return: The duration of the pulse in microseconds, or -1 for a timeout waiting for the level to match ``pulse_level``, or -2 on timeout waiting for the pulse to end + """ ... class mem: - """``mem8``, ``mem16``, ``mem32`` 메모리 뷰 클래스""" + """The class for the ``mem8``, ``mem16`` and ``mem32`` memory views.""" def __getitem__(self, address: int) -> int: - """메모리 값에 액세스합니다. + """Access a value from memory. -:param address: 메모리 주소입니다. -:return: The value at that address as an integer.""" + :param address: The memory address. + :return: The value at that address as an integer. + """ ... - def __setitem__(self, address: int, value: int) -> None: - """제공된 주소에 값을 설정합니다. + """Set a value at the given address. -:param address: 메모리 주소입니다. -:param value: 설정할 정수값입니다.""" + :param address: The memory address. + :param value: The integer value to set. + """ ... + mem8: mem -"""8비트(바이트) 메모리 뷰입니다.""" +"""8-bit (byte) view of memory.""" + mem16: mem -"""16비트 메모리 뷰입니다.""" +"""16-bit view of memory.""" + mem32: mem -"""32비트 메모리 뷰입니다.""" \ No newline at end of file +"""32-bit view of memory.""" diff --git a/lang/ko/typeshed/stdlib/math.pyi b/lang/ko/typeshed/stdlib/math.pyi index bb2dc94..f82d4de 100644 --- a/lang/ko/typeshed/stdlib/math.pyi +++ b/lang/ko/typeshed/stdlib/math.pyi @@ -1,246 +1,273 @@ -"""수학 함수입니다.""" +"""Mathematical functions. +""" + from typing import Tuple def acos(x: float) -> float: - """코사인의 역을 계산합니다. + """Calculate the inverse cosine. -Example: ``math.acos(1)`` + Example: ``math.acos(1)`` -:param x: 숫자 -:return: The inverse cosine of ``x``""" + :param x: A number + :return: The inverse cosine of ``x`` + """ ... def asin(x: float) -> float: - """사인의 역을 계산합니다. + """Calculate the inverse sine. -Example: ``math.asin(0)`` + Example: ``math.asin(0)`` -:param x: 숫자 -:return: The inverse sine of ``x``""" + :param x: A number + :return: The inverse sine of ``x`` + """ ... def atan(x: float) -> float: - """탄젠트의 역을 계산합니다. + """Calculate the inverse tangent. -Example: ``math.atan(0)`` + Example: ``math.atan(0)`` -:param x: 숫자 -:return: The inverse tangent of ``x``""" + :param x: A number + :return: The inverse tangent of ``x`` + """ ... def atan2(y: float, x: float) -> float: - """``y/x``의 역 탄젠트의 주 값을 계산합니다. + """Calculate the principal value of the inverse tangent of ``y/x``. -Example: ``math.atan2(0, -1)`` + Example: ``math.atan2(0, -1)`` -:param y: 숫자 -:param x: 숫자 -:return: The principal value of the inverse tangent of ``y/x``""" + :param y: A number + :param x: A number + :return: The principal value of the inverse tangent of ``y/x`` + """ ... def ceil(x: float) -> float: - """양의 무한대로 숫자를 반올림합니다. + """Round a number towards positive infinity. -Example: ``math.ceil(0.1)`` + Example: ``math.ceil(0.1)`` -:param x: 숫자 -:return: ``x`` rounded towards positive infinity.""" + :param x: A number + :return: ``x`` rounded towards positive infinity. + """ ... def copysign(x: float, y: float) -> float: - """``y``의 사인 값으로 ``x``를 계산합니다. + """Calculate ``x`` with the sign of ``y``. -Example: ``math.copysign(1, -1)`` + Example: ``math.copysign(1, -1)`` -:param x: 숫자 -:param y: 반환값의 사인의 출처 -:return: ``x`` with the sign of ``y``""" + :param x: A number + :param y: The source of the sign for the return value + :return: ``x`` with the sign of ``y`` + """ ... def cos(x: float) -> float: - """``x``의 코사인을 계산합니다. + """Calculate the cosine of ``x``. -Example: ``math.cos(0)`` + Example: ``math.cos(0)`` -:param x: 숫자 -:return: The cosine of ``x``""" + :param x: A number + :return: The cosine of ``x`` + """ ... def degrees(x: float) -> float: - """호도법을 각도법으로 변환합니다. (도) + """Convert radians to degrees. -Example: ``math.degrees(2 * math.pi)`` + Example: ``math.degrees(2 * math.pi)`` -:param x: 호도법 값 -:return: The value converted to degrees""" + :param x: A value in radians + :return: The value converted to degrees""" ... def exp(x: float) -> float: - """``x``의 지수를 계산합니다. + """Calculate the exponential of ``x``. -Example: ``math.exp(1)`` + Example: ``math.exp(1)`` -:param x: 숫자 -:return: The exponential of ``x``.""" + :param x: A number + :return: The exponential of ``x``. + """ ... def fabs(x: float) -> float: - """``x``의 절댓값을 반환합니다. + """Return the absolute value of ``x``. -Example: ``math.fabs(-0.1)`` + Example: ``math.fabs(-0.1)`` -:param x: 숫자 -:return: The absolute value of ``x``""" + :param x: A number + :return: The absolute value of ``x`` + """ ... def floor(x: float) -> int: - """음의 무한대로 숫자를 반올림합니다. + """Round a number towards negative infinity. -Example: ``math.floor(0.9)`` + Example: ``math.floor(0.9)`` -:param x: 숫자 -:return: ``x`` rounded towards negative infinity.""" + :param x: A number + :return: ``x`` rounded towards negative infinity. + """ ... def fmod(x: float, y: float) -> float: - """``x/y``의 나머지를 계산합니다. + """Calculate the remainder of ``x/y``. -Example: ``math.fmod(10, 3)`` + Example: ``math.fmod(10, 3)`` -:param x: 분자 -:param y: 분모""" + :param x: The numerator + :param y: The denominator + """ ... def frexp(x: float) -> Tuple[float, int]: - """부동 소수점 수를 가수와 지수로 분해합니다. + """Decomposes a floating-point number into its mantissa and exponent. -Example: ``mantissa, exponent = math.frexp(2)`` + Example: ``mantissa, exponent = math.frexp(2)`` -The returned value is the tuple ``(m, e)`` such that ``x == m * 2**e`` -exactly. If ``x == 0`` then the function returns ``(0.0, 0)``, otherwise -the relation ``0.5 <= abs(m) < 1`` holds. + The returned value is the tuple ``(m, e)`` such that ``x == m * 2**e`` + exactly. If ``x == 0`` then the function returns ``(0.0, 0)``, otherwise + the relation ``0.5 <= abs(m) < 1`` holds. -:param x: 부동 소수점 수 -:return: A tuple of length two containing its mantissa then exponent""" + :param x: A floating-point number + :return: A tuple of length two containing its mantissa then exponent + """ ... def isfinite(x: float) -> bool: - """값이 유한값인지 확인합니다. + """Check if a value is finite. -Example: ``math.isfinite(float('inf'))`` + Example: ``math.isfinite(float('inf'))`` -:param x: 숫자입니다. -:return: ``True`` if ``x`` is finite, ``False`` otherwise.""" + :param x: A number. + :return: ``True`` if ``x`` is finite, ``False`` otherwise. + """ ... def isinf(x: float) -> bool: - """값이 무한인지 확인합니다. + """Check if a value is infinite. -Example: ``math.isinf(float('-inf'))`` + Example: ``math.isinf(float('-inf'))`` -:param x: 숫자입니다. -:return: ``True`` if ``x`` is infinite, ``False`` otherwise.""" + :param x: A number. + :return: ``True`` if ``x`` is infinite, ``False`` otherwise. + """ ... def isnan(x: float) -> bool: - """값이 숫자가 아닌 값(NaN)인지 확인합니다. + """Check if a value is not-a-number (NaN). -Example: ``math.isnan(float('nan'))`` + Example: ``math.isnan(float('nan'))`` -:param x: 숫자 -:return: ``True`` if ``x`` is not-a-number (NaN), ``False`` otherwise.""" + :param x: A number + :return: ``True`` if ``x`` is not-a-number (NaN), ``False`` otherwise.""" ... def ldexp(x: float, exp: int) -> float: - """``x * (2**exp)``를 계산합니다. + """Calculate ``x * (2**exp)``. -Example: ``math.ldexp(0.5, 2)`` + Example: ``math.ldexp(0.5, 2)`` -:param x: 숫자 -:param exp: 정수 지수 -:return: ``x * (2**exp)``""" + :param x: A number + :param exp: Integer exponent + :return: ``x * (2**exp)`` + """ ... -def log(x: float, base: float=e) -> float: - """``x``의 로그를 주어진 베이스에 따라 계산합니다(기본값은 자연로그). +def log(x: float, base: float = e) -> float: + """Calculate the logarithm of ``x`` to the given base (defaults to natural logorithm). -Example: ``math.log(math.e)`` + Example: ``math.log(math.e)`` -With one argument, return the natural logarithm of x (to base e). + With one argument, return the natural logarithm of x (to base e). -With two arguments, return the logarithm of x to the given base, calculated as ``log(x)/log(base)``. + With two arguments, return the logarithm of x to the given base, calculated as ``log(x)/log(base)``. -:param x: 숫자 -:param base: 사용할 베이스 -:return: The natural logarithm of ``x``""" + :param x: A number + :param base: The base to use + :return: The natural logarithm of ``x`` + """ ... def modf(x: float) -> Tuple[float, float]: - """``x``의 분수 및 정수 부분을 계산합니다. + """Calculate the fractional and integral parts of ``x``. -Example: ``fractional, integral = math.modf(1.5)`` + Example: ``fractional, integral = math.modf(1.5)`` -:param x: 숫자 -:return: A tuple of two floats representing the fractional then integral parts of ``x``. + :param x: A number + :return: A tuple of two floats representing the fractional then integral parts of ``x``. -Both the fractional and integral values have the same sign as ``x``.""" + Both the fractional and integral values have the same sign as ``x``. + """ ... def pow(x: float, y: float) -> float: - """``y``의 제곱을 ``x``(으)로 반환합니다. + """Returns ``x`` to the power of ``y``. -Example: ``math.pow(4, 0.5)`` + Example: ``math.pow(4, 0.5)`` -:param x: 숫자 -:param y: 지수 -:return: ``x`` to the power of ``y``""" + :param x: A number + :param y: The exponent + :return: ``x`` to the power of ``y`` + """ ... def radians(x: float) -> float: - """각도법을 호도법으로 변환합니다. + """Convert a degrees to radians. -Example: ``math.radians(360)`` + Example: ``math.radians(360)`` -:param x: 각도법 값 -:return: The value converted to radians""" + :param x: A value in degrees + :return: The value converted to radians + """ ... def sin(x: float) -> float: - """``x``의 사인을 계산합니다. + """Calculate the sine of ``x``. -Example: ``math.sin(math.pi/2)`` + Example: ``math.sin(math.pi/2)`` -:param x: 숫자 -:return: The sine of ``x``""" + :param x: A number + :return: The sine of ``x`` + """ ... def sqrt(x: float) -> float: - """``x``의 제곱근을 계산합니다. + """Calculate the square root of ``x``. -Example: ``math.sqrt(4)`` + Example: ``math.sqrt(4)`` -:param x: 숫자 -:return: The square root of ``x``""" + :param x: A number + :return: The square root of ``x`` + """ ... def tan(x: float) -> float: - """``x``의 탄젠트를 계산합니다. + """Calculate the tangent of ``x``. -Example: ``math.tan(0)`` + Example: ``math.tan(0)`` -:param x: 숫자 -:return: The tangent of ``x``.""" + :param x: A number + :return: The tangent of ``x``. + """ ... def trunc(x: float) -> int: - """숫자를 0으로 반올림합니다. + """Round a number towards 0. -Example: ``math.trunc(-0.9)`` + Example: ``math.trunc(-0.9)`` -:param x: 숫자 -:return: ``x`` rounded towards zero.""" + :param x: A number + :return: ``x`` rounded towards zero. + """ ... + e: float -"""자연 알고리즘 베이스""" +"""Base of the natural logarithm""" + pi: float -"""원의 원주와 지름의 비율""" \ No newline at end of file +"""The ratio of a circle's circumference to its diameter""" diff --git a/lang/ko/typeshed/stdlib/microbit/__init__.pyi b/lang/ko/typeshed/stdlib/microbit/__init__.pyi index 1c64b85..f12158f 100644 --- a/lang/ko/typeshed/stdlib/microbit/__init__.pyi +++ b/lang/ko/typeshed/stdlib/microbit/__init__.pyi @@ -1,6 +1,11 @@ -"""핀, 이미지, 소리, 온도 및 음량입니다.""" +"""Pins, images, sounds, temperature and volume. +""" + from typing import Any, Callable, List, Optional, Tuple, Union, overload + from _typeshed import ReadableBuffer + +# V2 only from . import accelerometer as accelerometer from . import audio as audio from . import compass as compass @@ -11,696 +16,831 @@ from . import speaker as speaker from . import spi as spi from . import uart as uart -def run_every(callback: Optional[Callable[[], None]]=None, days: int=0, h: int=0, min: int=0, s: int=0, ms: int=0) -> Callable[[Callable[[], None]], Callable[[], None]]: - """매개 변수로 주어진 일정한 시간(밀리초, ms)마다 특정 함수를 호출합니다. **micro:bit V2 전용** +def run_every( + callback: Optional[Callable[[], None]] = None, + days: int = 0, + h: int = 0, + min: int = 0, + s: int = 0, + ms: int = 0, +) -> Callable[[Callable[[], None]], Callable[[], None]]: + """Schedule to run a function at the interval specified by the time arguments **V2 only**. -Example: ``run_every(my_logging, min=5)`` + Example: ``run_every(my_logging, min=5)`` -``run_every`` can be used in two ways: + ``run_every`` can be used in two ways: -As a Decorator - placed on top of the function to schedule. For example:: + As a Decorator - placed on top of the function to schedule. For example:: - @run_every(h=1, min=20, s=30, ms=50) - def my_function(): - # Do something here + @run_every(h=1, min=20, s=30, ms=50) + def my_function(): + # Do something here -As a Function - passing the callback as a positional argument. For example:: + As a Function - passing the callback as a positional argument. For example:: - def my_function(): - # Do something here - run_every(my_function, s=30) + def my_function(): + # Do something here + run_every(my_function, s=30) -Each argument corresponds to a different time unit and they are additive. -So ``run_every(min=1, s=30)`` schedules the callback every minute and a half. + Each argument corresponds to a different time unit and they are additive. + So ``run_every(min=1, s=30)`` schedules the callback every minute and a half. -When an exception is thrown inside the callback function it deschedules the -function. To avoid this you can catch exceptions with ``try/except``. + When an exception is thrown inside the callback function it deschedules the + function. To avoid this you can catch exceptions with ``try/except``. -:param callback: 주어진 시간이 되었을 때 호출할 함수. 데코레이터(장식자)로 사용할 때 호출. -:param days: 함수 호출 반복 시간의 날 단위를 정합니다. -:param h: 함수 호출 반복 시간의 시간 단위를 정합니다. -:param min: 함수 호출 반복 시간의 분 단위를 정합니다. -:param s: 함수 호출 반복 시간의 초 단위를 정합니다. -:param ms: 함수 호출 반복 시간의 밀리초 단위를 정합니다.""" + :param callback: Function to call at the provided interval. Omit when using as a decorator. + :param days: Sets the day mark for the scheduling. + :param h: Sets the hour mark for the scheduling. + :param min: Sets the minute mark for the scheduling. + :param s: Sets the second mark for the scheduling. + :param ms: Sets the millisecond mark for the scheduling. + """ def panic(n: int) -> None: - """패닉 모드를 활성화합니다. + """Enter a panic mode. -Example: ``panic(127)`` + Example: ``panic(127)`` -:param n: <= 255의 임의 정수로 상태를 표시합니다. + :param n: An arbitrary integer <= 255 to indicate a status. -Requires restart.""" + Requires restart. + """ def reset() -> None: - """보드를 재시작합니다.""" + """Restart the board.""" + @overload def scale(value: float, from_: Tuple[float, float], to: Tuple[int, int]) -> int: """Converts a value from a range to an integer range. -Example: ``volume = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255))`` + Example: ``volume = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255))`` -For example, to convert an accelerometer X value to a speaker volume. + For example, to convert an accelerometer X value to a speaker volume. -If one of the numbers in the ``to`` parameter is a floating point -(i.e a decimal number like ``10.0``), this function will return a -floating point number. + If one of the numbers in the ``to`` parameter is a floating point + (i.e a decimal number like ``10.0``), this function will return a + floating point number. - temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0)) + temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0)) -:param value: A number to convert. -:param from_: 변환할 범위를 정의할 튜플 값 -:param to: A tuple to define the range to convert to. -:return: The ``value`` converted to the ``to`` range.""" + :param value: A number to convert. + :param from_: A tuple to define the range to convert from. + :param to: A tuple to define the range to convert to. + :return: The ``value`` converted to the ``to`` range. + """ @overload def scale(value: float, from_: Tuple[float, float], to: Tuple[float, float]) -> float: """Converts a value from a range to a floating point range. -Example: ``temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0))`` + Example: ``temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0))`` -For example, to convert temperature from a Celsius scale to Fahrenheit. + For example, to convert temperature from a Celsius scale to Fahrenheit. -If one of the numbers in the ``to`` parameter is a floating point -(i.e a decimal number like ``10.0``), this function will return a -floating point number. -If they are both integers (i.e ``10``), it will return an integer:: + If one of the numbers in the ``to`` parameter is a floating point + (i.e a decimal number like ``10.0``), this function will return a + floating point number. + If they are both integers (i.e ``10``), it will return an integer:: - returns_int = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255)) + returns_int = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255)) -:param value: A number to convert. -:param from_: 변환할 범위를 정의할 튜플 값 -:param to: A tuple to define the range to convert to. -:return: The ``value`` converted to the ``to`` range.""" + :param value: A number to convert. + :param from_: A tuple to define the range to convert from. + :param to: A tuple to define the range to convert to. + :return: The ``value`` converted to the ``to`` range. + """ def sleep(n: float) -> None: - """``n``밀리초 동안 대기합니다. + """Wait for ``n`` milliseconds. -Example: ``sleep(1000)`` + Example: ``sleep(1000)`` -:param n: 대기할 밀리초 수 + :param n: The number of milliseconds to wait -One second is 1000 milliseconds, so:: + One second is 1000 milliseconds, so:: - microbit.sleep(1000) + microbit.sleep(1000) -will pause the execution for one second.""" + will pause the execution for one second. + """ def running_time() -> int: - """보드의 실행 시간을 불러옵니다. + """Get the running time of the board. -:return: The number of milliseconds since the board was switched on or restarted.""" + :return: The number of milliseconds since the board was switched on or restarted. + """ def temperature() -> int: - """섭씨로 micro:bit의 온도를 불러옵니다. (온도)""" + """Get the temperature of the micro:bit in degrees Celsius.""" def set_volume(v: int) -> None: - """음량을 설정합니다. + """Sets the volume. -Example: ``set_volume(127)`` + Example: ``set_volume(127)`` -:param v: 0(낮음) 및 255(높음) 사이의 값입니다. + :param v: a value between 0 (low) and 255 (high). -Out of range values will be clamped to 0 or 255. + Out of range values will be clamped to 0 or 255. -**V2** only.""" + **V2** only. + """ ... class Button: - """``button_a`` 및 ``button_b`` 버튼 클래스입니다.""" + """The class for the buttons ``button_a`` and ``button_b``.""" def is_pressed(self) -> bool: - """해당 버튼이 눌렸는지 확인합니다. + """Check if the button is pressed. -:return: ``True`` if the specified button ``button`` is pressed, and ``False`` otherwise.""" + :return: ``True`` if the specified button ``button`` is pressed, and ``False`` otherwise. + """ ... - def was_pressed(self) -> bool: - """장치가 시작한 후 또는 이 메서드가 호출된 후 해당 버튼이 눌렸는지 확인합니다. + """Check if the button was pressed since the device started or the last time this method was called. -Calling this method will clear the press state so -that the button must be pressed again before this method will return -``True`` again. + Calling this method will clear the press state so + that the button must be pressed again before this method will return + ``True`` again. -:return: ``True`` if the specified button ``button`` was pressed, and ``False`` otherwise""" + :return: ``True`` if the specified button ``button`` was pressed, and ``False`` otherwise + """ ... - def get_presses(self) -> int: - """버튼이 눌린 총 횟수를 불러오고, 총값을 반환하기 전 초기화합니다. + """Get the running total of button presses, and resets this total + to zero before returning. -:return: The number of presses since the device started or the last time this method was called""" + :return: The number of presses since the device started or the last time this method was called + """ ... + button_a: Button -"""왼쪽 버튼 ``Button`` 개체입니다.""" +"""The left button ``Button`` object.""" + button_b: Button -"""오른쪽 버튼 ``Button`` 개체입니다.""" +"""The right button ``Button`` object.""" class MicroBitDigitalPin: - """디지털 핀입니다. + """A digital pin. + + Some pins support analog and touch features using the ``MicroBitAnalogDigitalPin`` and ``MicroBitTouchPin`` subclasses. + """ -Some pins support analog and touch features using the ``MicroBitAnalogDigitalPin`` and ``MicroBitTouchPin`` subclasses.""" NO_PULL: int PULL_UP: int PULL_DOWN: int - def read_digital(self) -> int: - """핀의 디지털 값을 불러옵니다. + """Get the digital value of the pin. -Example: ``value = pin0.read_digital()`` + Example: ``value = pin0.read_digital()`` -:return: 1 if the pin is high, and 0 if it's low.""" + :return: 1 if the pin is high, and 0 if it's low. + """ ... - def write_digital(self, value: int) -> None: - """핀의 디지털 값을 설정합니다. + """Set the digital value of the pin. -Example: ``pin0.write_digital(1)`` + Example: ``pin0.write_digital(1)`` -:param value: 핀을 하이로 설정하려면 1, 로우로 설정하려면 0""" + :param value: 1 to set the pin high or 0 to set the pin low""" ... - def set_pull(self, value: int) -> None: - """다음 중 하나의 값으로 풀 상태를 설정: ``PULL_UP``, ``PULL_DOWN`` 또는 ``NO_PULL`` + """Set the pull state to one of three possible values: ``PULL_UP``, ``PULL_DOWN`` or ``NO_PULL``. -Example: ``pin0.set_pull(pin0.PULL_UP)`` + Example: ``pin0.set_pull(pin0.PULL_UP)`` -:param value: 관련 핀의 풀 상태입니다. (예: ``pin0.PULL_UP``)""" + :param value: The pull state from the relevant pin, e.g. ``pin0.PULL_UP``. + """ ... - def get_pull(self) -> int: - """핀의 풀 상태를 불러옵니다. + """Get the pull state on a pin. -Example: ``pin0.get_pull()`` + Example: ``pin0.get_pull()`` -:return: ``NO_PULL``, ``PULL_DOWN``, or ``PULL_UP`` + :return: ``NO_PULL``, ``PULL_DOWN``, or ``PULL_UP`` -These are set using the ``set_pull()`` method or automatically configured -when a pin mode requires it.""" + These are set using the ``set_pull()`` method or automatically configured + when a pin mode requires it. + """ ... - def get_mode(self) -> str: - """핀 모드를 반환합니다. + """Returns the pin mode. -Example: ``pin0.get_mode()`` + Example: ``pin0.get_mode()`` -When a pin is used for a specific function, like -writing a digital value, or reading an analog value, the pin mode -changes. + When a pin is used for a specific function, like + writing a digital value, or reading an analog value, the pin mode + changes. -:return: ``"unused"``, ``"analog"``, ``"read_digital"``, ``"write_digital"``, ``"display"``, ``"button"``, ``"music"``, ``"audio"``, ``"touch"``, ``"i2c"``, or ``"spi"``""" + :return: ``"unused"``, ``"analog"``, ``"read_digital"``, ``"write_digital"``, ``"display"``, ``"button"``, ``"music"``, ``"audio"``, ``"touch"``, ``"i2c"``, or ``"spi"`` + """ ... - def write_analog(self, value: int) -> None: - """핀의 PWM 신호를 출력하고 ``value``와(과) 비례해 듀티 사이클을 설정합니다. - -Example: ``pin0.write_analog(254)`` + """Output a PWM signal on the pin, with the duty cycle proportional to ``value``. -:param value: 0(0% 듀티 사이클) 및 1023(100% 듀티) 사이의 정수 또는 부동 소수점 수입니다.""" + Example: ``pin0.write_analog(254)`` + :param value: An integer or a floating point number between 0 (0% duty cycle) and 1023 (100% duty). + """ def set_analog_period(self, period: int) -> None: - """PWM 신호가 출력되는 주기를 ``period``밀리초로 설정합니다. + """Set the period of the PWM signal being output to ``period`` in milliseconds. -Example: ``pin0.set_analog_period(10)`` - -:param period: 유효한 최소값이 1ms인 밀리초 주기입니다.""" + Example: ``pin0.set_analog_period(10)`` + :param period: The period in milliseconds with a minimum valid value of 1ms. + """ def set_analog_period_microseconds(self, period: int) -> None: - """PWM 신호가 출력되는 주기를 ``period``마이크로초로 설정합니다. + """Set the period of the PWM signal being output to ``period`` in microseconds. -Example: ``pin0.set_analog_period_microseconds(512)`` + Example: ``pin0.set_analog_period_microseconds(512)`` -:param period: 유효한 최소값이 256µs인 마이크로초 주기입니다.""" + :param period: The period in microseconds with a minimum valid value of 256µs. + """ class MicroBitAnalogDigitalPin(MicroBitDigitalPin): - """아날로그 및 디지털 기능이 있는 핀입니다.""" + """A pin with analog and digital features.""" def read_analog(self) -> int: - """핀에 적용된 전압을 읽습니다. + """Read the voltage applied to the pin. -Example: ``pin0.read_analog()`` + Example: ``pin0.read_analog()`` -:return: An integer between 0 (meaning 0V) and 1023 (meaning 3.3V).""" + :return: An integer between 0 (meaning 0V) and 1023 (meaning 3.3V). + """ class MicroBitTouchPin(MicroBitAnalogDigitalPin): - """아날로그, 디지털, 터치 기능이 있는 핀입니다.""" + """A pin with analog, digital and touch features.""" + CAPACITIVE: int RESISTIVE: int - def is_touched(self) -> bool: - """핀이 접촉 상태인지 확인합니다. + """Check if the pin is being touched. -Example: ``pin0.is_touched()`` + Example: ``pin0.is_touched()`` -The default touch mode for the pins on the edge connector is ``resistive``. -The default for the logo pin **V2** is ``capacitive``. + The default touch mode for the pins on the edge connector is ``resistive``. + The default for the logo pin **V2** is ``capacitive``. -**Resistive touch** -This test is done by measuring how much resistance there is between the -pin and ground. A low resistance gives a reading of ``True``. To get -a reliable reading using a finger you may need to touch the ground pin -with another part of your body, for example your other hand. + **Resistive touch** + This test is done by measuring how much resistance there is between the + pin and ground. A low resistance gives a reading of ``True``. To get + a reliable reading using a finger you may need to touch the ground pin + with another part of your body, for example your other hand. -**Capacitive touch** -This test is done by interacting with the electric field of a capacitor -using a finger as a conductor. `Capacitive touch -`_ -does not require you to make a ground connection as part of a circuit. + **Capacitive touch** + This test is done by interacting with the electric field of a capacitor + using a finger as a conductor. `Capacitive touch + `_ + does not require you to make a ground connection as part of a circuit. -:return: ``True`` if the pin is being touched with a finger, otherwise return ``False``.""" + :return: ``True`` if the pin is being touched with a finger, otherwise return ``False``. + """ ... - def set_touch_mode(self, value: int) -> None: - """핀의 터치 모드를 설정합니다. + """Set the touch mode for the pin. -Example: ``pin0.set_touch_mode(pin0.CAPACITIVE)`` + Example: ``pin0.set_touch_mode(pin0.CAPACITIVE)`` -The default touch mode for the pins on the edge connector is -``resistive``. The default for the logo pin **V2** is ``capacitive``. + The default touch mode for the pins on the edge connector is + ``resistive``. The default for the logo pin **V2** is ``capacitive``. -:param value: 관련 핀의 ``CAPACITIVE`` 또는 ``RESISTIVE``입니다.""" + :param value: ``CAPACITIVE`` or ``RESISTIVE`` from the relevant pin. + """ ... + pin0: MicroBitTouchPin -"""디지털 및 아날로그, 터치 기능이 있는 핀입니다.""" +"""Pin with digital, analog and touch features.""" + pin1: MicroBitTouchPin -"""디지털 및 아날로그, 터치 기능이 있는 핀입니다.""" +"""Pin with digital, analog and touch features.""" + pin2: MicroBitTouchPin -"""디지털 및 아날로그, 터치 기능이 있는 핀입니다.""" +"""Pin with digital, analog and touch features.""" + pin3: MicroBitAnalogDigitalPin -"""디지털 및 아날로그 기능이 있는 핀입니다.""" +"""Pin with digital and analog features.""" + pin4: MicroBitAnalogDigitalPin -"""디지털 및 아날로그 기능이 있는 핀입니다.""" +"""Pin with digital and analog features.""" + pin5: MicroBitDigitalPin -"""디지털 기능이 있는 핀입니다. (pin speaker)""" +"""Pin with digital features.""" + pin6: MicroBitDigitalPin -"""디지털 기능이 있는 핀입니다.""" +"""Pin with digital features.""" + pin7: MicroBitDigitalPin -"""디지털 기능이 있는 핀입니다.""" +"""Pin with digital features.""" + pin8: MicroBitDigitalPin -"""디지털 기능이 있는 핀입니다.""" +"""Pin with digital features.""" + pin9: MicroBitDigitalPin -"""디지털 기능이 있는 핀입니다.""" +"""Pin with digital features.""" + pin10: MicroBitAnalogDigitalPin -"""디지털 및 아날로그 기능이 있는 핀입니다.""" +"""Pin with digital and analog features.""" + pin11: MicroBitDigitalPin -"""디지털 기능이 있는 핀입니다.""" +"""Pin with digital features.""" + pin12: MicroBitDigitalPin -"""디지털 기능이 있는 핀입니다.""" +"""Pin with digital features.""" + pin13: MicroBitDigitalPin -"""디지털 기능이 있는 핀입니다.""" +"""Pin with digital features.""" + pin14: MicroBitDigitalPin -"""디지털 기능이 있는 핀입니다.""" +"""Pin with digital features.""" + pin15: MicroBitDigitalPin -"""디지털 기능이 있는 핀입니다.""" +"""Pin with digital features.""" + pin16: MicroBitDigitalPin -"""디지털 기능이 있는 핀입니다.""" +"""Pin with digital features.""" + pin19: MicroBitDigitalPin -"""디지털 기능이 있는 핀입니다.""" +"""Pin with digital features.""" + pin20: MicroBitDigitalPin -"""디지털 기능이 있는 핀입니다.""" +"""Pin with digital features.""" + pin_logo: MicroBitTouchPin -"""micro:bit 전면의 터치 감지 로고 핀으로, 기본값은 정전식 터치 모드입니다. (핀 로고)""" +"""A touch sensitive logo pin on the front of the micro:bit, which by default is set to capacitive touch mode.""" + pin_speaker: MicroBitAnalogDigitalPin -"""micro:bit 스피커를 처리하는 핀입니다. (핀 스피커) +"""A pin to address the micro:bit speaker. This API is intended only for use in Pulse-Width Modulation pin operations e.g. pin_speaker.write_analog(128). """ class Image: - """micro:bit LED 디스플레이에 표시할 이미지입니다. + """An image to show on the micro:bit LED display. -Given an image object it's possible to display it via the ``display`` API:: + Given an image object it's possible to display it via the ``display`` API:: + + display.show(Image.HAPPY) + """ - display.show(Image.HAPPY)""" HEART: Image - """하트 이미지입니다.""" + """Heart image.""" + HEART_SMALL: Image - """작은 하트 이미지입니다.""" + """Small heart image.""" + HAPPY: Image - """행복한 얼굴 이미지입니다.""" + """Happy face image.""" + SMILE: Image - """미소 짓는 얼굴 이미지입니다.""" + """Smiling mouth image.""" + SAD: Image - """슬픈 얼굴 이미지입니다.""" + """Sad face image.""" + CONFUSED: Image - """혼란스러운 얼굴 이미지입니다.""" + """Confused face image.""" + ANGRY: Image - """화난 얼굴 이미지입니다.""" + """Angry face image.""" + ASLEEP: Image - """자는 얼굴 이미지입니다.""" + """Sleeping face image.""" + SURPRISED: Image - """놀란 얼굴 이미지입니다.""" + """Surprised face image.""" + SILLY: Image - """우스꽝스러운 얼굴 이미지입니다.""" + """Silly face image.""" + FABULOUS: Image - """선글라스를 쓴 얼굴 이미지입니다.""" + """Sunglasses face image.""" + MEH: Image - """지루한 얼굴 이미지입니다.""" + """Unimpressed face image.""" + YES: Image - """체크 표시 이미지입니다.""" + """Tick image.""" + NO: Image - """엑스 표시 이미지입니다.""" + """Cross image.""" + CLOCK12: Image - """12시 정각을 가리키는 이미지입니다.""" + """Image with line pointing to 12 o'clock.""" + CLOCK11: Image - """11시 정각을 가리키는 이미지입니다.""" + """Image with line pointing to 11 o'clock.""" + CLOCK10: Image - """10시 정각을 가리키는 이미지입니다.""" + """Image with line pointing to 10 o'clock.""" + CLOCK9: Image - """9시 정각을 가리키는 이미지입니다.""" + """Image with line pointing to 9 o'clock.""" + CLOCK8: Image - """8시 정각을 가리키는 이미지입니다.""" + """Image with line pointing to 8 o'clock.""" + CLOCK7: Image - """7시 정각을 가리키는 이미지입니다.""" + """Image with line pointing to 7 o'clock.""" + CLOCK6: Image - """6시 정각을 가리키는 이미지입니다.""" + """Image with line pointing to 6 o'clock.""" + CLOCK5: Image - """5시 정각을 가리키는 이미지입니다.""" + """Image with line pointing to 5 o'clock.""" + CLOCK4: Image - """4시 정각을 가리키는 이미지입니다.""" + """Image with line pointing to 4 o'clock.""" + CLOCK3: Image - """3시 정각을 가리키는 이미지입니다.""" + """Image with line pointing to 3 o'clock.""" + CLOCK2: Image - """2시 정각을 가리키는 이미지입니다.""" + """Image with line pointing to 2 o'clock.""" + CLOCK1: Image - """1시 정각을 가리키는 이미지입니다.""" + """Image with line pointing to 1 o'clock.""" + ARROW_N: Image - """북쪽을 가리키는 화살표 이미지입니다.""" + """Image of arrow pointing north.""" + ARROW_NE: Image - """북동쪽을 가리키는 화살표 이미지입니다.""" + """Image of arrow pointing north east.""" + ARROW_E: Image - """동쪽을 가리키는 화살표 이미지입니다.""" + """Image of arrow pointing east.""" + ARROW_SE: Image - """남동쪽을 가리키는 화살표 이미지입니다.""" + """Image of arrow pointing south east.""" + ARROW_S: Image - """남쪽을 가리키는 화살표 이미지입니다.""" + """Image of arrow pointing south.""" + ARROW_SW: Image - """남서쪽을 가리키는 화살표 이미지입니다.""" + """Image of arrow pointing south west.""" + ARROW_W: Image - """서쪽을 가리키는 화살표 이미지입니다.""" + """Image of arrow pointing west.""" + ARROW_NW: Image - """북서쪽을 가리키는 화살표 이미지입니다.""" + """Image of arrow pointing north west.""" + TRIANGLE: Image - """위쪽을 가리키는 삼각형 이미지입니다.""" + """Image of a triangle pointing up.""" + TRIANGLE_LEFT: Image - """왼쪽 구석의 삼각형 이미지입니다.""" + """Image of a triangle in the left corner.""" + CHESSBOARD: Image - """체스판 패턴으로 깜빡이는 LED 불빛입니다.""" + """Alternate LEDs lit in a chessboard pattern.""" + DIAMOND: Image - """다이아몬드 이미지입니다.""" + """Diamond image.""" + DIAMOND_SMALL: Image - """작은 다이아몬드 이미지입니다.""" + """Small diamond image.""" + SQUARE: Image - """사각형 이미지입니다.""" + """Square image.""" + SQUARE_SMALL: Image - """작은 사각형 이미지입니다.""" + """Small square image.""" + RABBIT: Image - """토끼 이미지입니다.""" + """Rabbit image.""" + COW: Image - """소 이미지입니다.""" + """Cow image.""" + MUSIC_CROTCHET: Image - """사분음표 이미지입니다.""" + """Crotchet note image.""" + MUSIC_QUAVER: Image - """팔분음표 이미지입니다.""" + """Quaver note image.""" + MUSIC_QUAVERS: Image - """두 개의 팔분음표 이미지입니다.""" + """Pair of quavers note image.""" + PITCHFORK: Image - """쇠스랑 이미지입니다.""" + """Pitchfork image.""" + XMAS: Image - """크리스마스 나무 이미지입니다.""" + """Christmas tree image.""" + PACMAN: Image - """오락실 캐릭터 Pac-Man 이미지입니다.""" + """Pac-Man arcade character image.""" + TARGET: Image - """표적 이미지입니다.""" + """Target image.""" + TSHIRT: Image - """티셔츠 이미지입니다.""" + """T-shirt image.""" + ROLLERSKATE: Image - """롤러스케이트 이미지입니다.""" + """Rollerskate image.""" + DUCK: Image - """오리 이미지입니다.""" + """Duck image.""" + HOUSE: Image - """집 이미지입니다.""" + """House image.""" + TORTOISE: Image - """거북이 이미지입니다.""" + """Tortoise image.""" + BUTTERFLY: Image - """나비 이미지입니다.""" + """Butterfly image.""" + STICKFIGURE: Image - """막대인간 이미지입니다.""" + """Stick figure image.""" + GHOST: Image - """유령 이미지입니다.""" + """Ghost image.""" + SWORD: Image - """칼 이미지입니다.""" + """Sword image.""" + GIRAFFE: Image - """기린 이미지입니다.""" + """Giraffe image.""" + SKULL: Image - """해골 이미지입니다.""" + """Skull image.""" + UMBRELLA: Image - """우산 이미지입니다.""" + """Umbrella image.""" + SNAKE: Image - """뱀 이미지입니다.""" + """Snake image.""" + SCISSORS: Image """Scissors image.""" + ALL_CLOCKS: List[Image] - """모든 CLOCK_ 이미지를 순서대로 나열한 리스트입니다.""" - ALL_ARROWS: List[Image] - """모든 ARROW_ 이미지를 순서대로 나열한 리스트입니다.""" + """A list containing all the CLOCK_ images in sequence.""" + ALL_ARROWS: List[Image] + """A list containing all the ARROW_ images in sequence.""" @overload def __init__(self, string: str) -> None: - """어떤 LED가 켜져있는지 설명하는 문자열로부터 이미지를 생성합니다. (string) + """Create an image from a string describing which LEDs are lit. -``string`` has to consist of digits 0-9 arranged into lines, -describing the image, for example:: + ``string`` has to consist of digits 0-9 arranged into lines, + describing the image, for example:: - image = Image("90009:" - "09090:" - "00900:" - "09090:" - "90009") + 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 newlines (\\n) insead of the colons. + 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 newlines (\\n) insead of the colons. -:param string: 이미지를 설명하는 문자열입니다.""" + :param string: The string describing the image. + """ ... - @overload - def __init__(self, width: int=5, height: int=5, buffer: ReadableBuffer=None) -> None: - """``width`` 열과 ``height`` 행의 비어있는 이미지를 생성합니다. + def __init__( + self, width: int = 5, height: int = 5, buffer: ReadableBuffer = None + ) -> None: + """Create an empty image with ``width`` columns and ``height`` rows. -:param width: 이미지 너비(선택 사항) -:param height: 이미지 높이(선택 사항) -:param buffer: 0~9의 범위에 속하는 정수로 구성된 ``width``x``height`` 배열 또는 바이트(선택 사항) + :param width: Optional width of the image + :param height: Optional height of the image + :param buffer: Optional array or bytes of ``width``×``height`` integers in range 0-9 to initialize the image -Examples:: + Examples:: - Image(2, 2, b'\x08\x08\x08\x08') - Image(2, 2, bytearray([9,9,9,9])) + Image(2, 2, b'\x08\x08\x08\x08') + Image(2, 2, bytearray([9,9,9,9])) -These create 2 x 2 pixel images at full brightness.""" + These create 2 x 2 pixel images at full brightness. + """ ... - def width(self) -> int: - """열의 수를 불러옵니다. + """Get the number of columns. -:return: The number of columns in the image""" + :return: The number of columns in the image + """ ... - def height(self) -> int: - """행의 수를 불러옵니다. + """Get the number of rows. -:return: The number of rows in the image""" + :return: The number of rows in the image + """ ... - def set_pixel(self, x: int, y: int, value: int) -> None: - """픽셀의 밝기를 설정합니다. + """Set the brightness of a pixel. -Example: ``my_image.set_pixel(0, 0, 9)`` + Example: ``my_image.set_pixel(0, 0, 9)`` -:param x: 열 번호 -:param y: 행 번호 -:param value: 0(어두움)과 9(밝음) 사이의 정수로 밝기를 설정합니다. + :param x: The column number + :param y: The row number + :param value: The brightness as an integer 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``.""" + 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: - """픽셀의 밝기를 불러옵니다. + """Get the brightness of a pixel. -Example: ``my_image.get_pixel(0, 0)`` + Example: ``my_image.get_pixel(0, 0)`` -:param x: 열 번호 -:param y: 행 번호 -:return: The brightness as an integer between 0 and 9.""" + :param x: The column number + :param y: The row number + :return: The brightness as an integer between 0 and 9. + """ ... - def shift_left(self, n: int) -> Image: - """사진을 왼쪽으로 옮겨 새로운 이미지를 생성합니다. + """Create a new image by shifting the picture left. -Example: ``Image.HEART_SMALL.shift_left(1)`` + Example: ``Image.HEART_SMALL.shift_left(1)`` -:param n: 옮길 열의 수 -:return: The shifted image""" + :param n: The number of columns to shift by + :return: The shifted image + """ ... - def shift_right(self, n: int) -> Image: - """사진을 오른쪽으로 옮겨 새로운 이미지를 생성합니다. + """Create a new image by shifting the picture right. -Example: ``Image.HEART_SMALL.shift_right(1)`` + Example: ``Image.HEART_SMALL.shift_right(1)`` -:param n: 옮길 열의 수 -:return: The shifted image""" + :param n: The number of columns to shift by + :return: The shifted image + """ ... - def shift_up(self, n: int) -> Image: - """사진을 위로 옮겨 새로운 이미지를 생성합니다. + """Create a new image by shifting the picture up. -Example: ``Image.HEART_SMALL.shift_up(1)`` + Example: ``Image.HEART_SMALL.shift_up(1)`` -:param n: 옮길 행의 수 -:return: The shifted image""" + :param n: The number of rows to shift by + :return: The shifted image + """ ... - def shift_down(self, n: int) -> Image: - """사진을 아래로 옮겨 새로운 이미지를 생성합니다. + """Create a new image by shifting the picture down. -Example: ``Image.HEART_SMALL.shift_down(1)`` + Example: ``Image.HEART_SMALL.shift_down(1)`` -:param n: 옮길 행의 수 -:return: The shifted image""" + :param n: The number of rows to shift by + :return: The shifted image + """ ... - def crop(self, x: int, y: int, w: int, h: int) -> Image: - """사진을 잘라 내 새로운 이미지를 생성합니다. + """Create a new image by cropping the picture. -Example: ``Image.HEART.crop(1, 1, 3, 3)`` + Example: ``Image.HEART.crop(1, 1, 3, 3)`` -:param x: 자르기 오프셋 열 -:param y: 자르기 오프셋 행 -:param w: 자르기 너비 -:param h: 자르기 높이 -:return: The new image""" + :param x: The crop offset column + :param y: The crop offset row + :param w: The crop width + :param h: The crop height + :return: The new image + """ ... - def copy(self) -> Image: - """이미지와 동일한 사본을 생성합니다. + """Create an exact copy of the image. -Example: ``Image.HEART.copy()`` + Example: ``Image.HEART.copy()`` -:return: The new image""" + :return: The new image + """ ... - def invert(self) -> Image: - """소스 이미지에 있는 픽셀을 밝기를 반전해 새로운 이미지를 생성합니다. + """Create a new image by inverting the brightness of the pixels in the + source image. -Example: ``Image.SMALL_HEART.invert()`` + Example: ``Image.SMALL_HEART.invert()`` -:return: The new image.""" + :return: The new image. + """ ... - def fill(self, value: int) -> None: - """이미지의 모든 픽셀의 밝기를 설정합니다. + """Set the brightness of all the pixels in the image. -Example: ``my_image.fill(5)`` + Example: ``my_image.fill(5)`` -:param value: 새로운 밝기를 0(어두움)과 9(밝기) 사이로 설정합니다. + :param value: The new brightness as a number 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``.""" + 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: - """다른 이미지로부터 영역을 복사해 이 이미지로 가져옵니다. - -Example: ``my_image.blit(Image.HEART, 1, 1, 3, 3, 1, 1)`` - -:param src: 소스 이미지 -:param x: 소스 이미지 내 시작 열 오프셋 -:param y: 소스 이미지 내 시작 행 오프셋 -:param w: 복사할 열의 수 -:param h: 복사할 행 번호 -:param xdest: 이 이미지에서 수정할 열의 오프셋 -:param ydest: 이 이미지에서 수정할 행의 오프셋 - -Pixels outside the source image are treated as having a brightness 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 blit( + self, + src: Image, + x: int, + y: int, + w: int, + h: int, + xdest: int = 0, + ydest: int = 0, + ) -> None: + """Copy an area from another image into this image. + + Example: ``my_image.blit(Image.HEART, 1, 1, 3, 3, 1, 1)`` + + :param src: The source image + :param x: The starting column offset in the source image + :param y: The starting row offset in the source image + :param w: The number of columns to copy + :param h: The number of rows to copy + :param xdest: The column offset to modify in this image + :param ydest: The row offset to modify in this image + + Pixels outside the source image are treated as having a brightness 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. -Example: ``Image.HEART + Image.HAPPY`` + Example: ``Image.HEART + Image.HAPPY`` -:param other: 더할 이미지입니다.""" + :param other: The image to add. + """ ... - def __sub__(self, other: Image) -> Image: - """두 이미지의 각 픽셀의 밝기 값을 빼 새로운 이미지를 생성합니다. + """Create a new image by subtracting the brightness values of the + other image from this image. -Example: ``Image.HEART - Image.HEART_SMALL`` + Example: ``Image.HEART - Image.HEART_SMALL`` -:param other: 뺄 이미지입니다.""" + :param other: The image to subtract. + """ ... - def __mul__(self, n: float) -> Image: - """각 픽셀의 밝기 값을 ``n``만큼 곱해 새로운 이미지를 생성합니다. + """Create a new image by multiplying the brightness of each pixel by + ``n``. -Example: ``Image.HEART * 0.5`` + Example: ``Image.HEART * 0.5`` -:param n: 곱할 값입니다.""" + :param n: The value to multiply by. + """ ... - def __truediv__(self, n: float) -> Image: - """각 픽셀의 밝기 값을 ``n``만큼 나누어 새로운 이미지를 생성합니다. + """Create a new image by dividing the brightness of each pixel by + ``n``. -Example: ``Image.HEART / 2`` + Example: ``Image.HEART / 2`` -:param n: 나눌 값입니다.""" + :param n: The value to divide by. + """ ... class SoundEvent: LOUD: SoundEvent - """``quiet``에서 박수 또는 함성 등 ``loud``로 소리 이벤트의 변화를 나타냅니다.""" + """Represents the transition of sound events, from ``quiet`` to ``loud`` like clapping or shouting.""" + QUIET: SoundEvent - """``loud``에서 말소리 또는 배경 음악 등 ``quiet``로 소리 이벤트의 변화를 나타냅니다.""" + """Represents the transition of sound events, from ``loud`` to ``quiet`` like speaking or background music.""" class Sound: - """``audio.play(Sound.NAME)``을 사용해 내장된 소리를 호출합니다.""" + """The built-in sounds can be called using ``audio.play(Sound.NAME)``.""" + GIGGLE: Sound - """웃는 소리입니다.""" + """Giggling sound.""" + HAPPY: Sound - """행복해하는 소리입니다.""" + """Happy sound.""" + HELLO: Sound - """인사 소리입니다.""" + """Greeting sound.""" + MYSTERIOUS: Sound - """신비한 소리입니다.""" + """Mysterious sound.""" + SAD: Sound - """슬퍼하는 소리입니다.""" + """Sad sound.""" + SLIDE: Sound - """슬라이드 소리입니다.""" + """Sliding sound.""" + SOARING: Sound - """솟아오르는 소리입니다.""" + """Soaring sound.""" + SPRING: Sound - """스프링 소리입니다.""" + """Spring sound.""" + TWINKLE: Sound - """반짝이는 소리입니다.""" + """Twinkling sound.""" + YAWN: Sound - """하품 소리입니다.""" \ No newline at end of file + """Yawning sound.""" diff --git a/lang/ko/typeshed/stdlib/microbit/accelerometer.pyi b/lang/ko/typeshed/stdlib/microbit/accelerometer.pyi index c57cd04..bac82c0 100644 --- a/lang/ko/typeshed/stdlib/microbit/accelerometer.pyi +++ b/lang/ko/typeshed/stdlib/microbit/accelerometer.pyi @@ -1,103 +1,115 @@ -"""micro:bit의 가속도를 측정하고 제스쳐를 인식합니다.""" +"""Measure the acceleration of the micro:bit and recognise gestures. +""" + from typing import Tuple def get_x() -> int: - """``x`` 축의 가속도 측정값을 milli-g로 불러옵니다. + """Get the acceleration measurement in the ``x`` axis in milli-g. -Example: ``accelerometer.get_x()`` + Example: ``accelerometer.get_x()`` -:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" + :return: A positive or negative integer depending on direction in the range +/- 2000mg. + """ ... def get_y() -> int: - """``y`` 축의 가속도 측정값을 milli-g로 불러옵니다. + """Get the acceleration measurement in the ``y`` axis in milli-g. -Example: ``accelerometer.get_y()`` + Example: ``accelerometer.get_y()`` -:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" + :return: A positive or negative integer depending on direction in the range +/- 2000mg. + """ ... def get_z() -> int: - """``z`` 축의 가속도 측정값을 milli-g로 불러옵니다. + """Get the acceleration measurement in the ``z`` axis in milli-g. -Example: ``accelerometer.get_z()`` + Example: ``accelerometer.get_z()`` -:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" + :return: A positive or negative integer depending on direction in the range +/- 2000mg. + """ ... def get_values() -> Tuple[int, int, int]: - """한 번에 모든 축의 가속도 측정값을 튜플로 불러옵니다. + """Get the acceleration measurements in all axes at once as a tuple. -Example: ``x, y, z = accelerometer.get_values()`` + Example: ``x, y, z = accelerometer.get_values()`` -:return: a three-element tuple of integers ordered as X, Y, Z, each value a positive or negative integer depending on direction in the range +/- 2000mg""" + :return: a three-element tuple of integers ordered as X, Y, Z, each value a positive or negative integer depending on direction in the range +/- 2000mg + """ ... def get_strength() -> int: """Get the acceleration measurement of all axes combined, as a positive integer. This is the Pythagorean sum of the X, Y and Z axes. -Example: ``accelerometer.get_strength()`` + Example: ``accelerometer.get_strength()`` -:return: The combined acceleration strength of all the axes, in milli-g.""" + :return: The combined acceleration strength of all the axes, in milli-g. + """ ... def current_gesture() -> str: - """현재 제스처의 이름을 불러옵니다. + """Get the name of the current gesture. -Example: ``accelerometer.current_gesture()`` + Example: ``accelerometer.current_gesture()`` -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. + 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. -:return: The current gesture""" + :return: The current gesture + """ ... def is_gesture(name: str) -> bool: - """해당 이름의 제스처가 현재 활성화 상태인지 확인합니다. + """Check if the named gesture is currently active. -Example: ``accelerometer.is_gesture('shake')`` + Example: ``accelerometer.is_gesture('shake')`` -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. + 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. -:param name: 제스쳐 이름. -:return: ``True`` if the gesture is active, ``False`` otherwise.""" + :param name: The gesture name. + :return: ``True`` if the gesture is active, ``False`` otherwise. + """ ... def was_gesture(name: str) -> bool: - """해당 이름의 제스처가 마지막 호출 이후로 활성화된 적이 있는지 확인합니다. + """Check if the named gesture was active since the last call. -Example: ``accelerometer.was_gesture('shake')`` + Example: ``accelerometer.was_gesture('shake')`` -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. + 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. -:param name: 제스처 이름입니다. -:return: ``True`` if the gesture was active since the last call, ``False`` otherwise.""" + :param name: The gesture name. + :return: ``True`` if the gesture was active since the last call, ``False`` otherwise. + """ def get_gestures() -> Tuple[str, ...]: - """제스처 기록의 튜플을 반환합니다. + """Return a tuple of the gesture history. -Example: ``accelerometer.get_gestures()`` + Example: ``accelerometer.get_gestures()`` -Clears the gesture history before returning. + Clears the gesture history before returning. -Gestures are not updated in the background so there needs to be constant -calls to some accelerometer method to do the gesture detection. Usually -gestures can be detected using a loop with a small :func:`microbit.sleep` delay. + Gestures are not updated in the background so there needs to be constant + calls to some accelerometer method to do the gesture detection. Usually + gestures can be detected using a loop with a small :func:`microbit.sleep` delay. -:return: The history as a tuple, most recent last.""" + :return: The history as a tuple, most recent last. + """ ... def set_range(value: int) -> None: """Set the accelerometer sensitivity range, in g (standard gravity), to the closest values supported by the hardware, so it rounds to either ``2``, ``4``, or ``8`` g. -Example: ``accelerometer.set_range(8)`` + Example: ``accelerometer.set_range(8)`` -:param value: New range for the accelerometer, an integer in ``g``.""" \ No newline at end of file + :param value: New range for the accelerometer, an integer in ``g``. + """ diff --git a/lang/ko/typeshed/stdlib/microbit/audio.pyi b/lang/ko/typeshed/stdlib/microbit/audio.pyi index e14bf7e..3b1e327 100644 --- a/lang/ko/typeshed/stdlib/microbit/audio.pyi +++ b/lang/ko/typeshed/stdlib/microbit/audio.pyi @@ -1,123 +1,160 @@ -"""micro:bit을 활용해 소리를 재생합니다(V1 호환을 위해서는 ``audio``를 가져오세요).""" +"""Play sounds using the micro:bit (import ``audio`` for V1 compatibility). +""" + from ..microbit import MicroBitDigitalPin, Sound, pin0 from typing import ClassVar, Iterable, Union -def play(source: Union[Iterable[AudioFrame], Sound, SoundEffect], wait: bool=True, pin: MicroBitDigitalPin=pin0, return_pin: Union[MicroBitDigitalPin, None]=None) -> None: +def play( + source: Union[Iterable[AudioFrame], Sound, SoundEffect], + wait: bool = True, + pin: MicroBitDigitalPin = pin0, + return_pin: Union[MicroBitDigitalPin, None] = None, +) -> None: """Play a built-in sound, sound effect or custom audio frames. -Example: ``audio.play(Sound.GIGGLE)`` + Example: ``audio.play(Sound.GIGGLE)`` -:param source: A built-in ``Sound`` such as ``Sound.GIGGLE``, a ``SoundEffect`` or sample data as an iterable of ``AudioFrame`` objects. -:param wait: ``wait``이 ``True``인 경우 사운드 재생이 완료될 때까지 이 함수가 차단됩니다. -:param pin: (핀) ``pin0``의 기본값을 덮어쓰는 데 사용할 출력 핀을 특정하는 인자입니다(선택 사항). 사운드를 재생하고 싶지 않다면 ``pin=None``을 사용할 수 있습니다. -:param return_pin: 접지 대신 외부 스피커에 연결할 차동 엣지 커넥터 핀을 특정합니다. **V2** 수정 버전에서는 무시합니다.""" + :param source: A built-in ``Sound`` such as ``Sound.GIGGLE``, a ``SoundEffect`` or sample data as an iterable of ``AudioFrame`` objects. + :param wait: If ``wait`` is ``True``, this function will block until the sound is complete. + :param pin: An optional argument to specify the output pin can be used to override the default of ``pin0``. If we do not want any sound to play we can use ``pin=None``. + :param return_pin: Specifies a differential edge connector pin to connect to an external speaker instead of ground. This is ignored for the **V2** revision. + """ def is_playing() -> bool: - """소리가 재생 중인지 체크합니다. + """Check whether a sound is playing. -Example: ``audio.is_playing()`` + Example: ``audio.is_playing()`` -:return: ``True`` if audio is playing, otherwise ``False``.""" + :return: ``True`` if audio is playing, otherwise ``False``.""" ... def stop() -> None: - """모든 오디오 플레이백을 중지합니다. + """Stop all audio playback. -Example: ``audio.stop()``""" + Example: ``audio.stop()`` + """ ... class SoundEffect: """A sound effect, composed by a set of parameters configured via the constructor or attributes.""" + WAVEFORM_SINE: ClassVar[int] """Sine wave option used for the ``waveform`` parameter.""" + WAVEFORM_SAWTOOTH: ClassVar[int] """Sawtooth wave option used for the ``waveform`` parameter.""" + WAVEFORM_TRIANGLE: ClassVar[int] """Triangle wave option used for the ``waveform`` parameter.""" + WAVEFORM_SQUARE: ClassVar[int] """Square wave option used for the ``waveform`` parameter.""" + WAVEFORM_NOISE: ClassVar[int] """Noise option used for the ``waveform`` parameter.""" + SHAPE_LINEAR: ClassVar[int] """Linear interpolation option used for the ``shape`` parameter.""" + SHAPE_CURVE: ClassVar[int] """Curve interpolation option used for the ``shape`` parameter.""" + SHAPE_LOG: ClassVar[int] """Logarithmic interpolation option used for the ``shape`` parameter.""" + FX_NONE: ClassVar[int] """No effect option used for the ``fx`` parameter.""" + FX_TREMOLO: ClassVar[int] """Tremolo effect option used for the ``fx`` parameter.""" + FX_VIBRATO: ClassVar[int] """Vibrato effect option used for the ``fx`` parameter.""" + FX_WARBLE: ClassVar[int] """Warble effect option used for the ``fx`` parameter.""" + freq_start: int """Start frequency in Hertz (Hz), a number between ``0`` and ``9999``""" + freq_end: int """End frequency in Hertz (Hz), a number between ``0`` and ``9999``""" + duration: int """Duration of the sound in milliseconds, a number between ``0`` and ``9999``""" + vol_start: int """Start volume value, a number between ``0`` and ``255``""" + vol_end: int """End volume value, a number between ``0`` and ``255``""" + waveform: int """Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise)""" + fx: int """Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``""" + shape: int """The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``""" - def __init__(self, freq_start: int=500, freq_end: int=2500, duration: int=500, vol_start: int=255, vol_end: int=0, waveform: int=WAVEFORM_SQUARE, fx: int=FX_NONE, shape: int=SHAPE_LOG): - """Create a new sound effect. (string) - -Example: ``my_effect = SoundEffect(duration=1000)`` - -All the parameters are optional, with default values as shown above, and -they can all be modified via attributes of the same name. For example, we -can first create an effect ``my_effect = SoundEffect(duration=1000)``, -and then change its attributes ``my_effect.duration = 500``. - -:param freq_start: Start frequency in Hertz (Hz), a number between ``0`` and ``9999``. -:param freq_end: End frequency in Hertz (Hz), a number between ``0`` and ``9999``. -:param duration: Duration of the sound in milliseconds, a number between ``0`` and ``9999``. -:param vol_start: Start volume value, a number between ``0`` and ``255``. -:param vol_end: End volume value, a number between ``0`` and ``255``. -:param waveform: Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise). -:param fx: Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``. -:param shape: The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``.""" - + def __init__( + self, + freq_start: int = 500, + freq_end: int = 2500, + duration: int = 500, + vol_start: int = 255, + vol_end: int = 0, + waveform: int = WAVEFORM_SQUARE, + fx: int = FX_NONE, + shape: int = SHAPE_LOG, + ): + """Create a new sound effect. + + Example: ``my_effect = SoundEffect(duration=1000)`` + + All the parameters are optional, with default values as shown above, and + they can all be modified via attributes of the same name. For example, we + can first create an effect ``my_effect = SoundEffect(duration=1000)``, + and then change its attributes ``my_effect.duration = 500``. + + :param freq_start: Start frequency in Hertz (Hz), a number between ``0`` and ``9999``. + :param freq_end: End frequency in Hertz (Hz), a number between ``0`` and ``9999``. + :param duration: Duration of the sound in milliseconds, a number between ``0`` and ``9999``. + :param vol_start: Start volume value, a number between ``0`` and ``255``. + :param vol_end: End volume value, a number between ``0`` and ``255``. + :param waveform: Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise). + :param fx: Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``. + :param shape: The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``. + """ def copy(self) -> SoundEffect: """Create a copy of this ``SoundEffect``. -Example: ``sound_2 = sound_1.copy()`` + Example: ``sound_2 = sound_1.copy()`` -:return: A copy of the SoundEffect.""" + :return: A copy of the SoundEffect. + """ class AudioFrame: - """``AudioFrame`` 오브젝트는 부호 없는 바이트 샘플 32개의 리스트입니다(0에서 255 사이의 모든 숫자). + """An ``AudioFrame`` object is a list of 32 samples each of which is a unsigned byte + (whole number between 0 and 255). -It takes just over 4 ms to play a single frame. + It takes just over 4 ms to play a single frame. -Example:: + Example:: - frame = AudioFrame() - for i in range(len(frame)): - frame[i] = 252 - i * 8""" + frame = AudioFrame() + for i in range(len(frame)): + frame[i] = 252 - i * 8 + """ def copyfrom(self, other: AudioFrame) -> None: """Overwrite the data in this ``AudioFrame`` with the data from another ``AudioFrame`` instance. -Example: ``my_frame.copyfrom(source_frame)`` - -:param other: ``AudioFrame`` instance from which to copy the data.""" - - def __len__(self) -> int: - ... - - def __setitem__(self, key: int, value: int) -> None: - ... + Example: ``my_frame.copyfrom(source_frame)`` - def __getitem__(self, key: int) -> int: - ... \ No newline at end of file + :param other: ``AudioFrame`` instance from which to copy the data. + """ + def __len__(self) -> int: ... + def __setitem__(self, key: int, value: int) -> None: ... + def __getitem__(self, key: int) -> int: ... diff --git a/lang/ko/typeshed/stdlib/microbit/compass.pyi b/lang/ko/typeshed/stdlib/microbit/compass.pyi index 1c2f8eb..c74a47b 100644 --- a/lang/ko/typeshed/stdlib/microbit/compass.pyi +++ b/lang/ko/typeshed/stdlib/microbit/compass.pyi @@ -1,70 +1,78 @@ -"""내장된 나침반을 사용합니다. (나침반)""" +"""Use the built-in compass. +""" def calibrate() -> None: - """보정 프로세스를 시작합니다. + """Starts the calibration process. -Example: ``compass.calibrate()`` + Example: ``compass.calibrate()`` -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.""" + 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: - """나침반이 보정되었는지 확인합니다. + """Check is the compass is calibrated. -Example: ``compass.is_calibrated()`` + Example: ``compass.is_calibrated()`` -:return: ``True`` if the compass has been successfully calibrated, ``False`` otherwise.""" + :return: ``True`` if the compass has been successfully calibrated, ``False`` otherwise. + """ ... def clear_calibration() -> None: - """보정을 해제해 나침반을 보정하지 않은 상태로 설정합니다. + """Undoes the calibration, making the compass uncalibrated again. -Example: ``compass.clear_calibration()``""" + Example: ``compass.clear_calibration()`` + """ ... def get_x() -> int: - """``x`` 축의 자기장 강도를 불러옵니다. + """Get the magnetic field strength on the ``x`` axis. -Example: ``compass.get_x()`` + Example: ``compass.get_x()`` -Call ``calibrate`` first or the results will be inaccurate. + Call ``calibrate`` first or the results will be inaccurate. -:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" + :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. + """ ... def get_y() -> int: - """``y`` 축의 자기장 강도를 불러옵니다. + """Get the magnetic field strength on the ``y`` axis. -Example: ``compass.get_y()`` + Example: ``compass.get_y()`` -Call ``calibrate`` first or the results will be inaccurate. + Call ``calibrate`` first or the results will be inaccurate. -:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" + :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. + """ ... def get_z() -> int: - """``z`` 축의 자기장 강도를 불러옵니다. + """Get the magnetic field strength on the ``z`` axis. -Example: ``compass.get_z()`` + Example: ``compass.get_z()`` -Call ``calibrate`` first or the results will be inaccurate. + Call ``calibrate`` first or the results will be inaccurate. -:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" + :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. + """ ... def heading() -> int: - """나침반의 방향을 불러옵니다. + """Get the compass heading. -Example: ``compass.heading()`` + Example: ``compass.heading()`` -:return: An integer in the range from 0 to 360, representing the angle in degrees, clockwise, with north as 0.""" + :return: An integer in the range from 0 to 360, representing the angle in degrees, clockwise, with north as 0. + """ ... def get_field_strength() -> int: - """장치 주변의 자기장 규모를 불러옵니다. + """Get the magnitude of the magnetic field around the device. -Example: ``compass.get_field_strength()`` + Example: ``compass.get_field_strength()`` -:return: An integer indication of the magnitude of the magnetic field in nano tesla.""" - ... \ No newline at end of file + :return: An integer indication of the magnitude of the magnetic field in nano tesla.""" + ... diff --git a/lang/ko/typeshed/stdlib/microbit/display.pyi b/lang/ko/typeshed/stdlib/microbit/display.pyi index af0c5de..aa4013e 100644 --- a/lang/ko/typeshed/stdlib/microbit/display.pyi +++ b/lang/ko/typeshed/stdlib/microbit/display.pyi @@ -1,92 +1,115 @@ -"""5×5 LED 디스플레이에 텍스트, 이미지, 애니메이션을 표시합니다.""" +"""Show text, images and animations on the 5×5 LED display. +""" + from ..microbit import Image from typing import Union, overload, Iterable def get_pixel(x: int, y: int) -> int: - """열 ``x``와 행 ``y``의 LED의 밝기를 불러옵니다. + """Get the brightness of the LED at column ``x`` and row ``y``. -Example: ``display.get_pixel(0, 0)`` + Example: ``display.get_pixel(0, 0)`` -:param x: 디스플레이 열(0..4) -:param y: 디스플레이 행(0..4) -:return: A number between 0 (off) and 9 (bright)""" + :param x: The display column (0..4) + :param y: The display row (0..4) + :return: A number between 0 (off) and 9 (bright) + """ ... def set_pixel(x: int, y: int, value: int) -> None: - """열 ``x``와 행 ``y``의 LED의 밝기를 설정합니다. + """Set the brightness of the LED at column ``x`` and row ``y``. -Example: ``display.set_pixel(0, 0, 9)`` + Example: ``display.set_pixel(0, 0, 9)`` -:param x: 디스플레이 열(0..4) -:param y: 디스플레이 행(0..4) -:param value: 0(꺼짐)과 9(밝음) 사이의 밝기""" + :param x: The display column (0..4) + :param y: The display row (0..4) + :param value: The brightness between 0 (off) and 9 (bright) + """ ... def clear() -> None: - """모든 LED의 밝기를 0(꺼짐)으로 설정합니다. + """Set the brightness of all LEDs to 0 (off). -Example: ``display.clear()``""" + Example: ``display.clear()`` + """ ... -def show(image: Union[str, float, int, Image, Iterable[Image]], delay: int=400, wait: bool=True, loop: bool=False, clear: bool=False) -> None: - """LED 디스플레이에 이미지, 글자 또는 숫자를 표시합니다. +def show( + image: Union[str, float, int, Image, Iterable[Image]], + delay: int = 400, + wait: bool = True, + loop: bool = False, + clear: bool = False, +) -> None: + """Shows images, letters or digits on the LED display. -Example: ``display.show(Image.HEART)`` + Example: ``display.show(Image.HEART)`` -When ``image`` is an image or a list of images then each image is displayed in turn. -If ``image`` is a string or number, each letter or digit is displayed in turn. + When ``image`` is an image or a list of images then each image is displayed in turn. + If ``image`` is a string or number, each letter or digit is displayed in turn. -:param image: 표시할 문자열, 숫자, 이미지 또는 이미지 목록입니다. -:param delay: ``delay``밀리초의 지연 시간을 두고 각 글자, 숫자 또는 이미지가 표시됩니다. -:param wait: ``wait``가 ``True``인 경우 이 기능은 애니메이션이 종료될 때까지 차단됩니다. 그렇지 않은 경우 애니메이션이 백그라운드에서 재생됩니다. -:param loop: ``loop``가 ``True``인 경우 애니메이션이 무한 반복됩니다. -:param clear: ``clear``가 ``True``인 경우 디스플레이는 시퀀스가 종료된 후 내용을 지웁니다. + :param image: A string, number, image or list of images to show. + :param delay: Each letter, digit or image is shown with ``delay`` milliseconds between them. + :param wait: If ``wait`` is ``True``, this function will block until the animation is finished, otherwise the animation will happen in the background. + :param loop: If ``loop`` is ``True``, the animation will repeat forever. + :param clear: If ``clear`` is ``True``, the display will be cleared after the sequence has finished. -The ``wait``, ``loop`` and ``clear`` arguments must be specified using their keyword.""" + The ``wait``, ``loop`` and ``clear`` arguments must be specified using their keyword. + """ ... -def scroll(text: Union[str, float, int], delay: int=150, wait: bool=True, loop: bool=False, monospace: bool=False) -> None: - """LED 디스플레이의 숫자 또는 텍스트를 스크롤합니다. - -Example: ``display.scroll('micro:bit')`` - -:param text: 스크롤할 문자열. 만약 ``text``가 정수 또는 부동수인 경우 먼저 ``str()``을 사용해 변환됩니다. -:param delay: ``delay`` 매개변수는 텍스트 스크롤링 속도를 조절합니다. -:param wait: ``wait``가 ``True``인 경우 이 기능은 애니메이션이 종료될 때까지 차단됩니다. 그렇지 않은 경우 애니메이션이 백그라운드에서 재생됩니다. -:param loop: ``loop``가 ``True``인 경우 애니메이션이 무한 반복됩니다. -:param monospace: ``monospace``가 ``True``인 경우 스크롤 중에 모든 글자는 5열의 픽셀만큼의 너비를 소모하며, 그렇지 않은 경우 글자 사이에 정확히 1열의 픽셀의 공백이 존재합니다. - -The ``wait``, ``loop`` and ``monospace`` arguments must be specified -using their keyword.""" +def scroll( + text: Union[str, float, int], + delay: int = 150, + wait: bool = True, + loop: bool = False, + monospace: bool = False, +) -> None: + """Scrolls a number or text on the LED display. + + Example: ``display.scroll('micro:bit')`` + + :param text: The string to scroll. If ``text`` is an integer or float it is first converted to a string using ``str()``. + :param delay: The ``delay`` parameter controls how fast the text is scrolling. + :param wait: If ``wait`` is ``True``, this function will block until the animation is finished, otherwise the animation will happen in the background. + :param loop: If ``loop`` is ``True``, the animation will repeat forever. + :param monospace: 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. + + The ``wait``, ``loop`` and ``monospace`` arguments must be specified + using their keyword. + """ ... def on() -> None: - """LED 디스플레이를 켭니다. + """Turn on the LED display. -Example: ``display.on()``""" + Example: ``display.on()`` + """ ... def off() -> None: - """LED 디스플레이를 끕니다(디스플레이를 비활성화하면 GPIO 핀을 다른 목적으로 재사용할 수 있습니다). + """Turn off the LED display (disabling the display allows you to re-use the GPIO pins for other purposes). -Example: ``display.off()``""" + Example: ``display.off()`` + """ ... def is_on() -> bool: - """LED 디스플레이가 활성화되어있는지 확인합니다. + """Check whether the LED display is enabled. -Example: ``display.is_on()`` + Example: ``display.is_on()`` -:return: ``True`` if the display is on, otherwise returns ``False``.""" + :return: ``True`` if the display is on, otherwise returns ``False``. + """ ... def read_light_level() -> int: - """밝기 레벨을 읽습니다. + """Read the light level. -Example: ``display.read_light_level()`` + Example: ``display.read_light_level()`` -Uses the display's LEDs in reverse-bias mode to sense the amount of light -falling on the display. + Uses the display's LEDs in reverse-bias mode to sense the amount of light + falling on the display. -:return: An integer between 0 and 255 representing the light level, with larger meaning more light.""" - ... \ No newline at end of file + :return: An integer between 0 and 255 representing the light level, with larger meaning more light. + """ + ... diff --git a/lang/ko/typeshed/stdlib/microbit/i2c.pyi b/lang/ko/typeshed/stdlib/microbit/i2c.pyi index 4fa2d4c..df26efa 100644 --- a/lang/ko/typeshed/stdlib/microbit/i2c.pyi +++ b/lang/ko/typeshed/stdlib/microbit/i2c.pyi @@ -1,49 +1,57 @@ -"""I²C 버스 프로토콜을 사용해 기기와 통신합니다.""" +"""Communicate with devices using the I²C bus protocol. +""" + from _typeshed import ReadableBuffer from ..microbit import MicroBitDigitalPin, pin19, pin20 from typing import List -def init(freq: int=100000, sda: MicroBitDigitalPin=pin20, scl: MicroBitDigitalPin=pin19) -> None: - """주변 장치를 다시 초기화합니다. +def init( + freq: int = 100000, sda: MicroBitDigitalPin = pin20, scl: MicroBitDigitalPin = pin19 +) -> None: + """Re-initialize a peripheral. -Example: ``i2c.init()`` + Example: ``i2c.init()`` -:param freq: 클럭 진동수 -:param sda: ``scl`` 핀(기본값 20) -:param scl: ``scl`` 핀(기본값 19) + :param freq: clock frequency + :param sda: ``sda`` pin (default 20) + :param scl: ``scl`` pin (default 19) -On a micro:bit V1 board, changing the I²C pins from defaults will make -the accelerometer and compass stop working, as they are connected -internally to those pins. This warning does not apply to the **V2** -revision of the micro:bit as this has `separate I²C lines `_ -for the motion sensors and the edge connector.""" + On a micro:bit V1 board, changing the I²C pins from defaults will make + the accelerometer and compass stop working, as they are connected + internally to those pins. This warning does not apply to the **V2** + revision of the micro:bit as this has `separate I²C lines `_ + for the motion sensors and the edge connector. + """ ... def scan() -> List[int]: - """버스에서 장치를 스캔합니다. + """Scan the bus for devices. -Example: ``i2c.scan()`` + Example: ``i2c.scan()`` -:return: A list of 7-bit addresses corresponding to those devices that responded to the scan.""" + :return: A list of 7-bit addresses corresponding to those devices that responded to the scan. + """ ... -def read(addr: int, n: int, repeat: bool=False) -> bytes: - """장치에서 바이트 값을 읽습니다. +def read(addr: int, n: int, repeat: bool = False) -> bytes: + """Read bytes from a device. -Example: ``i2c.read(0x50, 64)`` + Example: ``i2c.read(0x50, 64)`` -:param addr: 장치의 7비트 주소 -:param n: 읽을 바이트 수 -:param repeat: ``True``인 경우 스톱 비트가 전송되지 않습니다 -:return: The bytes read""" + :param addr: The 7-bit address of the device + :param n: The number of bytes to read + :param repeat: If ``True``, no stop bit will be sent + :return: The bytes read + """ ... -def write(addr: int, buf: ReadableBuffer, repeat: bool=False) -> None: - """장치에 바이트를 작성합니다. +def write(addr: int, buf: ReadableBuffer, repeat: bool = False) -> None: + """Write bytes to a device. -Example: ``i2c.write(0x50, bytes([1, 2, 3]))`` + Example: ``i2c.write(0x50, bytes([1, 2, 3]))`` -:param addr: 장치의 7비트 주소 -:param buf: 작성할 바이트가 포함된 버퍼 -:param repeat: ``True``인 경우 스톱 비트가 전송되지 않습니다""" - ... \ No newline at end of file + :param addr: The 7-bit address of the device + :param buf: A buffer containing the bytes to write + :param repeat: If ``True``, no stop bit will be sent + """ + ... diff --git a/lang/ko/typeshed/stdlib/microbit/microphone.pyi b/lang/ko/typeshed/stdlib/microbit/microphone.pyi index 9004514..68e8f3a 100644 --- a/lang/ko/typeshed/stdlib/microbit/microphone.pyi +++ b/lang/ko/typeshed/stdlib/microbit/microphone.pyi @@ -1,62 +1,70 @@ -"""내장 마이크를 사용해 소리에 반응합니다(V2 전용).""" +"""Respond to sound using the built-in microphone (V2 only). +""" + from typing import Optional, Tuple from ..microbit import SoundEvent def current_event() -> Optional[SoundEvent]: - """마지막으로 기록된 소리 이벤트 + """Get the last recorded sound event -Example: ``microphone.current_event()`` + Example: ``microphone.current_event()`` -:return: The event, ``SoundEvent('loud')`` or ``SoundEvent('quiet')``.""" + :return: The event, ``SoundEvent('loud')`` or ``SoundEvent('quiet')``. + """ ... def was_event(event: SoundEvent) -> bool: - """마지막 호출 이후로 소리가 들렸는지 확인합니다. + """Check if a sound was heard at least once since the last call. -Example: ``microphone.was_event(SoundEvent.LOUD)`` + Example: ``microphone.was_event(SoundEvent.LOUD)`` -This call clears the sound history before returning. + This call clears the sound history before returning. -:param event: ``SoundEvent.LOUD`` 또는 ``SoundEvent.QUIET`` 등을 확인하기 위한 이벤트 -:return: ``True`` if sound was heard at least once since the last call, otherwise ``False``.""" + :param event: The event to check for, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET`` + :return: ``True`` if sound was heard at least once since the last call, otherwise ``False``. + """ ... def is_event(event: SoundEvent) -> bool: - """가장 최근 탐지된 소리 이벤트를 확인합니다. + """Check the most recent sound event detected. -Example: ``microphone.is_event(SoundEvent.LOUD)`` + Example: ``microphone.is_event(SoundEvent.LOUD)`` -This call does not clear the sound event history. + This call does not clear the sound event history. -:param event: ``SoundEvent.LOUD`` 또는 ``SoundEvent.QUIET`` 등을 확인하기 위한 이벤트 -:return: ``True`` if sound was the most recent heard, ``False`` otherwise.""" + :param event: The event to check for, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET`` + :return: ``True`` if sound was the most recent heard, ``False`` otherwise. + """ ... def get_events() -> Tuple[SoundEvent, ...]: - """소리 이벤트 기록을 튜플로 가져옵니다. + """Get the sound event history as a tuple. -Example: ``microphone.get_events()`` + Example: ``microphone.get_events()`` -This call clears the sound history before returning. + This call clears the sound history before returning. -:return: A tuple of the event history with the most recent event last.""" + :return: A tuple of the event history with the most recent event last. + """ ... def set_threshold(event: SoundEvent, value: int) -> None: - """소리 이벤트 임계값을 설정합니다. + """Set the threshold for a sound event. -Example: ``microphone.set_threshold(SoundEvent.LOUD, 250)`` + Example: ``microphone.set_threshold(SoundEvent.LOUD, 250)`` -A high threshold means the event will only trigger if the sound is very loud (>= 250 in the example). + A high threshold means the event will only trigger if the sound is very loud (>= 250 in the example). -:param event: ``SoundEvent.LOUD`` 또는 ``SoundEvent.QUIET`` 등의 소리 이벤트입니다. -:param value: 0~255의 범위로 된 임계값입니다.""" + :param event: A sound event, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET``. + :param value: The threshold level in the range 0-255. + """ ... def sound_level() -> int: - """음압 레벨을 불러옵니다. + """Get the sound pressure level. -Example: ``microphone.sound_level()`` + Example: ``microphone.sound_level()`` -:return: A representation of the sound pressure level in the range 0 to 255.""" - ... \ No newline at end of file + :return: A representation of the sound pressure level in the range 0 to 255. + """ + ... diff --git a/lang/ko/typeshed/stdlib/microbit/speaker.pyi b/lang/ko/typeshed/stdlib/microbit/speaker.pyi index ce3f1d8..5a74a4d 100644 --- a/lang/ko/typeshed/stdlib/microbit/speaker.pyi +++ b/lang/ko/typeshed/stdlib/microbit/speaker.pyi @@ -1,15 +1,18 @@ -"""내장 스피커를 제어합니다(V2 전용).""" +"""Control the built-in speaker (V2 only). +""" def off() -> None: - """스피커를 끕니다. + """Turn the speaker off. -Example: ``speaker.off()`` + Example: ``speaker.off()`` -This does not disable sound output to an edge connector pin.""" + This does not disable sound output to an edge connector pin. + """ ... def on() -> None: - """스피커를 켭니다. + """Turn the speaker on. -Example: ``speaker.on()``""" - ... \ No newline at end of file + Example: ``speaker.on()`` + """ + ... diff --git a/lang/ko/typeshed/stdlib/microbit/spi.pyi b/lang/ko/typeshed/stdlib/microbit/spi.pyi index 192f1a2..09c4046 100644 --- a/lang/ko/typeshed/stdlib/microbit/spi.pyi +++ b/lang/ko/typeshed/stdlib/microbit/spi.pyi @@ -1,47 +1,60 @@ -"""직렬 주변 장치 인터페이스(SPI) 버스를 사용해 장치와 통신합니다.""" +"""Communicate with devices using the serial peripheral interface (SPI) bus. +""" + from _typeshed import ReadableBuffer, WriteableBuffer from ..microbit import pin13, pin14, pin15, MicroBitDigitalPin -def init(baudrate: int=1000000, bits: int=8, mode: int=0, sclk: MicroBitDigitalPin=pin13, mosi: MicroBitDigitalPin=pin15, miso: MicroBitDigitalPin=pin14) -> None: - """SPI 통신을 시작합니다. (string) - -Example: ``spi.init()`` - -For correct communication, the parameters have to be the same on both communicating devices. - -:param baudrate: 통신 속도입니다. -:param bits: 각 전송의 비트의 너비입니다. 현재 ``bits=8``만 지원되나 향후 변경될 수 있습니다. -:param mode: 클럭 극성과 페이즈의 조합을 결정합니다. 온라인 테이블을 참조하세요 `_. -:param sclk: sclk 핀(기본값 13) -:param mosi: mosi 핀(기본값 15) -:param miso: miso 핀(기본값 14)""" +def init( + baudrate: int = 1000000, + bits: int = 8, + mode: int = 0, + sclk: MicroBitDigitalPin = pin13, + mosi: MicroBitDigitalPin = pin15, + miso: MicroBitDigitalPin = pin14, +) -> None: + """Initialize SPI communication. + + Example: ``spi.init()`` + + For correct communication, the parameters have to be the same on both communicating devices. + + :param baudrate: The speed of communication. + :param bits: The width in bits of each transfer. Currently only ``bits=8`` is supported. However, this may change in the future. + :param mode: Determines the combination of clock polarity and phase - `see online table `_. + :param sclk: sclk pin (default 13) + :param mosi: mosi pin (default 15) + :param miso: miso pin (default 14) + """ ... -def read(nbytes: int, out: int=0) -> bytes: - """바이트를 읽습니다. +def read(nbytes: int, out: int = 0) -> bytes: + """Read at most ``nbytes`` while continuously writing the single byte given by ``out``. -Example: ``spi.read(64)`` + Example: ``spi.read(64)`` -:param nbytes: 읽을 바이트의 최대 수입니다. -:param out: The byte value to write (default 0). -:return: The bytes read.""" + :param nbytes: Maximum number of bytes to read. + :param out: The byte value to write (default 0). + :return: The bytes read. + """ ... def write(buffer: ReadableBuffer) -> None: - """버스에 바이트를 작성합니다. + """Write bytes to the bus. -Example: ``spi.write(bytes([1, 2, 3]))`` + Example: ``spi.write(bytes([1, 2, 3]))`` -:param buffer: 데이터를 읽을 버퍼입니다.""" + :param buffer: A buffer to read data from. + """ ... def write_readinto(out: WriteableBuffer, in_: ReadableBuffer) -> None: - """버스에 ``out`` 버퍼를 작성하고 발생하는 ``in_`` 버퍼의 모든 응답을 읽습니다. + """Write the ``out`` buffer to the bus and read any response into the ``in_`` buffer. -Example: ``spi.write_readinto(out_buffer, in_buffer)`` + Example: ``spi.write_readinto(out_buffer, in_buffer)`` -The length of the buffers should be the same. The buffers can be the same object. + The length of the buffers should be the same. The buffers can be the same object. -:param out: 응답을 작성할 버퍼입니다. -:param in_: 데이터를 읽을 버퍼입니다.""" - ... \ No newline at end of file + :param out: The buffer to write any response to. + :param in_: The buffer to read data from. + """ + ... diff --git a/lang/ko/typeshed/stdlib/microbit/uart.pyi b/lang/ko/typeshed/stdlib/microbit/uart.pyi index f40a262..2ab650f 100644 --- a/lang/ko/typeshed/stdlib/microbit/uart.pyi +++ b/lang/ko/typeshed/stdlib/microbit/uart.pyi @@ -1,79 +1,96 @@ -"""직렬 인터페이스를 사용해 장치와 통신합니다.""" +"""Communicate with a device using a serial interface. +""" + from _typeshed import WriteableBuffer from ..microbit import MicroBitDigitalPin from typing import Optional, Union -ODD: int -"""홀수 패리티""" -EVEN: int -"""짝수 패리티""" - -def init(baudrate: int=9600, bits: int=8, parity: Optional[int]=None, stop: int=1, tx: Optional[MicroBitDigitalPin]=None, rx: Optional[MicroBitDigitalPin]=None) -> None: - """직렬 통신을 시작합니다. (string) - -Example: ``uart.init(115200, tx=pin0, rx=pin1)`` -:param baudrate: 통신 속도입니다. -:param bits: 전송되는 바이트의 크기입니다. micro:bit는 8바이트만 지원합니다. -:param parity: (패리티) 패리티가 체크되는 방식으로 ``None``, ``uart.ODD`` 또는 ``uart.EVEN``을 사용합니다. -:param stop: 스톱 비트의 번호입니다. micro:bit는 1이어야 합니다. -:param tx: 전송하는 핀입니다. -:param rx: 수신하는 핀입니다. - -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. +ODD: int +"""Odd parity""" -For more details see `the online documentation `_.""" +EVEN: int +"""Even parity""" + +def init( + baudrate: int = 9600, + bits: int = 8, + parity: Optional[int] = None, + stop: int = 1, + tx: Optional[MicroBitDigitalPin] = None, + rx: Optional[MicroBitDigitalPin] = None, +) -> None: + """Initialize serial communication. + + Example: ``uart.init(115200, tx=pin0, rx=pin1)`` + + :param baudrate: The speed of communication. + :param bits: The size of bytes being transmitted. micro:bit only supports 8. + :param parity: How parity is checked, ``None``, ``uart.ODD`` or ``uart.EVEN``. + :param stop: The number of stop bits, has to be 1 for micro:bit. + :param tx: Transmitting pin. + :param rx: Receiving pin. + + 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. + + For more details see `the online documentation `_. + """ ... def any() -> bool: - """대기 중인 데이터가 있는지 확인합니다. + """Check if any data is waiting. -Example: ``uart.any()`` + Example: ``uart.any()`` -:return: ``True`` if any data is waiting, else ``False``.""" + :return: ``True`` if any data is waiting, else ``False``. + """ ... -def read(nbytes: Optional[int]=None) -> Optional[bytes]: - """바이트를 읽습니다. +def read(nbytes: Optional[int] = None) -> Optional[bytes]: + """Read bytes. -Example: ``uart.read()`` + Example: ``uart.read()`` -:param nbytes: ``nbytes``가 특정되어 있다면 해당 바이트 수만큼 읽습니다. 특정되지 않은 경우 최대한 많은 바이트를 읽습니다. -:return: A bytes object or ``None`` on timeout""" + :param nbytes: If ``nbytes`` is specified then read at most that many bytes, otherwise read as many bytes as possible + :return: A bytes object or ``None`` on timeout + """ ... -def readinto(buf: WriteableBuffer, nbytes: Optional[int]=None) -> Optional[int]: - """``buf``로 바이트를 읽습니다. +def readinto(buf: WriteableBuffer, nbytes: Optional[int] = None) -> Optional[int]: + """Read bytes into the ``buf``. -Example: ``uart.readinto(input_buffer)`` + Example: ``uart.readinto(input_buffer)`` -:param buf: 바이트를 기록할 버퍼입니다. -:param nbytes: ``nbytes``가 특정되어 있다면 해당 바이트 수만큼 읽습니다. 특정되지 않은 경우 ``len(buf)``바이트를 읽습니다. -:return: number of bytes read and stored into ``buf`` or ``None`` on timeout.""" + :param buf: The buffer to write to. + :param nbytes: If ``nbytes`` is specified then read at most that many bytes, otherwise read ``len(buf)`` bytes. + :return: number of bytes read and stored into ``buf`` or ``None`` on timeout. + """ ... def readline() -> Optional[bytes]: - """새로운 줄 문자로 끝나는 줄을 읽습니다. + """Read a line, ending in a newline character. -Example: ``uart.readline()`` + Example: ``uart.readline()`` -:return: The line read or ``None`` on timeout. The newline character is included in the returned bytes.""" + :return: The line read or ``None`` on timeout. The newline character is included in the returned bytes. + """ ... def write(buf: Union[bytes, str]) -> Optional[int]: - """버스에 버퍼를 기록합니다. + """Write a buffer to the bus. -Example: ``uart.write('hello world')`` + Example: ``uart.write('hello world')`` -:param buf: 바이트 오브젝트 또는 문자열입니다. -:return: The number of bytes written, or ``None`` on timeout. + :param buf: A bytes object or a string. + :return: The number of bytes written, or ``None`` on timeout. -Examples:: + Examples:: - uart.write('hello world') - uart.write(b'hello world') - uart.write(bytes([1, 2, 3]))""" - ... \ No newline at end of file + uart.write('hello world') + uart.write(b'hello world') + uart.write(bytes([1, 2, 3])) + """ + ... diff --git a/lang/ko/typeshed/stdlib/micropython.pyi b/lang/ko/typeshed/stdlib/micropython.pyi index 1f469da..7a6079f 100644 --- a/lang/ko/typeshed/stdlib/micropython.pyi +++ b/lang/ko/typeshed/stdlib/micropython.pyi @@ -1,131 +1,144 @@ -"""MicroPython 내부 정보입니다.""" +"""MicroPython internals.""" + from typing import Any, TypeVar, overload -_T = TypeVar('_T') + +_T = TypeVar("_T") def const(expr: _T) -> _T: - """컴파일러가 최적화할 수 있도록 해당 수식이 상수임을 선언합니다. + """Used to declare that the expression is a constant so that the compiler can + optimise it. -The use of this function should be as follows:: + The use of this function should be as follows:: - from micropython import const - CONST_X = const(123) - CONST_Y = const(2 * CONST_X + 1) + from micropython import const + CONST_X = const(123) + CONST_Y = const(2 * CONST_X + 1) -Constants declared this way are still accessible as global variables from -outside the module they are declared in. On the other hand, if a constant -begins with an underscore then it is hidden, it is not available as a -global variable, and does not take up any memory during execution. + Constants declared this way are still accessible as global variables from + outside the module they are declared in. On the other hand, if a constant + begins with an underscore then it is hidden, it is not available as a + global variable, and does not take up any memory during execution. -:param expr: 상수 표현식입니다.""" + :param expr: A constant expression. + """ ... @overload def opt_level() -> int: - """스크립트의 현재 컴파일 최적화 레벨을 불러옵니다. + """Get the current optimisation level for the compilation of scripts. -Example: ``micropython.opt_level()`` + Example: ``micropython.opt_level()`` -The optimisation level controls the following compilation features: + The optimisation level controls the following compilation features: -- Assertions: at level 0 assertion statements are enabled and compiled - into the bytecode; at levels 1 and higher assertions are not compiled. + - Assertions: at level 0 assertion statements are enabled and compiled + into the bytecode; at levels 1 and higher assertions are not compiled. -- Built-in ``__debug__`` variable: at level 0 this variable expands to - True; at levels 1 and higher it expands to False. + - Built-in ``__debug__`` variable: at level 0 this variable expands to + True; at levels 1 and higher it expands to False. -- Source-code line numbers: at levels 0, 1 and 2 source-code line number - are stored along with the bytecode so that exceptions can report the - line number they occurred at; at levels 3 and higher line numbers are - not stored. + - Source-code line numbers: at levels 0, 1 and 2 source-code line number + are stored along with the bytecode so that exceptions can report the + line number they occurred at; at levels 3 and higher line numbers are + not stored. -:return: An integer representing the current level.""" + :return: An integer representing the current level. + """ ... @overload def opt_level(level: int) -> None: - """스크립트의 후속 컴파일 최적화 레벨을 설정합니다. + """Sets the optimisation level for subsequent compilation of scripts. -Example: ``micropython.opt_level(1)`` + Example: ``micropython.opt_level(1)`` -The optimisation level controls the following compilation features: + The optimisation level controls the following compilation features: -- Assertions: at level 0 assertion statements are enabled and compiled - into the bytecode; at levels 1 and higher assertions are not compiled. + - Assertions: at level 0 assertion statements are enabled and compiled + into the bytecode; at levels 1 and higher assertions are not compiled. -- Built-in ``__debug__`` variable: at level 0 this variable expands to - True; at levels 1 and higher it expands to False. + - Built-in ``__debug__`` variable: at level 0 this variable expands to + True; at levels 1 and higher it expands to False. -- Source-code line numbers: at levels 0, 1 and 2 source-code line number - are stored along with the bytecode so that exceptions can report the - line number they occurred at; at levels 3 and higher line numbers are - not stored. + - Source-code line numbers: at levels 0, 1 and 2 source-code line number + are stored along with the bytecode so that exceptions can report the + line number they occurred at; at levels 3 and higher line numbers are + not stored. -The default optimisation level is usually level 0. + The default optimisation level is usually level 0. -:param level: 정수로 된 최적화 레벨입니다.""" + :param level: An integer optimisation level. + """ ... -def mem_info(verbose: Any=None) -> None: - """현재 사용 중인 메모리에 대한 정보를 프린트합니다. +def mem_info(verbose: Any = None) -> None: + """Print information about currently used memory. -Example: ``micropython.mem_info()`` + Example: ``micropython.mem_info()`` -:param verbose: ``verbose`` 인자가 주어지면 추가 정보를 프린트합니다.""" + :param verbose: If the ``verbose`` argument is given then extra information is printed. + """ ... -def qstr_info(verbose: Any=None) -> None: - """현재 반환된 문자열에 대한 정보를 프린트합니다. +def qstr_info(verbose: Any = None) -> None: + """Print information about currently interned strings. -Example: ``micropython.qstr_info()`` + Example: ``micropython.qstr_info()`` -:param verbose: ``verbose`` 인자가 주어지면 추가 정보를 프린트합니다. + :param verbose: If the ``verbose`` argument is given then extra information is printed. -The information that is printed is implementation dependent, but currently -includes the number of interned strings and the amount of RAM they use. In -verbose mode it prints out the names of all RAM-interned strings.""" + The information that is printed is implementation dependent, but currently + includes the number of interned strings and the amount of RAM they use. In + verbose mode it prints out the names of all RAM-interned strings. + """ ... def stack_use() -> int: - """현재 사용 중인 스택의 수를 나타내는 정수를 반환합니다. + """Return an integer representing the current amount of stack that is being + used. -Example: ``micropython.stack_use()`` + Example: ``micropython.stack_use()`` -The absolute value of this is not particularly useful, rather it -should be used to compute differences in stack usage at different points. + The absolute value of this is not particularly useful, rather it + should be used to compute differences in stack usage at different points. -:return: An integer representing current stack use.""" + :return: An integer representing current stack use. + """ ... def heap_lock() -> None: - """힙을 잠급니다. + """Lock the heap. -Example: ``micropython.heap_lock()`` + Example: ``micropython.heap_lock()`` -When locked no memory allocation can occur and a ``MemoryError`` will be -raised if any heap allocation is attempted.""" + When locked no memory allocation can occur and a ``MemoryError`` will be + raised if any heap allocation is attempted. + """ ... def heap_unlock() -> None: - """힙을 잠금 해제합니다. + """Unlock the heap. -Example: ``micropython.heap_unlock()`` + Example: ``micropython.heap_unlock()`` -When locked no memory allocation can occur and a ``MemoryError`` will be -raised if any heap allocation is attempted.""" + When locked no memory allocation can occur and a ``MemoryError`` will be + raised if any heap allocation is attempted. + """ ... def kbd_intr(chr: int) -> None: - """``KeyboardInterrupt`` 예외를 제기할 문자를 설정합니다. + """Set the character that will raise a ``KeyboardInterrupt`` exception. -Example: ``micropython.kbd_intr(-1)`` + Example: ``micropython.kbd_intr(-1)`` -:param chr: 인터럽트를 제기하기 위한 문자 코드입니다. -1은 Ctrl-C 캡처를 비활성화합니다. + :param chr: Character code to raise the interrupt or -1 to disable capture of Ctrl-C. -By default this is set to 3 during script execution, corresponding to Ctrl-C. -Passing -1 to this function will disable capture of Ctrl-C, and passing 3 -will restore it. + By default this is set to 3 during script execution, corresponding to Ctrl-C. + Passing -1 to this function will disable capture of Ctrl-C, and passing 3 + will restore it. -This function can be used to prevent the capturing of Ctrl-C on the -incoming stream of characters that is usually used for the REPL, in case -that stream is used for other purposes.""" - ... \ No newline at end of file + This function can be used to prevent the capturing of Ctrl-C on the + incoming stream of characters that is usually used for the REPL, in case + that stream is used for other purposes. + """ + ... diff --git a/lang/ko/typeshed/stdlib/music.pyi b/lang/ko/typeshed/stdlib/music.pyi index e61bcd8..5f4778b 100644 --- a/lang/ko/typeshed/stdlib/music.pyi +++ b/lang/ko/typeshed/stdlib/music.pyi @@ -1,128 +1,167 @@ -"""멜로디를 생성하고 재생합니다.""" +"""Create and play melodies. +""" from typing import Optional, Tuple, Union, List + from .microbit import MicroBitDigitalPin, pin0 + DADADADUM: Tuple[str, ...] -"""멜로디: 베토벤의 교향곡 제5번 다 단조 도입부입니다.""" +"""Melody: the opening to Beethoven’s 5th Symphony in C minor.""" + ENTERTAINER: Tuple[str, ...] -"""멜로디: 스콧 조플린의 래그타임 고전 “The Entertainer” 도입부 일부입니다.""" +"""Melody: the opening fragment of Scott Joplin’s Ragtime classic “The Entertainer”.""" + PRELUDE: Tuple[str, ...] -"""멜로디: 요한 제바스티안 바흐의 48 Preludes and Fugues 다 장조 첫 전주곡 도입부입니다.""" +"""Melody: the opening of the first Prelude in C Major of J.S.Bach’s 48 Preludes and Fugues.""" + ODE: Tuple[str, ...] -"""멜로디: 베토벤의 교향곡 제9번 라 단조 “Ode to Joy” 테마입니다.""" +"""Melody: the “Ode to Joy” theme from Beethoven’s 9th Symphony in D minor.""" + NYAN: Tuple[str, ...] -"""멜로디: Nyan Cat 테마입니다(http://www.nyan.cat/). +"""Melody: the Nyan Cat theme (http://www.nyan.cat/). The composer is unknown. This is fair use for educational porpoises (as they say in New York).""" + RINGTONE: Tuple[str, ...] -"""멜로디: 휴대폰 벨소리와 유사한 소리입니다. +"""Melody: something that sounds like a mobile phone ringtone. To be used to indicate an incoming message. """ + FUNK: Tuple[str, ...] -"""멜로디: 비밀 요원과 천재 범죄자에 어울리는 펑키 베이스 라인입니다.""" +"""Melody: a funky bass line for secret agents and criminal masterminds.""" + BLUES: Tuple[str, ...] -"""멜로디: 부기 우기 12바 블루스 워킹 베이스입니다.""" +"""Melody: a boogie-woogie 12-bar blues walking bass.""" + BIRTHDAY: Tuple[str, ...] -"""멜로디: 생일 축하 노래입니다. +"""Melody: “Happy Birthday to You…” For copyright status see: http://www.bbc.co.uk/news/world-us-canada-34332853 """ + WEDDING: Tuple[str, ...] -"""Melody: 바그너의 오페라 “로엔그린”의 결혼식 합창입니다.""" +"""Melody: the bridal chorus from Wagner’s opera “Lohengrin”.""" + FUNERAL: Tuple[str, ...] -"""멜로디: “장송행진곡”이라고도 알려진 프레데리크 쇼팽의 피아노 소나타 제2번 B♭ 단조 Op. 35입니다.""" +"""Melody: the “funeral march” otherwise known as Frédéric Chopin’s Piano Sonata No. 2 in B♭ minor, Op. 35.""" + PUNCHLINE: Tuple[str, ...] -"""멜로디: 농담할 때 나오는 재미있는 멜로디입니다.""" +"""Melody: a fun fragment that signifies a joke has been made.""" + PYTHON: Tuple[str, ...] -"""멜로디: 존 필립 수자의 “자유의 종” 행진곡입니다. “몬티 파이튼의 비행 서커스” 테마곡으로도 알려져 있습니다(Python 프로그래밍 언어는 몬티 파이튼의 이름에서 유래했습니다).""" +"""Melody: John Philip Sousa’s march “Liberty Bell” aka, the theme for “Monty Python’s Flying Circus” (after which the Python programming language is named).""" + BADDY: Tuple[str, ...] -"""멜로디: 무성 영화 시대의 악당 등장 멜로디입니다.""" +"""Melody: silent movie era entrance of a baddy.""" + CHASE: Tuple[str, ...] -"""멜로디: 무성 영화 시대의 추격 장면 멜로디입니다.""" +"""Melody: silent movie era chase scene.""" + BA_DING: Tuple[str, ...] -"""멜로디:어떤 일이 일어났다는 것을 알려주는 짧은 신호음입니다.""" +"""Melody: a short signal to indicate something has happened.""" + WAWAWAWAA: Tuple[str, ...] -"""멜로디: 아주 슬픈 트럼본 소리입니다.""" +"""Melody: a very sad trombone.""" + JUMP_UP: Tuple[str, ...] -"""멜로디: 게임에서 위로 움직이는 것을 표현하는 소리입니다.""" +"""Melody: for use in a game, indicating upward movement.""" + JUMP_DOWN: Tuple[str, ...] -"""멜로디: 게임에서 아래로 움직이는 것을 표현하는 소리입니다.""" +"""Melody: for use in a game, indicating downward movement.""" + POWER_UP: Tuple[str, ...] -"""멜로디: 업적 달성을 알리는 팡파르 소리입니다.""" +"""Melody: a fanfare to indicate an achievement unlocked.""" + POWER_DOWN: Tuple[str, ...] -"""멜로디: 업적 달성 실패를 의미하는 슬픈 팡파르 소리입니다.""" +"""Melody: a sad fanfare to indicate an achievement lost.""" -def set_tempo(ticks: int=4, bpm: int=120) -> None: - """플레이백의 빠르기를 대략적으로 설정합니다. +def set_tempo(ticks: int = 4, bpm: int = 120) -> None: + """Sets the approximate tempo for playback. -Example: ``music.set_tempo(bpm=120)`` + Example: ``music.set_tempo(bpm=120)`` -:param ticks: 비트 하나를 구성하는 틱의 수입니다. -:param bpm: 분당 비트 수를 결정하는 정수입니다. + :param ticks: The number of ticks constituting a beat. + :param bpm: An integer determining how many beats per minute. -Suggested default values allow the following useful behaviour: + Suggested default values allow the following useful behaviour: -- music.set_tempo() – reset the tempo to default of ticks = 4, bpm = 120 -- music.set_tempo(ticks=8) – change the “definition” of a beat -- music.set_tempo(bpm=180) – just change the tempo + - music.set_tempo() – reset the tempo to default of ticks = 4, bpm = 120 + - music.set_tempo(ticks=8) – change the “definition” of a beat + - music.set_tempo(bpm=180) – just change the tempo -To work out the length of a tick in milliseconds is very simple arithmetic: -60000/bpm/ticks_per_beat. For the default values that’s -60000/120/4 = 125 milliseconds or 1 beat = 500 milliseconds.""" + To work out the length of a tick in milliseconds is very simple arithmetic: + 60000/bpm/ticks_per_beat. For the default values that’s + 60000/120/4 = 125 milliseconds or 1 beat = 500 milliseconds. + """ ... def get_tempo() -> Tuple[int, int]: - """현재 빠르기를 정수 튜플로 가져옵니다: ``(ticks, bpm)``. + """Gets the current tempo as a tuple of integers: ``(ticks, bpm)``. -Example: ``ticks, beats = music.get_tempo()`` + Example: ``ticks, beats = music.get_tempo()`` -:return: The temp as a tuple with two integer values, the ticks then the beats per minute.""" + :return: The temp as a tuple with two integer values, the ticks then the beats per minute. + """ ... -def play(music: Union[str, List[str], Tuple[str, ...]], pin: Optional[MicroBitDigitalPin]=pin0, wait: bool=True, loop: bool=False) -> None: - """음악을 재생합니다. +def play( + music: Union[str, List[str], Tuple[str, ...]], + pin: Optional[MicroBitDigitalPin] = pin0, + wait: bool = True, + loop: bool = False, +) -> None: + """Plays music. -Example: ``music.play(music.NYAN)`` + Example: ``music.play(music.NYAN)`` -:param music: `별첨 `_에 명시된 음악 -:param pin: (핀) 외장 스피커에 사용할 출력 핀입니다(기본값 ``pin0``). ``None``으로 설정하면 소리가 재생되지 않습니다. -:param wait: ``wait``이 ``True``로 설정된 경우 이 기능은 블로킹 상태가 됩니다. -:param loop: ``loop``가 ``True``인 경우 ``stop``이 호출되거나 블로킹 호출이 인터럽트되기 전까지 계속 반복됩니다. + :param music: music specified in `a special notation `_ + :param pin: the output pin for use with an external speaker (default ``pin0``), ``None`` for no sound. + :param wait: If ``wait`` is set to ``True``, this function is blocking. + :param loop: If ``loop`` is set to ``True``, the tune repeats until ``stop`` is called or the blocking call is interrupted. -Many built-in melodies are defined in this module.""" + Many built-in melodies are defined in this module. + """ ... -def pitch(frequency: int, duration: int=-1, pin: Optional[MicroBitDigitalPin]=pin0, wait: bool=True) -> None: - """음을 재생합니다. (앞-뒤 기울기) +def pitch( + frequency: int, + duration: int = -1, + pin: Optional[MicroBitDigitalPin] = pin0, + wait: bool = True, +) -> None: + """Play a note. -Example: ``music.pitch(185, 1000)`` + Example: ``music.pitch(185, 1000)`` -:param frequency: (진동수) 정수 진동수입니다. -:param duration: 밀리초 단위의 기간입니다. 음수인 경우 소리가 다음 호출 또는 ``stop`` 호출까지 계속 재생됩니다. -:param pin: (핀) 출력 핀입니다(기본값 ``pin0``)(선택 사항). -:param wait: ``wait``이 ``True``로 설정된 경우 이 기능은 블로킹 상태가 됩니다. + :param frequency: An integer frequency + :param duration: A millisecond duration. If negative then sound is continuous until the next call or a call to ``stop``. + :param pin: Optional output pin (default ``pin0``). + :param wait: If ``wait`` is set to ``True``, this function is blocking. -For example, if the frequency is set to 440 and the length to -1000 then we hear a standard concert A for one second. + For example, if the frequency is set to 440 and the length to + 1000 then we hear a standard concert A for one second. -You can only play one pitch on one pin at any one time.""" + You can only play one pitch on one pin at any one time. + """ ... -def stop(pin: Optional[MicroBitDigitalPin]=pin0) -> None: - """내장 스피커와 핀으로 출력되는 모든 음악 플레이백을 멈춥니다. +def stop(pin: Optional[MicroBitDigitalPin] = pin0) -> None: + """Stops all music playback on the built-in speaker and any pin outputting sound. -Example: ``music.stop()`` + Example: ``music.stop()`` -:param pin: (핀) 핀을 특정하기 위한 인자입니다(예: ``music.stop(pin1)``)(선택 사항).""" + :param pin: An optional argument can be provided to specify a pin, e.g. ``music.stop(pin1)``. + """ def reset() -> None: - """틱, bpm, 기간 및 옥타브를 기본값으로 초기화합니다. + """Resets ticks, bpm, duration and octave to their default values. -Example: ``music.reset()`` + Example: ``music.reset()`` -Values: -- ``ticks = 4`` -- ``bpm = 120`` -- ``duration = 4`` -- ``octave = 4``""" - ... \ No newline at end of file + Values: + - ``ticks = 4`` + - ``bpm = 120`` + - ``duration = 4`` + - ``octave = 4`` + """ + ... diff --git a/lang/ko/typeshed/stdlib/neopixel.pyi b/lang/ko/typeshed/stdlib/neopixel.pyi index 275839b..2d5a749 100644 --- a/lang/ko/typeshed/stdlib/neopixel.pyi +++ b/lang/ko/typeshed/stdlib/neopixel.pyi @@ -1,81 +1,82 @@ -"""개별 주소를 지정할 수 있는 RGB 및 RGBW LED 스트립입니다.""" +"""Individually addressable RGB and RGBW LED strips. +""" from .microbit import MicroBitDigitalPin from typing import Tuple class NeoPixel: + def __init__(self, pin: MicroBitDigitalPin, n: int, bpp: int = 3) -> None: + """Initialise a new strip of neopixel LEDs controlled via a pin. - def __init__(self, pin: MicroBitDigitalPin, n: int, bpp: int=3) -> None: - """핀으로 제어되는 새로운 스트립의 네오픽셀 LED를 시작합니다. (string) + Example: ``np = neopixel.NeoPixel(pin0, 8)`` -Example: ``np = neopixel.NeoPixel(pin0, 8)`` + To support RGBW neopixels, a third argument can be passed to + ``NeoPixel`` to indicate the number of bytes per pixel (``bpp``). + For RGBW, this is is 4 rather than the default of 3 for RGB and GRB. -To support RGBW neopixels, a third argument can be passed to -``NeoPixel`` to indicate the number of bytes per pixel (``bpp``). -For RGBW, this is is 4 rather than the default of 3 for RGB and GRB. + Each pixel is addressed by a position (starting from 0). Neopixels are + given RGB (red, green, blue) / RGBW (red, green, blue, white) values + between 0-255 as a tuple. For example, in RGB, ``(255,255,255)`` is + white. In RGBW, ``(255,255,255,0)`` or ``(0,0,0,255)`` is white. -Each pixel is addressed by a position (starting from 0). Neopixels are -given RGB (red, green, blue) / RGBW (red, green, blue, white) values -between 0-255 as a tuple. For example, in RGB, ``(255,255,255)`` is -white. In RGBW, ``(255,255,255,0)`` or ``(0,0,0,255)`` is white. + See `the online docs `_ for warnings and other advice. -See `the online docs `_ for warnings and other advice. - -:param pin: (핀) 네오픽셀 스트립을 제어하는 핀입니다. -:param n: 스트립의 네오픽셀 수입니다. -:param bpp: 픽셀당 바이트입니다. RGBW 네오픽셀 지원을 위해서는 RGB 및 GRB의 기본값 3 대신 4를 패스해야 합니다.""" + :param pin: The pin controlling the neopixel strip. + :param n: The number of neopixels in the strip. + :param bpp: Bytes per pixel. For RGBW neopixel support, pass 4 rather than the default of 3 for RGB and GRB. + """ ... - def clear(self) -> None: - """모든 픽셀을 지웁니다. + """Clear all the pixels. -Example: ``np.clear()``""" + Example: ``np.clear()`` + """ ... - def show(self) -> None: - """픽셀을 표시합니다. + """Show the pixels. -Example: ``np.show()`` + Example: ``np.show()`` -Must be called for any updates to become visible.""" + Must be called for any updates to become visible. + """ ... - def write(self) -> None: - """픽셀을 표시합니다(micro:bit V2 전용). + """Show the pixels (micro:bit V2 only). -Example: ``np.write()`` + Example: ``np.write()`` -Must be called for any updates to become visible. + Must be called for any updates to become visible. -Equivalent to ``show``.""" + Equivalent to ``show``. + """ ... - def fill(self, colour: Tuple[int, ...]) -> None: - """모든 픽셀에 주어진 RGB/RGBW 값을 칠합니다(micro:bit V2 전용). + """Colour all pixels a given RGB/RGBW value (micro:bit V2 only). -Example: ``np.fill((0, 0, 255))`` + Example: ``np.fill((0, 0, 255))`` -:param colour: 픽셀 당 바이트 수(bpp)와 같은 길이의 튜플입니다. + :param colour: A tuple of the same length as the number of bytes per pixel (bpp). -Use in conjunction with ``show()`` to update the neopixels.""" + Use in conjunction with ``show()`` to update the neopixels. + """ ... - def __setitem__(self, key: int, value: Tuple[int, ...]) -> None: - """픽셀 색상을 설정합니다. + """Set a pixel colour. -Example: ``np[0] = (255, 0, 0)`` - -:param key: 픽셀 번호입니다. -:param value: 색상입니다.""" + Example: ``np[0] = (255, 0, 0)`` + :param key: The pixel number. + :param value: The colour. + """ def __getitem__(self, key: int) -> Tuple[int, ...]: - """픽셀 색상을 불러옵니다. - -Example: ``r, g, b = np[0]`` + """Get a pixel colour. -:param key: 픽셀 번호입니다. -:return: The colour tuple.""" + Example: ``r, g, b = np[0]`` + :param key: The pixel number. + :return: The colour tuple. + """ def __len__(self) -> int: - """이 픽셀 스트립의 길이를 불러옵니다. + """Get length of this pixel strip. -Example: ``len(np)``""" \ No newline at end of file + Example: ``len(np)`` + """ diff --git a/lang/ko/typeshed/stdlib/os.pyi b/lang/ko/typeshed/stdlib/os.pyi index 510ffbf..2f2db77 100644 --- a/lang/ko/typeshed/stdlib/os.pyi +++ b/lang/ko/typeshed/stdlib/os.pyi @@ -1,63 +1,73 @@ -"""파일 시스템에 액세스합니다.""" +"""Access the file system. +""" + from typing import Tuple from typing import List def listdir() -> List[str]: - """파일을 나열합니다. + """List files. -Example: ``os.listdir()`` + Example: ``os.listdir()`` -:return: A list of the names of all the files contained within the local -persistent on-device file system.""" + :return: A list of the names of all the files contained within the local + persistent on-device file system. + """ ... def remove(filename: str) -> None: - """파일을 제거(삭제)합니다. + """Remove (delete) a file. -Example: ``os.remove('data.txt')`` + Example: ``os.remove('data.txt')`` -:param filename: 삭제할 파일입니다. + :param filename: The file to delete. -If the file does not exist an ``OSError`` exception will occur.""" + If the file does not exist an ``OSError`` exception will occur. + """ ... def size(filename: str) -> int: - """파일의 크기를 반환합니다. + """Returns the size of a file. -Example: ``os.size('data.txt')`` + Example: ``os.size('data.txt')`` -:param filename: 파일 -:return: The size in bytes. + :param filename: The file + :return: The size in bytes. -If the file does not exist an ``OSError`` exception will occur.""" + If the file does not exist an ``OSError`` exception will occur. + """ class uname_result(Tuple[str, str, str, str, str]): - """``os.uname()``의 결과""" + """Result of ``os.uname()``""" sysname: str - """운영 체제 이름입니다.""" + """Operating system name.""" + nodename: str - """네트워크상의 머신 이름입니다(구현 방법에 따라 정의됨).""" + """Name of machine on network (implementation-defined).""" + release: str - """운영 체제 릴리스입니다.""" + """Operating system release.""" + version: str - """운영 체제 버전입니다.""" + """Operating system version.""" + machine: str - """하드웨어 식별자입니다.""" + """Hardware identifier.""" def uname() -> uname_result: - """현재 운영 시스템을 식별하는 정보를 반환합니다. + """Returns information identifying the current operating system. -Example: ``os.uname()`` + Example: ``os.uname()`` -The return value is an object with five attributes: + The return value is an object with five attributes: -- ``sysname`` - operating system name -- ``nodename`` - name of machine on network (implementation-defined) -- ``release`` - operating system release -- ``version`` - operating system version -- ``machine`` - hardware identifier + - ``sysname`` - operating system name + - ``nodename`` - name of machine on network (implementation-defined) + - ``release`` - operating system release + - ``version`` - operating system version + - ``machine`` - hardware identifier -There is no underlying operating system in MicroPython. As a result the -information returned by the ``uname`` function is mostly useful for -versioning details.""" - ... \ No newline at end of file + There is no underlying operating system in MicroPython. As a result the + information returned by the ``uname`` function is mostly useful for + versioning details. + """ + ... diff --git a/lang/ko/typeshed/stdlib/radio.pyi b/lang/ko/typeshed/stdlib/radio.pyi index 48868c8..8dd0267 100644 --- a/lang/ko/typeshed/stdlib/radio.pyi +++ b/lang/ko/typeshed/stdlib/radio.pyi @@ -1,125 +1,152 @@ -"""내장 라디오를 사용해 micro:bit끼리 통신합니다.""" +"""Communicate between micro:bits with the built-in radio. +""" + from _typeshed import WriteableBuffer from typing import Optional, Tuple + RATE_1MBIT: int -"""초당 1 MBit의 처리율을 지정하는 데 사용하는 상수""" +"""Constant used to indicate a throughput of 1 MBit a second.""" + RATE_2MBIT: int -"""초당 2 MBit의 처리율을 지정하는 데 사용하는 상수.""" +"""Constant used to indicate a throughput of 2 MBit a second.""" def on() -> None: - """라디오를 켭니다. + """Turns the radio on. -Example: ``radio.on()`` + Example: ``radio.on()`` -This needs to be explicitly called since the radio draws power and takes -up memory that you may otherwise need.""" + This needs to be explicitly called since the radio draws power and takes + up memory that you may otherwise need. + """ ... def off() -> None: - """라디오를 꺼 전력과 메모리를 절약합니다. + """Turns off the radio, saving power and memory. -Example: ``radio.off()``""" + Example: ``radio.off()`` + """ ... -def config(length: int=32, queue: int=3, channel: int=7, power: int=6, address: int=1969383796, group: int=0, data_rate: int=RATE_1MBIT) -> None: - """라디오를 설정합니다. - -Example: ``radio.config(group=42)`` - -The default configuration is suitable for most use. - -:param length: (기본값=32) 라디오를 통해 전송되는 메시지의 최대 길이를 바이트로 정의합니다. -최대 251바이트까지 정의할 수 있습니다(S0, LENGTH 및 S1 프리앰블의 경우 254 - 3바이트). -:param queue: (기본값=3) 수신 메시지 대기열에 보관할 수 있는 메시지의 수를 특정합니다. 만약 수신 메시지의 대기열 공간이 부족하다면 수신 메시지는 드롭됩니다. -:param channel: (기본값=7) 임의의 "채널"을 라디오 채널로 설정하는 0부터 83까지의 정수(경계값 포함)입니다. 메시지는 이 채널로 전송되며 이 채널을 통해 받은 메시지만 수신 메시지 대기열에 등록됩니다. 2400MHz 기준으로 각 단계는 1MHz 대역입니다. -:param power: (기본값=6) 0부터 7의 정수값(경계값 포함)으로 메시지를 송출할 때의 신호 강도를 표현합니다. -값이 높을 수록 신호는 강해지지만 장치의 전력을 더 소모합니다. 각 숫자는 다음 dBm(데시벨 밀리와트)값 리스트의 위치로 변환됩니다: -30, -20, -16, -12, -8, -4, 0, 4. -:param address: (기본=0x75626974) 32비트로 표현되는 임의의 이름입니다. 하드웨어 레벨에서 수신 패킷을 필터링하는 데 사용되며 설정한 주소와 일치하는 패킷만 유지합니다. 다른 micro:bit 관련 플랫폼이 사용하는 기본값은 여기에서도 사용됩니다. -:param group: 메시지를 필터링할 때 ``address``와 함께 사용되는 8비트 값(0~255)입니다. 개념상 "address(주소)"는 집/사무실 주소, "group(그룹)"은 해당 주소에서 메시지를 보내고자 하는 인물입니다. -:param data_rate: (default=``radio.RATE_1MBIT``) 데이터 처리율의 속도를 지정합니다. ``radio`` 모듈의 다음 상수 중 하나가 될 수 있습니다: ``RATE_250KBIT``, ``RATE_1MBIT`` 또는 ``RATE_2MBIT``. - -If ``config`` is not called then the defaults described above are assumed.""" +def config( + length: int = 32, + queue: int = 3, + channel: int = 7, + power: int = 6, + address: int = 0x75626974, + group: int = 0, + data_rate: int = RATE_1MBIT, +) -> None: + """Configures the radio. + + Example: ``radio.config(group=42)`` + + The default configuration is suitable for most use. + + :param length: (default=32) defines the maximum length, in bytes, of a message sent via the radio. + It can be up to 251 bytes long (254 - 3 bytes for S0, LENGTH and S1 preamble). + :param queue: (default=3) specifies the number of messages that can be stored on the incoming message queue. + If there are no spaces left on the queue for incoming messages, then the incoming message is dropped. + :param channel: (default=7) an integer value from 0 to 83 (inclusive) that defines an arbitrary "channel" to which the radio is tuned. + Messages will be sent via this channel and only messages received via this channel will be put onto the incoming message queue. Each step is 1MHz wide, based at 2400MHz. + :param power: (default=6) is an integer value from 0 to 7 (inclusive) to indicate the strength of signal used when broadcasting a message. + The higher the value the stronger the signal, but the more power is consumed by the device. The numbering translates to positions in the following list of dBm (decibel milliwatt) values: -30, -20, -16, -12, -8, -4, 0, 4. + :param address: (default=0x75626974) an arbitrary name, expressed as a 32-bit address, that's used to filter incoming packets at the hardware level, keeping only those that match the address you set. + The default used by other micro:bit related platforms is the default setting used here. + :param group: (default=0) an 8-bit value (0-255) used with the ``address`` when filtering messages. + Conceptually, "address" is like a house/office address and "group" is like the person at that address to which you want to send your message. + :param data_rate: (default=``radio.RATE_1MBIT``) indicates the speed at which data throughput takes place. + Can be one of the following constants defined in the ``radio`` module: ``RATE_250KBIT``, ``RATE_1MBIT`` or ``RATE_2MBIT``. + + If ``config`` is not called then the defaults described above are assumed. + """ ... def reset() -> None: - """설정을 기본값으로 초기화합니다. + """Reset the settings to their default values. -Example: ``radio.reset()`` + Example: ``radio.reset()`` -The defaults as as per the ``config`` function above.""" + The defaults as as per the ``config`` function above. + """ ... def send_bytes(message: bytes) -> None: - """바이트가 포함된 메시지를 전송합니다. + """Sends a message containing bytes. -Example: ``radio.send_bytes(b'hello')`` + Example: ``radio.send_bytes(b'hello')`` -:param message: 전송할 바이트입니다.""" + :param message: The bytes to send. + """ ... def receive_bytes() -> Optional[bytes]: - """메시지 대기열에 있는 다음 수신 메시지를 받습니다. + """Receive the next incoming message on the message queue. -Example: ``radio.receive_bytes()`` + Example: ``radio.receive_bytes()`` -:return: The message bytes if any, otherwise ``None``.""" + :return: The message bytes if any, otherwise ``None``. + """ ... def receive_bytes_into(buffer: WriteableBuffer) -> Optional[int]: - """메시지 대기열에 있는 다음 수신 메시지를 버퍼에 복사합니다. + """Copy the next incoming message on the message queue into a buffer. -Example: ``radio.receive_bytes_info(buffer)`` + Example: ``radio.receive_bytes_info(buffer)`` -:param buffer: 목표 버퍼입니다. 메시지가 버퍼보다 크면 메시지가 잘립니다. -:return: ``None`` if there are no pending messages, otherwise it returns the length of the message (which might be more than the length of the buffer).""" + :param buffer: The target buffer. The message is truncated if larger than the buffer. + :return: ``None`` if there are no pending messages, otherwise it returns the length of the message (which might be more than the length of the buffer). + """ ... def send(message: str) -> None: - """메시지 문자열을 전송합니다. + """Sends a message string. -Example: ``radio.send('hello')`` + Example: ``radio.send('hello')`` -This is the equivalent of ``radio.send_bytes(bytes(message, 'utf8'))`` but with ``b'\x01\x00\x01'`` -prepended to the front (to make it compatible with other platforms that target the micro:bit). + This is the equivalent of ``radio.send_bytes(bytes(message, 'utf8'))`` but with ``b'\x01\x00\x01'`` + prepended to the front (to make it compatible with other platforms that target the micro:bit). -:param message: 전송할 문자열입니다.""" + :param message: The string to send. + """ ... def receive() -> Optional[str]: - """``receive_bytes``와 정확히 동일한 작업을 하지만 모든 전송 항목을 반환한다는 차이가 있습니다. + """Works in exactly the same way as ``receive_bytes`` but returns whatever was sent. -Example: ``radio.receive()`` + Example: ``radio.receive()`` -Equivalent to ``str(receive_bytes(), 'utf8')`` but with a check that the the first -three bytes are ``b'\x01\x00\x01'`` (to make it compatible with other platforms that -may target the micro:bit). + Equivalent to ``str(receive_bytes(), 'utf8')`` but with a check that the the first + three bytes are ``b'\x01\x00\x01'`` (to make it compatible with other platforms that + may target the micro:bit). -:return: The message with the prepended bytes stripped and converted to a string. + :return: The message with the prepended bytes stripped and converted to a string. -A ``ValueError`` exception is raised if conversion to string fails.""" + A ``ValueError`` exception is raised if conversion to string fails. + """ ... def receive_full() -> Optional[Tuple[bytes, int, int]]: - """메시지 대기열에 있는 다음 수신 메시지의 정보를 세 종류의 값이 포함된 튜플로 반환합니다. + """Returns a tuple containing three values representing the next incoming message on the message queue. -Example: ``radio.receive_full()`` + Example: ``radio.receive_full()`` -If there are no pending messages then ``None`` is returned. + If there are no pending messages then ``None`` is returned. -The three values in the tuple represent: + The three values in the tuple represent: -- the next incoming message on the message queue as bytes. -- the RSSI (signal strength): a value between 0 (strongest) and -255 (weakest) as measured in dBm. -- a microsecond timestamp: the value returned by ``time.ticks_us()`` when the message was received. + - the next incoming message on the message queue as bytes. + - the RSSI (signal strength): a value between 0 (strongest) and -255 (weakest) as measured in dBm. + - a microsecond timestamp: the value returned by ``time.ticks_us()`` when the message was received. -For example:: + For example:: - details = radio.receive_full() - if details: - msg, rssi, timestamp = details + details = radio.receive_full() + if details: + msg, rssi, timestamp = details -This function is useful for providing information needed for triangulation -and/or trilateration with other micro:bit devices. + This function is useful for providing information needed for triangulation + and/or trilateration with other micro:bit devices. -:return: ``None`` if there is no message, otherwise a tuple of length three with the bytes, strength and timestamp values.""" - ... \ No newline at end of file + :return: ``None`` if there is no message, otherwise a tuple of length three with the bytes, strength and timestamp values. + """ + ... diff --git a/lang/ko/typeshed/stdlib/random.pyi b/lang/ko/typeshed/stdlib/random.pyi index ea623df..a2c2ef3 100644 --- a/lang/ko/typeshed/stdlib/random.pyi +++ b/lang/ko/typeshed/stdlib/random.pyi @@ -1,80 +1,93 @@ -"""무작위 숫자를 생성합니다.""" +"""Generate random numbers. +""" from typing import TypeVar, Sequence, Union, overload def getrandbits(n: int) -> int: - """무작위 비트가 ``n``개 있는 정수를 생성합니다. + """Generate an integer with ``n`` random bits. -Example: ``random.getrandbits(1)`` + Example: ``random.getrandbits(1)`` -:param n: 1~30 사이의 값입니다(경계값 포함).""" + :param n: A value between 1-30 (inclusive). + """ ... def seed(n: int) -> None: - """무작위 숫자 생성기를 초기화합니다. + """Initialize the random number generator. -Example: ``random.seed(0)`` + Example: ``random.seed(0)`` -:param n: 정수 시드 + :param n: The integer seed -This will give you reproducibly deterministic randomness from a given starting -state (``n``).""" + This will give you reproducibly deterministic randomness from a given starting + state (``n``). + """ ... def randint(a: int, b: int) -> int: - """``a``부터 ``b``까지 중 무작위 정수를 선택합니다(경계값 포함). + """Choose a random integer between ``a`` and ``b`` inclusive. -Example: ``random.randint(0, 9)`` + Example: ``random.randint(0, 9)`` -:param a: 범위 시작 값(경계값 포함) -:param b: 범위 종료 값(경계값 포함) + :param a: Start value for the range (inclusive) + :param b: End value for the range (inclusive) -Alias for ``randrange(a, b + 1)``.""" + Alias for ``randrange(a, b + 1)``. + """ ... @overload def randrange(stop: int) -> int: - """0과``stop``사이의 무작위 정수를 선택합니다(경계값 제외). + """Choose a randomly selected integer between zero and up to (but not + including) ``stop``. -Example: ``random.randrange(10)`` + Example: ``random.randrange(10)`` -:param stop: 범위 종료 값(경계값 제외)""" + :param stop: End value for the range (exclusive) + """ ... @overload -def randrange(start: int, stop: int, step: int=1) -> int: - """``range(start, stop, step)``에서 무작위로 정해지는 요소를 선택합니다. +def randrange(start: int, stop: int, step: int = 1) -> int: + """ + Choose a randomly selected element from ``range(start, stop, step)``. -Example: ``random.randrange(0, 10)`` + Example: ``random.randrange(0, 10)`` -:param start: 범위 시작(경계값 포함) -:param stop: 범위 끝(경계값 제외) -:param step: 걸음 수입니다.""" + :param start: The start of the range (inclusive) + :param stop: The end of the range (exclusive) + :param step: The step. + """ ... -_T = TypeVar('_T') + +_T = TypeVar("_T") def choice(seq: Sequence[_T]) -> _T: - """공백이 아닌 ``seq`` 시퀀스로부터 무작위 요소를 선택합니다. + """Choose a random element from the non-empty sequence ``seq``. -Example: ``random.choice([Image.HAPPY, Image.SAD])`` + Example: ``random.choice([Image.HAPPY, Image.SAD])`` -:param seq: 시퀀스입니다. + :param seq: A sequence. -If ``seq`` is empty, raises ``IndexError``.""" + If ``seq`` is empty, raises ``IndexError``. + """ ... def random() -> float: - """[0.0, 1.0) 범위 내의 무작위 부동 소수점 수를 생성합니다. + """Generate a random floating point number in the range [0.0, 1.0). -Example: ``random.random()`` + Example: ``random.random()`` -:return: The random floating point number""" + :return: The random floating point number + """ ... def uniform(a: float, b: float) -> float: - """경계값을 포함한 ``a``와 ``b``사이의 무작위 부동 소수점 수를 반환합니다. + """ + Return a random floating point number between ``a`` and ``b`` inclusive. -Example: ``random.uniform(0, 9)`` + Example: ``random.uniform(0, 9)`` -:param a: 범위 시작 값(경계값 포함) -:param b: 범위 종료 값(경계값 포함)""" - ... \ No newline at end of file + :param a: Start value for the range (inclusive) + :param b: End value for the range (inclusive) + """ + ... diff --git a/lang/ko/typeshed/stdlib/speech.pyi b/lang/ko/typeshed/stdlib/speech.pyi index 7a58115..349d188 100644 --- a/lang/ko/typeshed/stdlib/speech.pyi +++ b/lang/ko/typeshed/stdlib/speech.pyi @@ -1,79 +1,106 @@ -"""micro:bit이 말하고 노래부르고 소리를 재생하게 합니다.""" +"""Make the micro:bit talk, sing and make other speech like sounds. +""" + from typing import Optional from .microbit import MicroBitDigitalPin, pin0 def translate(words: str) -> str: - """영단어를 음소로 변환합니다. + """Translate English words to phonemes. -Example: ``speech.translate('hello world')`` + Example: ``speech.translate('hello world')`` -:param words: 영단어 문자열입니다. -:return: A string containing a best guess at the appropriate phonemes to pronounce. -The output is generated from this `text to phoneme translation table `_. + :param words: A string of English words. + :return: A string containing a best guess at the appropriate phonemes to pronounce. + The output is generated from this `text to phoneme translation table `_. -This function should be used to generate a first approximation of phonemes -that can be further hand-edited to improve accuracy, inflection and -emphasis. + This function should be used to generate a first approximation of phonemes + that can be further hand-edited to improve accuracy, inflection and + emphasis. -See `the online documentation `_ for detailed information.""" + See `the online documentation `_ for detailed information. + """ ... -def pronounce(phonemes: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: Optional[MicroBitDigitalPin]=pin0) -> None: - """음소를 발음합니다. - -Example: ``speech.pronounce(' /HEHLOW WERLD')`` - -:param phonemes: 발음할 음소의 문자열 -:param pitch: (앞-뒤 기울기) 목소리의 음높이를 표현하는 숫자 -:param speed: 목소리의 속도를 표현하는 숫자 -:param mouth: 목소리의 입 모양을 표현하는 숫자 -:param throat: 목소리의 목 모양을 표현하는 숫자 -:param pin: (핀) ``pin0``의 기본값을 덮어쓰고 출력 핀을 특정하는 인자입니다(선택 사항). -핀에서 사운드를 재생하기 싫다면 ``pin=None``을 사용할 수 있습니다. micro:bit V2 전용입니다. - -Override the optional pitch, speed, mouth and throat settings to change the -timbre (quality) of the voice. - -See `the online documentation `_ for detailed information.""" +def pronounce( + phonemes: str, + pitch: int = 64, + speed: int = 72, + mouth: int = 128, + throat: int = 128, + pin: Optional[MicroBitDigitalPin] = pin0, +) -> None: + """Pronounce phonemes. + + Example: ``speech.pronounce(' /HEHLOW WERLD')`` + + :param phonemes: The string of phonemes to pronounce + :param pitch: A number representing the pitch of the voice + :param speed: A number representing the speed of the voice + :param mouth: A number representing the mouth of the voice + :param throat: A number representing the throat of the voice + :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. + If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. + + Override the optional pitch, speed, mouth and throat settings to change the + timbre (quality) of the voice. + + See `the online documentation `_ for detailed information. + """ ... -def say(words: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: MicroBitDigitalPin=pin0) -> None: - """영어 단어를 말합니다. - -Example: ``speech.say('hello world')`` - -:param words: 말할 단어의 문자열입니다. -:param pitch: (앞-뒤 기울기) 목소리의 음높이를 표현하는 숫자 -:param speed: 목소리의 속도를 표현하는 숫자 -:param mouth: 목소리의 입 모양을 표현하는 숫자 -:param throat: 목소리의 목 모양을 표현하는 숫자 -:param pin: (핀) ``pin0``의 기본값을 덮어쓰고 출력 핀을 특정하는 인자입니다(선택 사항). -핀에서 사운드를 재생하기 싫다면 ``pin=None``을 사용할 수 있습니다. micro:bit V2 전용입니다. - -The result is semi-accurate for English. Override the optional pitch, speed, -mouth and throat settings to change the timbre (quality) of the voice. - -This is a short-hand equivalent of: -``speech.pronounce(speech.translate(words))`` - -See `the online documentation `_ for detailed information.""" +def say( + words: str, + pitch: int = 64, + speed: int = 72, + mouth: int = 128, + throat: int = 128, + pin: MicroBitDigitalPin = pin0, +) -> None: + """Say English words. + + Example: ``speech.say('hello world')`` + + :param words: The string of words to say. + :param pitch: A number representing the pitch of the voice + :param speed: A number representing the speed of the voice + :param mouth: A number representing the mouth of the voice + :param throat: A number representing the throat of the voice + :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. + If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. + + The result is semi-accurate for English. Override the optional pitch, speed, + mouth and throat settings to change the timbre (quality) of the voice. + + This is a short-hand equivalent of: + ``speech.pronounce(speech.translate(words))`` + + See `the online documentation `_ for detailed information. + """ ... -def sing(phonemes: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: MicroBitDigitalPin=pin0) -> None: - """음소를 노래합니다. - -Example: ``speech.sing(' /HEHLOW WERLD')`` - -:param phonemes: 노래할 단어 문자열입니다. -:param pitch: (앞-뒤 기울기) 목소리의 음높이를 표현하는 숫자 -:param speed: 목소리의 속도를 표현하는 숫자 -:param mouth: 목소리의 입 모양을 표현하는 숫자 -:param throat: 목소리의 목 모양을 표현하는 숫자 -:param pin: (핀) ``pin0``의 기본값을 덮어쓰고 출력 핀을 특정하는 인자입니다(선택 사항). -핀에서 사운드를 재생하기 싫다면 ``pin=None``을 사용할 수 있습니다. micro:bit V2 전용입니다. - -Override the optional pitch, speed, mouth and throat settings to change -the timbre (quality) of the voice. - -See `the online documentation `_ for detailed information.""" - ... \ No newline at end of file +def sing( + phonemes: str, + pitch: int = 64, + speed: int = 72, + mouth: int = 128, + throat: int = 128, + pin: MicroBitDigitalPin = pin0, +) -> None: + """Sing phonemes. + + Example: ``speech.sing(' /HEHLOW WERLD')`` + + :param phonemes: The string of words to sing. + :param pitch: A number representing the pitch of the voice + :param speed: A number representing the speed of the voice + :param mouth: A number representing the mouth of the voice + :param throat: A number representing the throat of the voice + :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. + If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. + + Override the optional pitch, speed, mouth and throat settings to change + the timbre (quality) of the voice. + + See `the online documentation `_ for detailed information. + """ + ... diff --git a/lang/ko/typeshed/stdlib/struct.pyi b/lang/ko/typeshed/stdlib/struct.pyi index 03c8b8c..53b3e0b 100644 --- a/lang/ko/typeshed/stdlib/struct.pyi +++ b/lang/ko/typeshed/stdlib/struct.pyi @@ -1,56 +1,65 @@ -"""원시 데이터 유형을 패킹하고 언패킹합니다.""" +"""Pack and unpack primitive data types. +""" + from _typeshed import ReadableBuffer, WriteableBuffer from typing import Any, Tuple, Union def calcsize(fmt: str) -> int: - """주어진 ``fmt``를 저장하는 데 필요한 바이트의 수를 불러옵니다. + """Get the number of bytes needed to store the given ``fmt``. -Example: ``struct.calcsize('hf')`` + Example: ``struct.calcsize('hf')`` -:param fmt: 형식 문자열입니다. -:return The number of bytes needed to store such a value.""" + :param fmt: A format string. + :return The number of bytes needed to store such a value. + """ ... def pack(fmt: str, v1: Any, *vn: Any) -> bytes: - """형식 문자열에 따라 값을 패킹합니다. + """Pack values according to a format string. -Example: ``struct.pack('hf', 1, 3.1415)`` + Example: ``struct.pack('hf', 1, 3.1415)`` -:param fmt: 형식 문자열입니다. -:param v1: 첫 값입니다. -:param *vn: 남은 값입니다. -:return A bytes object encoding the values.""" + :param fmt: The format string. + :param v1: The first value. + :param *vn: The remaining values. + :return A bytes object encoding the values. + """ ... -def pack_into(fmt: str, buffer: WriteableBuffer, offset: int, v1: Any, *vn: Any) -> None: - """형식 문자열에 따라 값을 패킹합니다. +def pack_into( + fmt: str, buffer: WriteableBuffer, offset: int, v1: Any, *vn: Any +) -> None: + """Pack values according to a format string. -Example: ``struct.pack_info('hf', buffer, 1, 3.1415)`` + Example: ``struct.pack_info('hf', buffer, 1, 3.1415)`` -:param fmt: 형식 문자열입니다. -:param buffer: 작성할 목표 버퍼입니다. -:param offset: 버퍼에 적용할 오프셋입니다. 음수를 입력하면 버퍼 끝부터 셀 수 있습니다. -:param v1: 첫 값입니다. -:param *vn: 남은 값입니다.""" + :param fmt: The format string. + :param buffer: The target buffer to write into. + :param offset: The offset into the buffer. May be negative to count from the end of the buffer. + :param v1: The first value. + :param *vn: The remaining values. + """ ... def unpack(fmt: str, data: ReadableBuffer) -> Tuple[Any, ...]: - """형식 문자열에 따라 데이터를 언패킹합니다. + """Unpack data according to a format string. -Example: ``v1, v2 = struct.unpack('hf', buffer)`` + Example: ``v1, v2 = struct.unpack('hf', buffer)`` -:param fmt: 형식 문자열입니다. -:param data: 데이터입니다. -:return: A tuple of the unpacked values.""" + :param fmt: The format string. + :param data: The data. + :return: A tuple of the unpacked values. + """ ... -def unpack_from(fmt: str, buffer: ReadableBuffer, offset: int=0) -> Tuple: - """형식 문자열에 따라 버퍼로부터 데이터를 언패킹합니다. +def unpack_from(fmt: str, buffer: ReadableBuffer, offset: int = 0) -> Tuple: + """Unpack data from a buffer according to a format string. -Example: ``v1, v2 = struct.unpack_from('hf', buffer)`` + Example: ``v1, v2 = struct.unpack_from('hf', buffer)`` -:param fmt: 형식 문자열입니다. -:param buffer: 읽을 소스 버퍼입니다. -:param offset: (오프셋) 버퍼에 적용할 오프셋입니다. 음수를 입력하면 버퍼 끝부터 셀 수 있습니다. -:return: A tuple of the unpacked values.""" - ... \ No newline at end of file + :param fmt: The format string. + :param buffer: The source buffer to read from. + :param offset: The offset into the buffer. May be negative to count from the end of the buffer. + :return: A tuple of the unpacked values. + """ + ... diff --git a/lang/ko/typeshed/stdlib/sys.pyi b/lang/ko/typeshed/stdlib/sys.pyi index 73473c5..320bac9 100644 --- a/lang/ko/typeshed/stdlib/sys.pyi +++ b/lang/ko/typeshed/stdlib/sys.pyi @@ -1,36 +1,43 @@ -"""시스템 특정 함수""" +"""System specific functions""" + from typing import Any, Dict, List, NoReturn, TextIO, Tuple -def exit(retval: object=...) -> NoReturn: - """주어진 종료 코드로 현재 프로그램을 종료합니다. +def exit(retval: object = ...) -> NoReturn: + """Terminate current program with a given exit code. -Example: ``sys.exit(1)`` + Example: ``sys.exit(1)`` -This function raises a ``SystemExit`` exception. If an argument is given, its -value given as an argument to ``SystemExit``. + This function raises a ``SystemExit`` exception. If an argument is given, its + value given as an argument to ``SystemExit``. -:param retval: 종료 코드 또는 메시지입니다.""" + :param retval: The exit code or message. + """ ... def print_exception(exc: Exception) -> None: - """트레이스백으로 예외를 프린트합니다. + """ + Print an exception with a traceback. + + Example: ``sys.print_exception(e)`` -Example: ``sys.print_exception(e)`` + :param exc: The exception to print -:param exc: 프린트할 예외 + This is simplified version of a function which appears in the + ``traceback`` module in CPython. + """ -This is simplified version of a function which appears in the -``traceback`` module in CPython.""" argv: List[str] -"""현재 프로그램과 같이 시작된 인자의 가변 리스트입니다.""" +"""A mutable list of arguments the current program was started with.""" + byteorder: str -"""시스템의 바이트 순서를 (``"little"`` 또는 ``"big"``)으로 정렬합니다.""" +"""The byte order of the system (``"little"`` or ``"big"``).""" class _implementation: name: str version: Tuple[int, int, int] + implementation: _implementation -"""현재 Python 구현에 관한 정보가 담긴 개체 +"""Object with information about the current Python implementation. For MicroPython, it has following attributes: @@ -44,9 +51,13 @@ minimal ports). CPython mandates more attributes for this object, but the actual useful bare minimum is implemented in MicroPython. """ + maxsize: int """ -현재 플랫폼에서 자연 정수 유형이 지원할 수 있는 최대 값, 또는 값이 플랫폼의 최대 값보다 작다면 MicroPython 정수 유형으로 표현할 수 있는 최대 값입니다(long int를 지원하지 않는 MicroPython 포트의 경우). +Maximum value which a native integer type can hold on the current platform, +or maximum value representable by MicroPython integer type, if it's smaller +than platform max value (that is the case for MicroPython ports without +long int support). This attribute is useful for detecting "bitness" of a platform (32-bit vs 64-bit, etc.). It's recommended to not compare this attribute to some @@ -66,14 +77,17 @@ value directly, but instead count number of bits in it:: # (e.g. 31) due to peculiarities described above, so use "> 16", # "> 32", "> 64" style of comparisons. """ + modules: Dict[str, Any] -"""로드된 모듈의 딕셔너리입니다. +"""Dictionary of loaded modules. On some ports, it may not include builtin modules.""" + path: List[str] -"""불러온 모듈을 검색하기 위한 딕셔너리 가변 리스트입니다.""" +"""A mutable list of directories to search for imported modules.""" + platform: str -"""MicroPython이 실행되고 있는 플랫폼입니다. +"""The platform that MicroPython is running on. For OS/RTOS ports, this is usually an identifier of the OS, e.g. ``"linux"``. For baremetal ports it is an identifier of a board, e.g. ``"pyboard"`` for @@ -83,11 +97,13 @@ distinguish one board from another. If you need to check whether your program runs on MicroPython (vs other Python implementation), use ``sys.implementation`` instead. """ + version: str -"""이 구현이 준수하는 Python 언어 버전을 문자열로 제공합니다.""" +"""Python language version that this implementation conforms to, as a string.""" + version_info: Tuple[int, int, int] -"""이 구현이 준수하는 Python 언어 버전을 정수 튜플로 제공합니다. +"""Python language version that this implementation conforms to, as a tuple of ints. Only the first three version numbers (major, minor, micro) are supported and they can be referenced only by index, not by name. -""" \ No newline at end of file +""" diff --git a/lang/ko/typeshed/stdlib/time.pyi b/lang/ko/typeshed/stdlib/time.pyi index fe2abeb..598c483 100644 --- a/lang/ko/typeshed/stdlib/time.pyi +++ b/lang/ko/typeshed/stdlib/time.pyi @@ -1,111 +1,132 @@ -"""시간을 측정하고 프로그램에 지연을 부여합니다.""" +"""Measure time and add delays to programs. +""" + from typing import Union def sleep(seconds: Union[int, float]) -> None: - """초 단위로 지연을 부여합니다. + """ + Delay a number of seconds. -Example: ``time.sleep(1)`` + Example: ``time.sleep(1)`` -:param seconds: 절전 상태를 설정할 초 단위입니다. -초 단위 미만으로 절전 상태를 설정하려면 부동 소수점 수를 사용하세요.""" + :param seconds: The number of seconds to sleep for. + Use a floating-point number to sleep for a fractional number of seconds. + """ ... def sleep_ms(ms: int) -> None: - """밀리초 단위로 지연을 부여합니다. + """ + Delay for given number of milliseconds. -Example: ``time.sleep_ms(1_000_000)`` + Example: ``time.sleep_ms(1_000_000)`` -:param ms: 밀리초 단위의 지연 시간입니다(>= 0).""" + :param ms: The number of milliseconds delay (>= 0). + """ ... def sleep_us(us: int) -> None: - """마이크로초 단위로 지연을 부여합니다. + """ + Delay for given number of microseconds. -Example: ``time.sleep_us(1000)`` + Example: ``time.sleep_us(1000)`` -:param us: 마이크로초 단위의 지연 시간입니다(>= 0).""" + :param us: The number of microseconds delay (>= 0). + """ ... def ticks_ms() -> int: - """임의의 레퍼런스 포인트가 있는 점진적으로 증가하는 밀리초 카운터로, 일부 값을 따라 래핑합니다. + """ + Get an increasing, millisecond counter with an arbitrary reference point, + that wraps around after some value. -Example: ``time.ticks_ms()`` + Example: ``time.ticks_ms()`` -:return: The counter value in milliseconds.""" + :return: The counter value in milliseconds. + """ ... def ticks_us() -> int: - """임의의 레퍼런스 포인트가 있는 점진적으로 증가하는 마이크로초 카운터로, 일부 값을 따라 래핑합니다. + """ + Get an increasing, microsecond counter with an arbitrary reference point, + that wraps around after some value. -Example: ``time.ticks_us()`` + Example: ``time.ticks_us()`` -:return: The counter value in microseconds.""" + :return: The counter value in microseconds. + """ ... def ticks_add(ticks: int, delta: int) -> int: - """주어진 숫자에 따라 틱 값을 오프셋으로 사용합니다. 양수나 음수일 수 있습니다. + """ + Offset ticks value by a given number, which can be either positive or + negative. -Example: ``time.ticks_add(time.ticks_ms(), 200)`` + Example: ``time.ticks_add(time.ticks_ms(), 200)`` -Given a ticks value, this function allows to calculate ticks -value delta ticks before or after it, following modular-arithmetic -definition of tick values. + Given a ticks value, this function allows to calculate ticks + value delta ticks before or after it, following modular-arithmetic + definition of tick values. -:param ticks: 틱 값 -:param delta: 정수 오프셋 + :param ticks: A ticks value + :param delta: An integer offset -Example:: + Example:: - # Find out what ticks value there was 100ms ago - print(ticks_add(time.ticks_ms(), -100)) + # Find out what ticks value there was 100ms ago + print(ticks_add(time.ticks_ms(), -100)) - # Calculate deadline for operation and test for it - deadline = ticks_add(time.ticks_ms(), 200) - while ticks_diff(deadline, time.ticks_ms()) > 0: - do_a_little_of_something() + # Calculate deadline for operation and test for it + deadline = ticks_add(time.ticks_ms(), 200) + while ticks_diff(deadline, time.ticks_ms()) > 0: + do_a_little_of_something() - # Find out TICKS_MAX used by this port - print(ticks_add(0, -1))""" + # Find out TICKS_MAX used by this port + print(ticks_add(0, -1)) + """ ... def ticks_diff(ticks1: int, ticks2: int) -> int: - """``time.ticks_ms()`` 또는 ``ticks_us()``에서 반환된 값 사이의 틱 차이를 측정합니다. 서명된 값은 래핑될 수 있습니다. - -Example: ``time.ticks_diff(scheduled_time, now)`` - -:param ticks1: 뺄 값 -:param ticks2: 뺄 값 - -The argument order is the same as for subtraction operator, -``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. - -``ticks_diff()`` is designed to accommodate various usage -patterns, among them: - -Polling with timeout. In this case, the order of events is known, and you -will deal only with positive results of :func:`time.ticks_diff()`:: - - # Wait for GPIO pin to be asserted, but at most 500us - start = time.ticks_us() - while pin.value() == 0: - if time.ticks_diff(time.ticks_us(), start) > 500: - raise TimeoutError - - -Scheduling events. In this case, :func:`time.ticks_diff()` result may be -negative if an event is overdue:: - - # This code snippet is not optimized - now = time.ticks_ms() - scheduled_time = task.scheduled_time() - if ticks_diff(scheduled_time, now) > 0: - print("Too early, let's nap") - sleep_ms(ticks_diff(scheduled_time, now)) - task.run() - elif ticks_diff(scheduled_time, now) == 0: - print("Right at time!") - task.run() - elif ticks_diff(scheduled_time, now) < 0: - print("Oops, running late, tell task to run faster!") - task.run(run_faster=True)""" - ... \ No newline at end of file + """ + Measure ticks difference between values returned from + ``time.ticks_ms()`` or ``ticks_us()``, as a signed value + which may wrap around. + + Example: ``time.ticks_diff(scheduled_time, now)`` + + :param ticks1: The value to subtract from + :param ticks2: The value to subtract + + The argument order is the same as for subtraction operator, + ``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. + + ``ticks_diff()`` is designed to accommodate various usage + patterns, among them: + + Polling with timeout. In this case, the order of events is known, and you + will deal only with positive results of :func:`time.ticks_diff()`:: + + # Wait for GPIO pin to be asserted, but at most 500us + start = time.ticks_us() + while pin.value() == 0: + if time.ticks_diff(time.ticks_us(), start) > 500: + raise TimeoutError + + + Scheduling events. In this case, :func:`time.ticks_diff()` result may be + negative if an event is overdue:: + + # This code snippet is not optimized + now = time.ticks_ms() + scheduled_time = task.scheduled_time() + if ticks_diff(scheduled_time, now) > 0: + print("Too early, let's nap") + sleep_ms(ticks_diff(scheduled_time, now)) + task.run() + elif ticks_diff(scheduled_time, now) == 0: + print("Right at time!") + task.run() + elif ticks_diff(scheduled_time, now) < 0: + print("Oops, running late, tell task to run faster!") + task.run(run_faster=True) + """ + ... diff --git a/lang/lol/typeshed/stdlib/gc.pyi b/lang/lol/typeshed/stdlib/gc.pyi index d91bd02..1370abf 100644 --- a/lang/lol/typeshed/stdlib/gc.pyi +++ b/lang/lol/typeshed/stdlib/gc.pyi @@ -1,68 +1,73 @@ -"""crwdns328732:0crwdne328732:0 (crwdns328730:0crwdne328730:0)""" +"""Control the garbage collector""" + from typing import overload def enable() -> None: - """crwdns328736:0crwdne328736:0 (crwdns328734:0crwdne328734:0)""" + """Enable automatic garbage collection.""" ... def disable() -> None: - """crwdns328740:0crwdne328740:0 (crwdns328738:0crwdne328738:0) + """Disable automatic garbage collection. -Heap memory can still be allocated, -and garbage collection can still be initiated manually using ``gc.collect``.""" + Heap memory can still be allocated, + and garbage collection can still be initiated manually using ``gc.collect``.""" def collect() -> None: - """crwdns328744:0crwdne328744:0 (crwdns328742:0crwdne328742:0)""" + """Run a garbage collection.""" ... def mem_alloc() -> int: - """crwdns328748:0crwdne328748:0 (crwdns328746:0crwdne328746:0) + """Get the number of bytes of heap RAM that are allocated. -:return: The number of bytes allocated. + :return: The number of bytes allocated. -This function is MicroPython extension.""" + This function is MicroPython extension. + """ ... def mem_free() -> int: - """crwdns328752:0crwdne328752:0 (crwdns328750:0crwdne328750:0) + """Get the number of bytes of available heap RAM, or -1 if this amount is not known. -:return: The number of bytes free. + :return: The number of bytes free. -This function is MicroPython extension.""" + This function is MicroPython extension. + """ ... @overload def threshold() -> int: - """crwdns328756:0crwdne328756:0 (crwdns328754:0crwdne328754:0) + """Query the additional GC allocation threshold. -:return: The GC allocation threshold. + :return: The GC allocation threshold. -This function is a MicroPython extension. CPython has a similar -function - ``set_threshold()``, but due to different GC -implementations, its signature and semantics are different.""" + This function is a MicroPython extension. CPython has a similar + function - ``set_threshold()``, but due to different GC + implementations, its signature and semantics are different. + """ ... @overload def threshold(amount: int) -> None: - """crwdns328760:0crwdne328760:0 (crwdns328758:0crwdne328758:0) - -Normally, a collection is triggered only when a new allocation -cannot be satisfied, i.e. on an out-of-memory (OOM) condition. -If this function is called, in addition to OOM, a collection -will be triggered each time after ``amount`` bytes have been -allocated (in total, since the previous time such an amount of bytes -have been allocated). ``amount`` is usually specified as less than the -full heap size, with the intention to trigger a collection earlier than when the -heap becomes exhausted, and in the hope that an early collection will prevent -excessive memory fragmentation. This is a heuristic measure, the effect -of which will vary from application to application, as well as -the optimal value of the ``amount`` parameter. - -A value of -1 means a disabled allocation threshold. - -This function is a MicroPython extension. CPython has a similar -function - ``set_threshold()``, but due to different GC -implementations, its signature and semantics are different. - -:param amount: (crwdns328762:0crwdne328762:0) crwdns328764:0crwdne328764:0""" - ... \ No newline at end of file + """Set the additional GC allocation threshold. + + Normally, a collection is triggered only when a new allocation + cannot be satisfied, i.e. on an out-of-memory (OOM) condition. + If this function is called, in addition to OOM, a collection + will be triggered each time after ``amount`` bytes have been + allocated (in total, since the previous time such an amount of bytes + have been allocated). ``amount`` is usually specified as less than the + full heap size, with the intention to trigger a collection earlier than when the + heap becomes exhausted, and in the hope that an early collection will prevent + excessive memory fragmentation. This is a heuristic measure, the effect + of which will vary from application to application, as well as + the optimal value of the ``amount`` parameter. + + A value of -1 means a disabled allocation threshold. + + This function is a MicroPython extension. CPython has a similar + function - ``set_threshold()``, but due to different GC + implementations, its signature and semantics are different. + + :param amount: The number of bytes after which a garbage collection should be triggered. + """ + ... diff --git a/lang/lol/typeshed/stdlib/log.pyi b/lang/lol/typeshed/stdlib/log.pyi index 725cc6e..c9870fa 100644 --- a/lang/lol/typeshed/stdlib/log.pyi +++ b/lang/lol/typeshed/stdlib/log.pyi @@ -1,89 +1,104 @@ -"""crwdns328768:0crwdne328768:0 (crwdns328766:0crwdne328766:0)""" +"""Log data to your micro:bit V2.""" + from typing import Literal, Mapping, Optional, Union, overload + MILLISECONDS = 1 -"""crwdns328772:0crwdne328772:0 (crwdns328770:0crwdne328770:0)""" +"""Milliseconds timestamp format.""" + SECONDS = 10 -"""crwdns328776:0crwdne328776:0 (crwdns328774:0crwdne328774:0)""" +"""Seconds timestamp format.""" + MINUTES = 600 -"""crwdns328780:0crwdne328780:0 (crwdns328778:0crwdne328778:0)""" +"""Minutes timestamp format.""" + HOURS = 36000 -"""crwdns328784:0crwdne328784:0 (crwdns328782:0crwdne328782:0)""" +"""Hours timestamp format.""" + DAYS = 864000 -"""crwdns328788:0crwdne328788:0 (crwdns328786:0crwdne328786:0)""" +"""Days timestamp format.""" -def set_labels(*labels: str, timestamp: Optional[Literal[1, 10, 36000, 864000]]=SECONDS) -> None: - """crwdns328792:0crwdne328792:0 (crwdns328790:0crwdne328790:0) +def set_labels( + *labels: str, timestamp: Optional[Literal[1, 10, 36000, 864000]] = SECONDS +) -> None: + """Set up the log file header. -Example: ``log.set_labels('X', 'Y', 'Z', timestamp=log.MINUTES)`` + Example: ``log.set_labels('X', 'Y', 'Z', timestamp=log.MINUTES)`` -Ideally this function should be called a single time, before any data is -logged, to configure the data table header once. + Ideally this function should be called a single time, before any data is + logged, to configure the data table header once. -If a log file already exists when the program starts, or if this function -is called multiple times, it will check the labels already defined in the -log file. If this function call contains any new labels not already -present, it will generate a new header row with the additional columns. + If a log file already exists when the program starts, or if this function + is called multiple times, it will check the labels already defined in the + log file. If this function call contains any new labels not already + present, it will generate a new header row with the additional columns. -By default the first column contains a timestamp for each row. The time -unit can be selected via the timestamp argument. + By default the first column contains a timestamp for each row. The time + unit can be selected via the timestamp argument. -:param *labels: (crwdns335772:0crwdne335772:0) crwdns335774:0crwdne335774:0 -:param timestamp: (crwdns328798:0crwdne328798:0) crwdns335776:0``log.MILLISECONDS``crwdnd335776:0``log.SECONDS``crwdnd335776:0``log.MINUTES``crwdnd335776:0``log.HOURS``crwdnd335776:0``log.DAYS``crwdnd335776:0``None``crwdnd335776:0``log.SECONDS``crwdne335776:0""" + :param *labels: Any number of positional arguments, each corresponding to an entry in the log header. + :param timestamp: Select the timestamp unit that will be automatically added as the first column in every row. Timestamp values can be one of ``log.MILLISECONDS``, ``log.SECONDS``, ``log.MINUTES``, ``log.HOURS``, ``log.DAYS`` or ``None`` to disable the timestamp. The default value is ``log.SECONDS``. + """ ... @overload -def add(data_dictionary: Optional[Mapping[str, Union[str, int, float]]]) -> None: - """crwdns328804:0crwdne328804:0 (crwdns328802:0crwdne328802:0) +def add( + data_dictionary: Optional[Mapping[str, Union[str, int, float]]], +) -> None: + """Add a data row to the log by passing a dictionary of headers and values. -Example: ``log.add({ 'temp': temperature() })`` + Example: ``log.add({ 'temp': temperature() })`` -Each call to this function adds a row to the log. + Each call to this function adds a row to the log. -New labels not previously specified via the set_labels function, or by a -previous call to this function, will trigger a new header entry to be added -to the log with the extra labels. + New labels not previously specified via the set_labels function, or by a + previous call to this function, will trigger a new header entry to be added + to the log with the extra labels. -Labels previously specified and not present in a call to this function will -be skipped with an empty value in the log row. + Labels previously specified and not present in a call to this function will + be skipped with an empty value in the log row. -:param data_dictionary: (crwdns335778:0crwdne335778:0) crwdns335780:0crwdne335780:0""" + :param data_dictionary: The data to log as a dictionary with a key for each header. + """ ... @overload def add(**kwargs: Union[str, int, float]) -> None: - """crwdns328812:0crwdne328812:0 (crwdns328810:0crwdne328810:0) + """Add a data row to the log using keyword arguments. -Example: ``log.add(temp=temperature())`` + Example: ``log.add(temp=temperature())`` -Each call to this function adds a row to the log. + Each call to this function adds a row to the log. -New labels not previously specified via the set_labels function, or by a -previous call to this function, will trigger a new header entry to be added -to the log with the extra labels. + New labels not previously specified via the set_labels function, or by a + previous call to this function, will trigger a new header entry to be added + to the log with the extra labels. -Labels previously specified and not present in a call to this function will -be skipped with an empty value in the log row.""" + Labels previously specified and not present in a call to this function will + be skipped with an empty value in the log row. + """ ... def delete(full=False): - """crwdns328816:0crwdne328816:0 (crwdns328814:0crwdne328814:0) + """Deletes the contents of the log, including headers. -Example: ``log.delete()`` + Example: ``log.delete()`` -To add the log headers again the ``set_labels`` function should to be called after this function. + To add the log headers again the ``set_labels`` function should to be called after this function. -There are two erase modes; “full” completely removes the data from the physical storage, -and “fast” invalidates the data without removing it. + There are two erase modes; “full” completely removes the data from the physical storage, + and “fast” invalidates the data without removing it. -:param full: (crwdns328818:0crwdne328818:0) crwdns335782:0``True``crwdnd335782:0``False``crwdne335782:0""" + :param full: ``True`` selects a “full” erase and ``False`` selects the “fast” erase method. + """ ... def set_mirroring(serial: bool): - """crwdns335784:0crwdne335784:0 (crwdns328822:0crwdne328822:0) + """Configure mirroring of the data logging activity to the serial output. -Example: ``log.set_mirroring(True)`` + Example: ``log.set_mirroring(True)`` -Serial mirroring is disabled by default. When enabled, it will print to serial each row logged into the log file. + Serial mirroring is disabled by default. When enabled, it will print to serial each row logged into the log file. -:param serial: (crwdns328826:0crwdne328826:0) crwdns335786:0``True``crwdne335786:0""" - ... \ No newline at end of file + :param serial: ``True`` enables mirroring data to the serial output. + """ + ... diff --git a/lang/lol/typeshed/stdlib/machine.pyi b/lang/lol/typeshed/stdlib/machine.pyi index 6dd178c..2e82f5b 100644 --- a/lang/lol/typeshed/stdlib/machine.pyi +++ b/lang/lol/typeshed/stdlib/machine.pyi @@ -1,84 +1,97 @@ -"""crwdns328832:0crwdne328832:0 (crwdns328830:0crwdne328830:0)""" +"""Low-level utilities. +""" from typing import Any from .microbit import MicroBitDigitalPin def unique_id() -> bytes: - """crwdns328836:0crwdne328836:0 (crwdns328834:0crwdne328834:0) + """Get a byte string with a unique identifier of a board. -Example: ``machine.unique_id()`` + Example: ``machine.unique_id()`` -:return: An identifier that varies from one board instance to another.""" + :return: An identifier that varies from one board instance to another. + """ ... def reset() -> None: - """crwdns328840:0crwdne328840:0 (crwdns328838:0crwdne328838:0) + """Reset the device in a manner similar to pushing the external RESET button. -Example: ``machine.reset()``""" + Example: ``machine.reset()`` + """ ... def freq() -> int: - """crwdns328844:0crwdne328844:0 (crwdns328842:0crwdne328842:0) + """Get the CPU frequency in hertz. -Example: ``machine.freq()`` + Example: ``machine.freq()`` -:return: The CPU frequency.""" + :return: The CPU frequency. + """ ... def disable_irq() -> Any: - """crwdns328848:0crwdne328848:0 (crwdns328846:0crwdne328846:0) + """Disable interrupt requests. -Example: ``interrupt_state = machine.disable_irq()`` + Example: ``interrupt_state = machine.disable_irq()`` -:return: the previous IRQ state which should be considered an opaque value + :return: the previous IRQ state which should be considered an opaque value -The return value should be passed to the ``enable_irq`` function to restore -interrupts to their original state.""" + The return value should be passed to the ``enable_irq`` function to restore + interrupts to their original state. + """ ... def enable_irq(state: Any) -> None: - """crwdns328852:0crwdne328852:0 (crwdns328850:0crwdne328850:0) + """Re-enable interrupt requests. -Example: ``machine.enable_irq(interrupt_state)`` + Example: ``machine.enable_irq(interrupt_state)`` -:param state: (crwdns328854:0crwdne328854:0) crwdns328856:0``disable_irq``crwdne328856:0""" + :param state: The value that was returned from the most recent call to the ``disable_irq`` function. + """ ... -def time_pulse_us(pin: MicroBitDigitalPin, pulse_level: int, timeout_us: int=1000000) -> int: - """crwdns328860:0crwdne328860:0 (crwdns328858:0crwdne328858:0) +def time_pulse_us( + pin: MicroBitDigitalPin, pulse_level: int, timeout_us: int = 1000000 +) -> int: + """Time a pulse on a pin. -Example: ``time_pulse_us(pin0, 1)`` + Example: ``time_pulse_us(pin0, 1)`` -If the current input value of the pin is different to ``pulse_level``, the -function first waits until the pin input becomes equal to -``pulse_level``, then times the duration that the pin is equal to -``pulse_level``. If the pin is already equal to ``pulse_level`` then timing -starts straight away. + If the current input value of the pin is different to ``pulse_level``, the + function first waits until the pin input becomes equal to + ``pulse_level``, then times the duration that the pin is equal to + ``pulse_level``. If the pin is already equal to ``pulse_level`` then timing + starts straight away. -:param pin: (crwdns328862:0crwdne328862:0) crwdns328864:0crwdne328864:0 -:param pulse_level: (crwdns328866:0crwdne328866:0) crwdns328868:0crwdne328868:0 -:param timeout_us: (crwdns328870:0crwdne328870:0) crwdns328872:0crwdne328872:0 -:return: The duration of the pulse in microseconds, or -1 for a timeout waiting for the level to match ``pulse_level``, or -2 on timeout waiting for the pulse to end""" + :param pin: The pin to use + :param pulse_level: 0 to time a low pulse or 1 to time a high pulse + :param timeout_us: A microsecond timeout + :return: The duration of the pulse in microseconds, or -1 for a timeout waiting for the level to match ``pulse_level``, or -2 on timeout waiting for the pulse to end + """ ... class mem: - """crwdns328876:0``mem8``crwdnd328876:0``mem16``crwdnd328876:0``mem32``crwdne328876:0 (crwdns328874:0crwdne328874:0)""" + """The class for the ``mem8``, ``mem16`` and ``mem32`` memory views.""" def __getitem__(self, address: int) -> int: - """crwdns328880:0crwdne328880:0 (crwdns328878:0crwdne328878:0) + """Access a value from memory. -:param address: (crwdns328882:0crwdne328882:0) crwdns328884:0crwdne328884:0 -:return: The value at that address as an integer.""" + :param address: The memory address. + :return: The value at that address as an integer. + """ ... - def __setitem__(self, address: int, value: int) -> None: - """crwdns328888:0crwdne328888:0 (crwdns328886:0crwdne328886:0) + """Set a value at the given address. -:param address: (crwdns328890:0crwdne328890:0) crwdns328892:0crwdne328892:0 -:param value: (crwdns328894:0crwdne328894:0) crwdns328896:0crwdne328896:0""" + :param address: The memory address. + :param value: The integer value to set. + """ ... + mem8: mem -"""crwdns328900:0crwdne328900:0 (crwdns328898:0crwdne328898:0)""" +"""8-bit (byte) view of memory.""" + mem16: mem -"""crwdns328904:0crwdne328904:0 (crwdns328902:0crwdne328902:0)""" +"""16-bit view of memory.""" + mem32: mem -"""crwdns328908:0crwdne328908:0 (crwdns328906:0crwdne328906:0)""" \ No newline at end of file +"""32-bit view of memory.""" diff --git a/lang/lol/typeshed/stdlib/math.pyi b/lang/lol/typeshed/stdlib/math.pyi index 9373c19..f82d4de 100644 --- a/lang/lol/typeshed/stdlib/math.pyi +++ b/lang/lol/typeshed/stdlib/math.pyi @@ -1,246 +1,273 @@ -"""crwdns328912:0crwdne328912:0 (crwdns328910:0crwdne328910:0)""" +"""Mathematical functions. +""" + from typing import Tuple def acos(x: float) -> float: - """crwdns328916:0crwdne328916:0 (crwdns328914:0crwdne328914:0) + """Calculate the inverse cosine. -Example: ``math.acos(1)`` + Example: ``math.acos(1)`` -:param x: (crwdns328918:0crwdne328918:0) crwdns328920:0crwdne328920:0 -:return: The inverse cosine of ``x``""" + :param x: A number + :return: The inverse cosine of ``x`` + """ ... def asin(x: float) -> float: - """crwdns328924:0crwdne328924:0 (crwdns328922:0crwdne328922:0) + """Calculate the inverse sine. -Example: ``math.asin(0)`` + Example: ``math.asin(0)`` -:param x: (crwdns328926:0crwdne328926:0) crwdns328928:0crwdne328928:0 -:return: The inverse sine of ``x``""" + :param x: A number + :return: The inverse sine of ``x`` + """ ... def atan(x: float) -> float: - """crwdns328932:0crwdne328932:0 (crwdns328930:0crwdne328930:0) + """Calculate the inverse tangent. -Example: ``math.atan(0)`` + Example: ``math.atan(0)`` -:param x: (crwdns328934:0crwdne328934:0) crwdns328936:0crwdne328936:0 -:return: The inverse tangent of ``x``""" + :param x: A number + :return: The inverse tangent of ``x`` + """ ... def atan2(y: float, x: float) -> float: - """crwdns328940:0``y/x``crwdne328940:0 (crwdns328938:0crwdne328938:0) + """Calculate the principal value of the inverse tangent of ``y/x``. -Example: ``math.atan2(0, -1)`` + Example: ``math.atan2(0, -1)`` -:param y: (crwdns328942:0crwdne328942:0) crwdns328944:0crwdne328944:0 -:param x: (crwdns328942:0crwdne328942:0) crwdns328944:0crwdne328944:0 -:return: The principal value of the inverse tangent of ``y/x``""" + :param y: A number + :param x: A number + :return: The principal value of the inverse tangent of ``y/x`` + """ ... def ceil(x: float) -> float: - """crwdns328952:0crwdne328952:0 (crwdns328950:0crwdne328950:0) + """Round a number towards positive infinity. -Example: ``math.ceil(0.1)`` + Example: ``math.ceil(0.1)`` -:param x: (crwdns328954:0crwdne328954:0) crwdns328956:0crwdne328956:0 -:return: ``x`` rounded towards positive infinity.""" + :param x: A number + :return: ``x`` rounded towards positive infinity. + """ ... def copysign(x: float, y: float) -> float: - """crwdns328960:0``x``crwdnd328960:0``y``crwdne328960:0 (crwdns328958:0crwdne328958:0) + """Calculate ``x`` with the sign of ``y``. -Example: ``math.copysign(1, -1)`` + Example: ``math.copysign(1, -1)`` -:param x: (crwdns328962:0crwdne328962:0) crwdns328964:0crwdne328964:0 -:param y: (crwdns328966:0crwdne328966:0) crwdns328968:0crwdne328968:0 -:return: ``x`` with the sign of ``y``""" + :param x: A number + :param y: The source of the sign for the return value + :return: ``x`` with the sign of ``y`` + """ ... def cos(x: float) -> float: - """crwdns328972:0``x``crwdne328972:0 (crwdns328970:0crwdne328970:0) + """Calculate the cosine of ``x``. -Example: ``math.cos(0)`` + Example: ``math.cos(0)`` -:param x: (crwdns328974:0crwdne328974:0) crwdns328976:0crwdne328976:0 -:return: The cosine of ``x``""" + :param x: A number + :return: The cosine of ``x`` + """ ... def degrees(x: float) -> float: - """crwdns328980:0crwdne328980:0 (crwdns328978:0crwdne328978:0) + """Convert radians to degrees. -Example: ``math.degrees(2 * math.pi)`` + Example: ``math.degrees(2 * math.pi)`` -:param x: (crwdns328982:0crwdne328982:0) crwdns328984:0crwdne328984:0 -:return: The value converted to degrees""" + :param x: A value in radians + :return: The value converted to degrees""" ... def exp(x: float) -> float: - """crwdns328988:0``x``crwdne328988:0 (crwdns328986:0crwdne328986:0) + """Calculate the exponential of ``x``. -Example: ``math.exp(1)`` + Example: ``math.exp(1)`` -:param x: (crwdns328990:0crwdne328990:0) crwdns328992:0crwdne328992:0 -:return: The exponential of ``x``.""" + :param x: A number + :return: The exponential of ``x``. + """ ... def fabs(x: float) -> float: - """crwdns328996:0``x``crwdne328996:0 (crwdns328994:0crwdne328994:0) + """Return the absolute value of ``x``. -Example: ``math.fabs(-0.1)`` + Example: ``math.fabs(-0.1)`` -:param x: (crwdns328998:0crwdne328998:0) crwdns329000:0crwdne329000:0 -:return: The absolute value of ``x``""" + :param x: A number + :return: The absolute value of ``x`` + """ ... def floor(x: float) -> int: - """crwdns329004:0crwdne329004:0 (crwdns329002:0crwdne329002:0) + """Round a number towards negative infinity. -Example: ``math.floor(0.9)`` + Example: ``math.floor(0.9)`` -:param x: (crwdns329006:0crwdne329006:0) crwdns329008:0crwdne329008:0 -:return: ``x`` rounded towards negative infinity.""" + :param x: A number + :return: ``x`` rounded towards negative infinity. + """ ... def fmod(x: float, y: float) -> float: - """crwdns329012:0``x/y``crwdne329012:0 (crwdns329010:0crwdne329010:0) + """Calculate the remainder of ``x/y``. -Example: ``math.fmod(10, 3)`` + Example: ``math.fmod(10, 3)`` -:param x: (crwdns329014:0crwdne329014:0) crwdns329016:0crwdne329016:0 -:param y: (crwdns329018:0crwdne329018:0) crwdns329020:0crwdne329020:0""" + :param x: The numerator + :param y: The denominator + """ ... def frexp(x: float) -> Tuple[float, int]: - """crwdns329024:0crwdne329024:0 (crwdns329022:0crwdne329022:0) + """Decomposes a floating-point number into its mantissa and exponent. -Example: ``mantissa, exponent = math.frexp(2)`` + Example: ``mantissa, exponent = math.frexp(2)`` -The returned value is the tuple ``(m, e)`` such that ``x == m * 2**e`` -exactly. If ``x == 0`` then the function returns ``(0.0, 0)``, otherwise -the relation ``0.5 <= abs(m) < 1`` holds. + The returned value is the tuple ``(m, e)`` such that ``x == m * 2**e`` + exactly. If ``x == 0`` then the function returns ``(0.0, 0)``, otherwise + the relation ``0.5 <= abs(m) < 1`` holds. -:param x: (crwdns329026:0crwdne329026:0) crwdns329028:0crwdne329028:0 -:return: A tuple of length two containing its mantissa then exponent""" + :param x: A floating-point number + :return: A tuple of length two containing its mantissa then exponent + """ ... def isfinite(x: float) -> bool: - """crwdns329032:0crwdne329032:0 (crwdns329030:0crwdne329030:0) + """Check if a value is finite. -Example: ``math.isfinite(float('inf'))`` + Example: ``math.isfinite(float('inf'))`` -:param x: (crwdns329034:0crwdne329034:0) crwdns329036:0crwdne329036:0 -:return: ``True`` if ``x`` is finite, ``False`` otherwise.""" + :param x: A number. + :return: ``True`` if ``x`` is finite, ``False`` otherwise. + """ ... def isinf(x: float) -> bool: - """crwdns329040:0crwdne329040:0 (crwdns329038:0crwdne329038:0) + """Check if a value is infinite. -Example: ``math.isinf(float('-inf'))`` + Example: ``math.isinf(float('-inf'))`` -:param x: (crwdns329042:0crwdne329042:0) crwdns329044:0crwdne329044:0 -:return: ``True`` if ``x`` is infinite, ``False`` otherwise.""" + :param x: A number. + :return: ``True`` if ``x`` is infinite, ``False`` otherwise. + """ ... def isnan(x: float) -> bool: - """crwdns329048:0crwdne329048:0 (crwdns329046:0crwdne329046:0) + """Check if a value is not-a-number (NaN). -Example: ``math.isnan(float('nan'))`` + Example: ``math.isnan(float('nan'))`` -:param x: (crwdns329050:0crwdne329050:0) crwdns329052:0crwdne329052:0 -:return: ``True`` if ``x`` is not-a-number (NaN), ``False`` otherwise.""" + :param x: A number + :return: ``True`` if ``x`` is not-a-number (NaN), ``False`` otherwise.""" ... def ldexp(x: float, exp: int) -> float: - """crwdns329056:0crwdne329056:0 (crwdns329054:0crwdne329054:0) + """Calculate ``x * (2**exp)``. -Example: ``math.ldexp(0.5, 2)`` + Example: ``math.ldexp(0.5, 2)`` -:param x: (crwdns329062:0crwdne329062:0) crwdns329064:0crwdne329064:0 -:param exp: (crwdns329058:0crwdne329058:0) crwdns329060:0crwdne329060:0 -:return: ``x * (2**exp)``""" + :param x: A number + :param exp: Integer exponent + :return: ``x * (2**exp)`` + """ ... -def log(x: float, base: float=e) -> float: - """crwdns329068:0``x``crwdne329068:0 (crwdns329066:0crwdne329066:0) +def log(x: float, base: float = e) -> float: + """Calculate the logarithm of ``x`` to the given base (defaults to natural logorithm). -Example: ``math.log(math.e)`` + Example: ``math.log(math.e)`` -With one argument, return the natural logarithm of x (to base e). + With one argument, return the natural logarithm of x (to base e). -With two arguments, return the logarithm of x to the given base, calculated as ``log(x)/log(base)``. + With two arguments, return the logarithm of x to the given base, calculated as ``log(x)/log(base)``. -:param x: (crwdns329074:0crwdne329074:0) crwdns329076:0crwdne329076:0 -:param base: (crwdns329070:0crwdne329070:0) crwdns329072:0crwdne329072:0 -:return: The natural logarithm of ``x``""" + :param x: A number + :param base: The base to use + :return: The natural logarithm of ``x`` + """ ... def modf(x: float) -> Tuple[float, float]: - """crwdns329080:0``x``crwdne329080:0 (crwdns329078:0crwdne329078:0) + """Calculate the fractional and integral parts of ``x``. -Example: ``fractional, integral = math.modf(1.5)`` + Example: ``fractional, integral = math.modf(1.5)`` -:param x: (crwdns329082:0crwdne329082:0) crwdns329084:0crwdne329084:0 -:return: A tuple of two floats representing the fractional then integral parts of ``x``. + :param x: A number + :return: A tuple of two floats representing the fractional then integral parts of ``x``. -Both the fractional and integral values have the same sign as ``x``.""" + Both the fractional and integral values have the same sign as ``x``. + """ ... def pow(x: float, y: float) -> float: - """crwdns329088:0``x``crwdnd329088:0``y``crwdne329088:0 (crwdns329086:0crwdne329086:0) + """Returns ``x`` to the power of ``y``. -Example: ``math.pow(4, 0.5)`` + Example: ``math.pow(4, 0.5)`` -:param x: (crwdns329090:0crwdne329090:0) crwdns329092:0crwdne329092:0 -:param y: (crwdns329094:0crwdne329094:0) crwdns329096:0crwdne329096:0 -:return: ``x`` to the power of ``y``""" + :param x: A number + :param y: The exponent + :return: ``x`` to the power of ``y`` + """ ... def radians(x: float) -> float: - """crwdns329100:0crwdne329100:0 (crwdns329098:0crwdne329098:0) + """Convert a degrees to radians. -Example: ``math.radians(360)`` + Example: ``math.radians(360)`` -:param x: (crwdns329102:0crwdne329102:0) crwdns329104:0crwdne329104:0 -:return: The value converted to radians""" + :param x: A value in degrees + :return: The value converted to radians + """ ... def sin(x: float) -> float: - """crwdns329108:0``x``crwdne329108:0 (crwdns329106:0crwdne329106:0) + """Calculate the sine of ``x``. -Example: ``math.sin(math.pi/2)`` + Example: ``math.sin(math.pi/2)`` -:param x: (crwdns329110:0crwdne329110:0) crwdns329112:0crwdne329112:0 -:return: The sine of ``x``""" + :param x: A number + :return: The sine of ``x`` + """ ... def sqrt(x: float) -> float: - """crwdns329116:0``x``crwdne329116:0 (crwdns329114:0crwdne329114:0) + """Calculate the square root of ``x``. -Example: ``math.sqrt(4)`` + Example: ``math.sqrt(4)`` -:param x: (crwdns329118:0crwdne329118:0) crwdns329120:0crwdne329120:0 -:return: The square root of ``x``""" + :param x: A number + :return: The square root of ``x`` + """ ... def tan(x: float) -> float: - """crwdns329124:0``x``crwdne329124:0 (crwdns329122:0crwdne329122:0) + """Calculate the tangent of ``x``. -Example: ``math.tan(0)`` + Example: ``math.tan(0)`` -:param x: (crwdns329126:0crwdne329126:0) crwdns329128:0crwdne329128:0 -:return: The tangent of ``x``.""" + :param x: A number + :return: The tangent of ``x``. + """ ... def trunc(x: float) -> int: - """crwdns329132:0crwdne329132:0 (crwdns329130:0crwdne329130:0) + """Round a number towards 0. -Example: ``math.trunc(-0.9)`` + Example: ``math.trunc(-0.9)`` -:param x: (crwdns329134:0crwdne329134:0) crwdns329136:0crwdne329136:0 -:return: ``x`` rounded towards zero.""" + :param x: A number + :return: ``x`` rounded towards zero. + """ ... + e: float -"""crwdns329140:0crwdne329140:0 (crwdns329138:0crwdne329138:0)""" +"""Base of the natural logarithm""" + pi: float -"""crwdns329144:0crwdne329144:0 (crwdns329142:0crwdne329142:0)""" \ No newline at end of file +"""The ratio of a circle's circumference to its diameter""" diff --git a/lang/lol/typeshed/stdlib/microbit/__init__.pyi b/lang/lol/typeshed/stdlib/microbit/__init__.pyi index f0c5493..f12158f 100644 --- a/lang/lol/typeshed/stdlib/microbit/__init__.pyi +++ b/lang/lol/typeshed/stdlib/microbit/__init__.pyi @@ -1,6 +1,11 @@ -"""crwdns329148:0crwdne329148:0 (crwdns329146:0crwdne329146:0)""" +"""Pins, images, sounds, temperature and volume. +""" + from typing import Any, Callable, List, Optional, Tuple, Union, overload + from _typeshed import ReadableBuffer + +# V2 only from . import accelerometer as accelerometer from . import audio as audio from . import compass as compass @@ -11,696 +16,831 @@ from . import speaker as speaker from . import spi as spi from . import uart as uart -def run_every(callback: Optional[Callable[[], None]]=None, days: int=0, h: int=0, min: int=0, s: int=0, ms: int=0) -> Callable[[Callable[[], None]], Callable[[], None]]: - """crwdns335788:0crwdne335788:0 (crwdns329150:0crwdne329150:0) +def run_every( + callback: Optional[Callable[[], None]] = None, + days: int = 0, + h: int = 0, + min: int = 0, + s: int = 0, + ms: int = 0, +) -> Callable[[Callable[[], None]], Callable[[], None]]: + """Schedule to run a function at the interval specified by the time arguments **V2 only**. -Example: ``run_every(my_logging, min=5)`` + Example: ``run_every(my_logging, min=5)`` -``run_every`` can be used in two ways: + ``run_every`` can be used in two ways: -As a Decorator - placed on top of the function to schedule. For example:: + As a Decorator - placed on top of the function to schedule. For example:: - @run_every(h=1, min=20, s=30, ms=50) - def my_function(): - # Do something here + @run_every(h=1, min=20, s=30, ms=50) + def my_function(): + # Do something here -As a Function - passing the callback as a positional argument. For example:: + As a Function - passing the callback as a positional argument. For example:: - def my_function(): - # Do something here - run_every(my_function, s=30) + def my_function(): + # Do something here + run_every(my_function, s=30) -Each argument corresponds to a different time unit and they are additive. -So ``run_every(min=1, s=30)`` schedules the callback every minute and a half. + Each argument corresponds to a different time unit and they are additive. + So ``run_every(min=1, s=30)`` schedules the callback every minute and a half. -When an exception is thrown inside the callback function it deschedules the -function. To avoid this you can catch exceptions with ``try/except``. + When an exception is thrown inside the callback function it deschedules the + function. To avoid this you can catch exceptions with ``try/except``. -:param callback: (crwdns329154:0crwdne329154:0) crwdns335790:0crwdne335790:0 -:param days: (crwdns329158:0crwdne329158:0) crwdns335792:0crwdne335792:0 -:param h: (crwdns329162:0crwdne329162:0) crwdns335794:0crwdne335794:0 -:param min: (crwdns329166:0crwdne329166:0) crwdns335796:0crwdne335796:0 -:param s: (crwdns329174:0crwdne329174:0) crwdns335800:0crwdne335800:0 -:param ms: (crwdns329170:0crwdne329170:0) crwdns335798:0crwdne335798:0""" + :param callback: Function to call at the provided interval. Omit when using as a decorator. + :param days: Sets the day mark for the scheduling. + :param h: Sets the hour mark for the scheduling. + :param min: Sets the minute mark for the scheduling. + :param s: Sets the second mark for the scheduling. + :param ms: Sets the millisecond mark for the scheduling. + """ def panic(n: int) -> None: - """crwdns329180:0crwdne329180:0 (crwdns329178:0crwdne329178:0) + """Enter a panic mode. -Example: ``panic(127)`` + Example: ``panic(127)`` -:param n: (crwdns329182:0crwdne329182:0) crwdns329184:0crwdne329184:0 + :param n: An arbitrary integer <= 255 to indicate a status. -Requires restart.""" + Requires restart. + """ def reset() -> None: - """crwdns329188:0crwdne329188:0 (crwdns329186:0crwdne329186:0)""" + """Restart the board.""" + @overload def scale(value: float, from_: Tuple[float, float], to: Tuple[int, int]) -> int: - """crwdns336078:0crwdne336078:0 (crwdns336076:0crwdne336076:0) + """Converts a value from a range to an integer range. -Example: ``volume = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255))`` + Example: ``volume = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255))`` -For example, to convert an accelerometer X value to a speaker volume. + For example, to convert an accelerometer X value to a speaker volume. -If one of the numbers in the ``to`` parameter is a floating point -(i.e a decimal number like ``10.0``), this function will return a -floating point number. + If one of the numbers in the ``to`` parameter is a floating point + (i.e a decimal number like ``10.0``), this function will return a + floating point number. - temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0)) + temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0)) -:param value: (crwdns336088:0crwdne336088:0) crwdns336090:0crwdne336090:0 -:param from_: (crwdns336080:0crwdne336080:0) crwdns336082:0crwdne336082:0 -:param to: (crwdns336084:0crwdne336084:0) crwdns336086:0crwdne336086:0 -:return: The ``value`` converted to the ``to`` range.""" + :param value: A number to convert. + :param from_: A tuple to define the range to convert from. + :param to: A tuple to define the range to convert to. + :return: The ``value`` converted to the ``to`` range. + """ @overload def scale(value: float, from_: Tuple[float, float], to: Tuple[float, float]) -> float: - """crwdns336094:0crwdne336094:0 (crwdns336092:0crwdne336092:0) + """Converts a value from a range to a floating point range. -Example: ``temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0))`` + Example: ``temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0))`` -For example, to convert temperature from a Celsius scale to Fahrenheit. + For example, to convert temperature from a Celsius scale to Fahrenheit. -If one of the numbers in the ``to`` parameter is a floating point -(i.e a decimal number like ``10.0``), this function will return a -floating point number. -If they are both integers (i.e ``10``), it will return an integer:: + If one of the numbers in the ``to`` parameter is a floating point + (i.e a decimal number like ``10.0``), this function will return a + floating point number. + If they are both integers (i.e ``10``), it will return an integer:: - returns_int = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255)) + returns_int = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255)) -:param value: (crwdns336104:0crwdne336104:0) crwdns336106:0crwdne336106:0 -:param from_: (crwdns336096:0crwdne336096:0) crwdns336098:0crwdne336098:0 -:param to: (crwdns336100:0crwdne336100:0) crwdns336102:0crwdne336102:0 -:return: The ``value`` converted to the ``to`` range.""" + :param value: A number to convert. + :param from_: A tuple to define the range to convert from. + :param to: A tuple to define the range to convert to. + :return: The ``value`` converted to the ``to`` range. + """ def sleep(n: float) -> None: - """crwdns329192:0``n``crwdne329192:0 (crwdns329190:0crwdne329190:0) + """Wait for ``n`` milliseconds. -Example: ``sleep(1000)`` + Example: ``sleep(1000)`` -:param n: (crwdns329194:0crwdne329194:0) crwdns329196:0crwdne329196:0 + :param n: The number of milliseconds to wait -One second is 1000 milliseconds, so:: + One second is 1000 milliseconds, so:: - microbit.sleep(1000) + microbit.sleep(1000) -will pause the execution for one second.""" + will pause the execution for one second. + """ def running_time() -> int: - """crwdns329200:0crwdne329200:0 (crwdns329198:0crwdne329198:0) + """Get the running time of the board. -:return: The number of milliseconds since the board was switched on or restarted.""" + :return: The number of milliseconds since the board was switched on or restarted. + """ def temperature() -> int: - """crwdns329204:0crwdne329204:0 (crwdns329202:0crwdne329202:0)""" + """Get the temperature of the micro:bit in degrees Celsius.""" def set_volume(v: int) -> None: - """crwdns329208:0crwdne329208:0 (crwdns329206:0crwdne329206:0) + """Sets the volume. -Example: ``set_volume(127)`` + Example: ``set_volume(127)`` -:param v: (crwdns329210:0crwdne329210:0) crwdns329212:0crwdne329212:0 + :param v: a value between 0 (low) and 255 (high). -Out of range values will be clamped to 0 or 255. + Out of range values will be clamped to 0 or 255. -**V2** only.""" + **V2** only. + """ ... class Button: - """crwdns329216:0``button_a``crwdnd329216:0``button_b``crwdne329216:0 (crwdns329214:0crwdne329214:0)""" + """The class for the buttons ``button_a`` and ``button_b``.""" def is_pressed(self) -> bool: - """crwdns329220:0crwdne329220:0 (crwdns329218:0crwdne329218:0) + """Check if the button is pressed. -:return: ``True`` if the specified button ``button`` is pressed, and ``False`` otherwise.""" + :return: ``True`` if the specified button ``button`` is pressed, and ``False`` otherwise. + """ ... - def was_pressed(self) -> bool: - """crwdns329224:0crwdne329224:0 (crwdns329222:0crwdne329222:0) + """Check if the button was pressed since the device started or the last time this method was called. -Calling this method will clear the press state so -that the button must be pressed again before this method will return -``True`` again. + Calling this method will clear the press state so + that the button must be pressed again before this method will return + ``True`` again. -:return: ``True`` if the specified button ``button`` was pressed, and ``False`` otherwise""" + :return: ``True`` if the specified button ``button`` was pressed, and ``False`` otherwise + """ ... - def get_presses(self) -> int: - """crwdns329228:0crwdne329228:0 (crwdns329226:0crwdne329226:0) + """Get the running total of button presses, and resets this total + to zero before returning. -:return: The number of presses since the device started or the last time this method was called""" + :return: The number of presses since the device started or the last time this method was called + """ ... + button_a: Button -"""crwdns329232:0``Button``crwdne329232:0 (crwdns329230:0crwdne329230:0)""" +"""The left button ``Button`` object.""" + button_b: Button -"""crwdns329236:0``Button``crwdne329236:0 (crwdns329234:0crwdne329234:0)""" +"""The right button ``Button`` object.""" class MicroBitDigitalPin: - """crwdns329240:0crwdne329240:0 (crwdns329238:0crwdne329238:0) + """A digital pin. + + Some pins support analog and touch features using the ``MicroBitAnalogDigitalPin`` and ``MicroBitTouchPin`` subclasses. + """ -Some pins support analog and touch features using the ``MicroBitAnalogDigitalPin`` and ``MicroBitTouchPin`` subclasses.""" NO_PULL: int PULL_UP: int PULL_DOWN: int - def read_digital(self) -> int: - """crwdns329244:0crwdne329244:0 (crwdns329242:0crwdne329242:0) + """Get the digital value of the pin. -Example: ``value = pin0.read_digital()`` + Example: ``value = pin0.read_digital()`` -:return: 1 if the pin is high, and 0 if it's low.""" + :return: 1 if the pin is high, and 0 if it's low. + """ ... - def write_digital(self, value: int) -> None: - """crwdns329248:0crwdne329248:0 (crwdns329246:0crwdne329246:0) + """Set the digital value of the pin. -Example: ``pin0.write_digital(1)`` + Example: ``pin0.write_digital(1)`` -:param value: (crwdns329250:0crwdne329250:0) crwdns329252:0crwdne329252:0""" + :param value: 1 to set the pin high or 0 to set the pin low""" ... - def set_pull(self, value: int) -> None: - """crwdns329256:0``PULL_UP``crwdnd329256:0``PULL_DOWN``crwdnd329256:0``NO_PULL``crwdne329256:0 (crwdns329254:0crwdne329254:0) + """Set the pull state to one of three possible values: ``PULL_UP``, ``PULL_DOWN`` or ``NO_PULL``. -Example: ``pin0.set_pull(pin0.PULL_UP)`` + Example: ``pin0.set_pull(pin0.PULL_UP)`` -:param value: (crwdns329258:0crwdne329258:0) crwdns329260:0``pin0.PULL_UP``crwdne329260:0""" + :param value: The pull state from the relevant pin, e.g. ``pin0.PULL_UP``. + """ ... - def get_pull(self) -> int: - """crwdns329264:0crwdne329264:0 (crwdns329262:0crwdne329262:0) + """Get the pull state on a pin. -Example: ``pin0.get_pull()`` + Example: ``pin0.get_pull()`` -:return: ``NO_PULL``, ``PULL_DOWN``, or ``PULL_UP`` + :return: ``NO_PULL``, ``PULL_DOWN``, or ``PULL_UP`` -These are set using the ``set_pull()`` method or automatically configured -when a pin mode requires it.""" + These are set using the ``set_pull()`` method or automatically configured + when a pin mode requires it. + """ ... - def get_mode(self) -> str: - """crwdns329268:0crwdne329268:0 (crwdns329266:0crwdne329266:0) + """Returns the pin mode. -Example: ``pin0.get_mode()`` + Example: ``pin0.get_mode()`` -When a pin is used for a specific function, like -writing a digital value, or reading an analog value, the pin mode -changes. + When a pin is used for a specific function, like + writing a digital value, or reading an analog value, the pin mode + changes. -:return: ``"unused"``, ``"analog"``, ``"read_digital"``, ``"write_digital"``, ``"display"``, ``"button"``, ``"music"``, ``"audio"``, ``"touch"``, ``"i2c"``, or ``"spi"``""" + :return: ``"unused"``, ``"analog"``, ``"read_digital"``, ``"write_digital"``, ``"display"``, ``"button"``, ``"music"``, ``"audio"``, ``"touch"``, ``"i2c"``, or ``"spi"`` + """ ... - def write_analog(self, value: int) -> None: - """crwdns329272:0``value``crwdne329272:0 (crwdns329270:0crwdne329270:0) - -Example: ``pin0.write_analog(254)`` + """Output a PWM signal on the pin, with the duty cycle proportional to ``value``. -:param value: (crwdns329274:0crwdne329274:0) crwdns329276:0crwdne329276:0""" + Example: ``pin0.write_analog(254)`` + :param value: An integer or a floating point number between 0 (0% duty cycle) and 1023 (100% duty). + """ def set_analog_period(self, period: int) -> None: - """crwdns329280:0``period``crwdne329280:0 (crwdns329278:0crwdne329278:0) + """Set the period of the PWM signal being output to ``period`` in milliseconds. -Example: ``pin0.set_analog_period(10)`` - -:param period: (crwdns329282:0crwdne329282:0) crwdns329284:0crwdne329284:0""" + Example: ``pin0.set_analog_period(10)`` + :param period: The period in milliseconds with a minimum valid value of 1ms. + """ def set_analog_period_microseconds(self, period: int) -> None: - """crwdns329288:0``period``crwdne329288:0 (crwdns329286:0crwdne329286:0) + """Set the period of the PWM signal being output to ``period`` in microseconds. -Example: ``pin0.set_analog_period_microseconds(512)`` + Example: ``pin0.set_analog_period_microseconds(512)`` -:param period: (crwdns329290:0crwdne329290:0) crwdns329292:0crwdne329292:0""" + :param period: The period in microseconds with a minimum valid value of 256µs. + """ class MicroBitAnalogDigitalPin(MicroBitDigitalPin): - """crwdns329296:0crwdne329296:0 (crwdns329294:0crwdne329294:0)""" + """A pin with analog and digital features.""" def read_analog(self) -> int: - """crwdns329300:0crwdne329300:0 (crwdns329298:0crwdne329298:0) + """Read the voltage applied to the pin. -Example: ``pin0.read_analog()`` + Example: ``pin0.read_analog()`` -:return: An integer between 0 (meaning 0V) and 1023 (meaning 3.3V).""" + :return: An integer between 0 (meaning 0V) and 1023 (meaning 3.3V). + """ class MicroBitTouchPin(MicroBitAnalogDigitalPin): - """crwdns329304:0crwdne329304:0 (crwdns329302:0crwdne329302:0)""" + """A pin with analog, digital and touch features.""" + CAPACITIVE: int RESISTIVE: int - def is_touched(self) -> bool: - """crwdns329308:0crwdne329308:0 (crwdns329306:0crwdne329306:0) + """Check if the pin is being touched. -Example: ``pin0.is_touched()`` + Example: ``pin0.is_touched()`` -The default touch mode for the pins on the edge connector is ``resistive``. -The default for the logo pin **V2** is ``capacitive``. + The default touch mode for the pins on the edge connector is ``resistive``. + The default for the logo pin **V2** is ``capacitive``. -**Resistive touch** -This test is done by measuring how much resistance there is between the -pin and ground. A low resistance gives a reading of ``True``. To get -a reliable reading using a finger you may need to touch the ground pin -with another part of your body, for example your other hand. + **Resistive touch** + This test is done by measuring how much resistance there is between the + pin and ground. A low resistance gives a reading of ``True``. To get + a reliable reading using a finger you may need to touch the ground pin + with another part of your body, for example your other hand. -**Capacitive touch** -This test is done by interacting with the electric field of a capacitor -using a finger as a conductor. `Capacitive touch -`_ -does not require you to make a ground connection as part of a circuit. + **Capacitive touch** + This test is done by interacting with the electric field of a capacitor + using a finger as a conductor. `Capacitive touch + `_ + does not require you to make a ground connection as part of a circuit. -:return: ``True`` if the pin is being touched with a finger, otherwise return ``False``.""" + :return: ``True`` if the pin is being touched with a finger, otherwise return ``False``. + """ ... - def set_touch_mode(self, value: int) -> None: - """crwdns329312:0crwdne329312:0 (crwdns329310:0crwdne329310:0) + """Set the touch mode for the pin. -Example: ``pin0.set_touch_mode(pin0.CAPACITIVE)`` + Example: ``pin0.set_touch_mode(pin0.CAPACITIVE)`` -The default touch mode for the pins on the edge connector is -``resistive``. The default for the logo pin **V2** is ``capacitive``. + The default touch mode for the pins on the edge connector is + ``resistive``. The default for the logo pin **V2** is ``capacitive``. -:param value: (crwdns329314:0crwdne329314:0) crwdns329316:0``CAPACITIVE``crwdnd329316:0``RESISTIVE``crwdne329316:0""" + :param value: ``CAPACITIVE`` or ``RESISTIVE`` from the relevant pin. + """ ... + pin0: MicroBitTouchPin -"""crwdns329320:0crwdne329320:0 (crwdns329318:0crwdne329318:0)""" +"""Pin with digital, analog and touch features.""" + pin1: MicroBitTouchPin -"""crwdns329324:0crwdne329324:0 (crwdns329322:0crwdne329322:0)""" +"""Pin with digital, analog and touch features.""" + pin2: MicroBitTouchPin -"""crwdns329328:0crwdne329328:0 (crwdns329326:0crwdne329326:0)""" +"""Pin with digital, analog and touch features.""" + pin3: MicroBitAnalogDigitalPin -"""crwdns329332:0crwdne329332:0 (crwdns329330:0crwdne329330:0)""" +"""Pin with digital and analog features.""" + pin4: MicroBitAnalogDigitalPin -"""crwdns329336:0crwdne329336:0 (crwdns329334:0crwdne329334:0)""" +"""Pin with digital and analog features.""" + pin5: MicroBitDigitalPin -"""crwdns329340:0crwdne329340:0 (crwdns329338:0crwdne329338:0)""" +"""Pin with digital features.""" + pin6: MicroBitDigitalPin -"""crwdns329344:0crwdne329344:0 (crwdns329342:0crwdne329342:0)""" +"""Pin with digital features.""" + pin7: MicroBitDigitalPin -"""crwdns329348:0crwdne329348:0 (crwdns329346:0crwdne329346:0)""" +"""Pin with digital features.""" + pin8: MicroBitDigitalPin -"""crwdns329352:0crwdne329352:0 (crwdns329350:0crwdne329350:0)""" +"""Pin with digital features.""" + pin9: MicroBitDigitalPin -"""crwdns329356:0crwdne329356:0 (crwdns329354:0crwdne329354:0)""" +"""Pin with digital features.""" + pin10: MicroBitAnalogDigitalPin -"""crwdns329360:0crwdne329360:0 (crwdns329358:0crwdne329358:0)""" +"""Pin with digital and analog features.""" + pin11: MicroBitDigitalPin -"""crwdns329364:0crwdne329364:0 (crwdns329362:0crwdne329362:0)""" +"""Pin with digital features.""" + pin12: MicroBitDigitalPin -"""crwdns329368:0crwdne329368:0 (crwdns329366:0crwdne329366:0)""" +"""Pin with digital features.""" + pin13: MicroBitDigitalPin -"""crwdns329372:0crwdne329372:0 (crwdns329370:0crwdne329370:0)""" +"""Pin with digital features.""" + pin14: MicroBitDigitalPin -"""crwdns329376:0crwdne329376:0 (crwdns329374:0crwdne329374:0)""" +"""Pin with digital features.""" + pin15: MicroBitDigitalPin -"""crwdns329380:0crwdne329380:0 (crwdns329378:0crwdne329378:0)""" +"""Pin with digital features.""" + pin16: MicroBitDigitalPin -"""crwdns329384:0crwdne329384:0 (crwdns329382:0crwdne329382:0)""" +"""Pin with digital features.""" + pin19: MicroBitDigitalPin -"""crwdns329388:0crwdne329388:0 (crwdns329386:0crwdne329386:0)""" +"""Pin with digital features.""" + pin20: MicroBitDigitalPin -"""crwdns329392:0crwdne329392:0 (crwdns329390:0crwdne329390:0)""" +"""Pin with digital features.""" + pin_logo: MicroBitTouchPin -"""crwdns329396:0crwdne329396:0 (crwdns329394:0crwdne329394:0)""" +"""A touch sensitive logo pin on the front of the micro:bit, which by default is set to capacitive touch mode.""" + pin_speaker: MicroBitAnalogDigitalPin -"""crwdns329400:0crwdne329400:0 (crwdns329398:0crwdne329398:0) +"""A pin to address the micro:bit speaker. This API is intended only for use in Pulse-Width Modulation pin operations e.g. pin_speaker.write_analog(128). """ class Image: - """crwdns329404:0crwdne329404:0 (crwdns329402:0crwdne329402:0) + """An image to show on the micro:bit LED display. -Given an image object it's possible to display it via the ``display`` API:: + Given an image object it's possible to display it via the ``display`` API:: + + display.show(Image.HAPPY) + """ - display.show(Image.HAPPY)""" HEART: Image - """crwdns329408:0crwdne329408:0 (crwdns329406:0crwdne329406:0)""" + """Heart image.""" + HEART_SMALL: Image - """crwdns329412:0crwdne329412:0 (crwdns329410:0crwdne329410:0)""" + """Small heart image.""" + HAPPY: Image - """crwdns329416:0crwdne329416:0 (crwdns329414:0crwdne329414:0)""" + """Happy face image.""" + SMILE: Image - """crwdns329420:0crwdne329420:0 (crwdns329418:0crwdne329418:0)""" + """Smiling mouth image.""" + SAD: Image - """crwdns329424:0crwdne329424:0 (crwdns329422:0crwdne329422:0)""" + """Sad face image.""" + CONFUSED: Image - """crwdns329428:0crwdne329428:0 (crwdns329426:0crwdne329426:0)""" + """Confused face image.""" + ANGRY: Image - """crwdns329432:0crwdne329432:0 (crwdns329430:0crwdne329430:0)""" + """Angry face image.""" + ASLEEP: Image - """crwdns329436:0crwdne329436:0 (crwdns329434:0crwdne329434:0)""" + """Sleeping face image.""" + SURPRISED: Image - """crwdns329440:0crwdne329440:0 (crwdns329438:0crwdne329438:0)""" + """Surprised face image.""" + SILLY: Image - """crwdns329444:0crwdne329444:0 (crwdns329442:0crwdne329442:0)""" + """Silly face image.""" + FABULOUS: Image - """crwdns329448:0crwdne329448:0 (crwdns329446:0crwdne329446:0)""" + """Sunglasses face image.""" + MEH: Image - """crwdns329452:0crwdne329452:0 (crwdns329450:0crwdne329450:0)""" + """Unimpressed face image.""" + YES: Image - """crwdns329456:0crwdne329456:0 (crwdns329454:0crwdne329454:0)""" + """Tick image.""" + NO: Image - """crwdns329460:0crwdne329460:0 (crwdns329458:0crwdne329458:0)""" + """Cross image.""" + CLOCK12: Image - """crwdns329464:0crwdne329464:0 (crwdns329462:0crwdne329462:0)""" + """Image with line pointing to 12 o'clock.""" + CLOCK11: Image - """crwdns329468:0crwdne329468:0 (crwdns329466:0crwdne329466:0)""" + """Image with line pointing to 11 o'clock.""" + CLOCK10: Image - """crwdns329472:0crwdne329472:0 (crwdns329470:0crwdne329470:0)""" + """Image with line pointing to 10 o'clock.""" + CLOCK9: Image - """crwdns329476:0crwdne329476:0 (crwdns329474:0crwdne329474:0)""" + """Image with line pointing to 9 o'clock.""" + CLOCK8: Image - """crwdns329480:0crwdne329480:0 (crwdns329478:0crwdne329478:0)""" + """Image with line pointing to 8 o'clock.""" + CLOCK7: Image - """crwdns329484:0crwdne329484:0 (crwdns329482:0crwdne329482:0)""" + """Image with line pointing to 7 o'clock.""" + CLOCK6: Image - """crwdns329488:0crwdne329488:0 (crwdns329486:0crwdne329486:0)""" + """Image with line pointing to 6 o'clock.""" + CLOCK5: Image - """crwdns329492:0crwdne329492:0 (crwdns329490:0crwdne329490:0)""" + """Image with line pointing to 5 o'clock.""" + CLOCK4: Image - """crwdns329496:0crwdne329496:0 (crwdns329494:0crwdne329494:0)""" + """Image with line pointing to 4 o'clock.""" + CLOCK3: Image - """crwdns329500:0crwdne329500:0 (crwdns329498:0crwdne329498:0)""" + """Image with line pointing to 3 o'clock.""" + CLOCK2: Image - """crwdns329504:0crwdne329504:0 (crwdns329502:0crwdne329502:0)""" + """Image with line pointing to 2 o'clock.""" + CLOCK1: Image - """crwdns329508:0crwdne329508:0 (crwdns329506:0crwdne329506:0)""" + """Image with line pointing to 1 o'clock.""" + ARROW_N: Image - """crwdns329512:0crwdne329512:0 (crwdns329510:0crwdne329510:0)""" + """Image of arrow pointing north.""" + ARROW_NE: Image - """crwdns329516:0crwdne329516:0 (crwdns329514:0crwdne329514:0)""" + """Image of arrow pointing north east.""" + ARROW_E: Image - """crwdns329520:0crwdne329520:0 (crwdns329518:0crwdne329518:0)""" + """Image of arrow pointing east.""" + ARROW_SE: Image - """crwdns329524:0crwdne329524:0 (crwdns329522:0crwdne329522:0)""" + """Image of arrow pointing south east.""" + ARROW_S: Image - """crwdns329528:0crwdne329528:0 (crwdns329526:0crwdne329526:0)""" + """Image of arrow pointing south.""" + ARROW_SW: Image - """crwdns329532:0crwdne329532:0 (crwdns329530:0crwdne329530:0)""" + """Image of arrow pointing south west.""" + ARROW_W: Image - """crwdns329536:0crwdne329536:0 (crwdns329534:0crwdne329534:0)""" + """Image of arrow pointing west.""" + ARROW_NW: Image - """crwdns329540:0crwdne329540:0 (crwdns329538:0crwdne329538:0)""" + """Image of arrow pointing north west.""" + TRIANGLE: Image - """crwdns329544:0crwdne329544:0 (crwdns329542:0crwdne329542:0)""" + """Image of a triangle pointing up.""" + TRIANGLE_LEFT: Image - """crwdns329548:0crwdne329548:0 (crwdns329546:0crwdne329546:0)""" + """Image of a triangle in the left corner.""" + CHESSBOARD: Image - """crwdns329552:0crwdne329552:0 (crwdns329550:0crwdne329550:0)""" + """Alternate LEDs lit in a chessboard pattern.""" + DIAMOND: Image - """crwdns329556:0crwdne329556:0 (crwdns329554:0crwdne329554:0)""" + """Diamond image.""" + DIAMOND_SMALL: Image - """crwdns329560:0crwdne329560:0 (crwdns329558:0crwdne329558:0)""" + """Small diamond image.""" + SQUARE: Image - """crwdns329564:0crwdne329564:0 (crwdns329562:0crwdne329562:0)""" + """Square image.""" + SQUARE_SMALL: Image - """crwdns329568:0crwdne329568:0 (crwdns329566:0crwdne329566:0)""" + """Small square image.""" + RABBIT: Image - """crwdns329572:0crwdne329572:0 (crwdns329570:0crwdne329570:0)""" + """Rabbit image.""" + COW: Image - """crwdns329576:0crwdne329576:0 (crwdns329574:0crwdne329574:0)""" + """Cow image.""" + MUSIC_CROTCHET: Image - """crwdns329580:0crwdne329580:0 (crwdns329578:0crwdne329578:0)""" + """Crotchet note image.""" + MUSIC_QUAVER: Image - """crwdns329584:0crwdne329584:0 (crwdns329582:0crwdne329582:0)""" + """Quaver note image.""" + MUSIC_QUAVERS: Image - """crwdns329588:0crwdne329588:0 (crwdns329586:0crwdne329586:0)""" + """Pair of quavers note image.""" + PITCHFORK: Image - """crwdns329592:0crwdne329592:0 (crwdns329590:0crwdne329590:0)""" + """Pitchfork image.""" + XMAS: Image - """crwdns329596:0crwdne329596:0 (crwdns329594:0crwdne329594:0)""" + """Christmas tree image.""" + PACMAN: Image - """crwdns329600:0crwdne329600:0 (crwdns329598:0crwdne329598:0)""" + """Pac-Man arcade character image.""" + TARGET: Image - """crwdns329604:0crwdne329604:0 (crwdns329602:0crwdne329602:0)""" + """Target image.""" + TSHIRT: Image - """crwdns329608:0crwdne329608:0 (crwdns329606:0crwdne329606:0)""" + """T-shirt image.""" + ROLLERSKATE: Image - """crwdns329612:0crwdne329612:0 (crwdns329610:0crwdne329610:0)""" + """Rollerskate image.""" + DUCK: Image - """crwdns329616:0crwdne329616:0 (crwdns329614:0crwdne329614:0)""" + """Duck image.""" + HOUSE: Image - """crwdns329620:0crwdne329620:0 (crwdns329618:0crwdne329618:0)""" + """House image.""" + TORTOISE: Image - """crwdns329624:0crwdne329624:0 (crwdns329622:0crwdne329622:0)""" + """Tortoise image.""" + BUTTERFLY: Image - """crwdns329628:0crwdne329628:0 (crwdns329626:0crwdne329626:0)""" + """Butterfly image.""" + STICKFIGURE: Image - """crwdns329632:0crwdne329632:0 (crwdns329630:0crwdne329630:0)""" + """Stick figure image.""" + GHOST: Image - """crwdns329636:0crwdne329636:0 (crwdns329634:0crwdne329634:0)""" + """Ghost image.""" + SWORD: Image - """crwdns329640:0crwdne329640:0 (crwdns329638:0crwdne329638:0)""" + """Sword image.""" + GIRAFFE: Image - """crwdns329644:0crwdne329644:0 (crwdns329642:0crwdne329642:0)""" + """Giraffe image.""" + SKULL: Image - """crwdns329648:0crwdne329648:0 (crwdns329646:0crwdne329646:0)""" + """Skull image.""" + UMBRELLA: Image - """crwdns329652:0crwdne329652:0 (crwdns329650:0crwdne329650:0)""" + """Umbrella image.""" + SNAKE: Image - """crwdns329656:0crwdne329656:0 (crwdns329654:0crwdne329654:0)""" + """Snake image.""" + SCISSORS: Image - """crwdns335820:0crwdne335820:0 (crwdns335818:0crwdne335818:0)""" + """Scissors image.""" + ALL_CLOCKS: List[Image] - """crwdns329660:0crwdne329660:0 (crwdns329658:0crwdne329658:0)""" - ALL_ARROWS: List[Image] - """crwdns329664:0crwdne329664:0 (crwdns329662:0crwdne329662:0)""" + """A list containing all the CLOCK_ images in sequence.""" + ALL_ARROWS: List[Image] + """A list containing all the ARROW_ images in sequence.""" @overload def __init__(self, string: str) -> None: - """crwdns329668:0crwdne329668:0 (crwdns329666:0crwdne329666:0) + """Create an image from a string describing which LEDs are lit. -``string`` has to consist of digits 0-9 arranged into lines, -describing the image, for example:: + ``string`` has to consist of digits 0-9 arranged into lines, + describing the image, for example:: - image = Image("90009:" - "09090:" - "00900:" - "09090:" - "90009") + 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 newlines (\\n) insead of the colons. + 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 newlines (\\n) insead of the colons. -:param string: (crwdns329670:0crwdne329670:0) crwdns329672:0crwdne329672:0""" + :param string: The string describing the image. + """ ... - @overload - def __init__(self, width: int=5, height: int=5, buffer: ReadableBuffer=None) -> None: - """crwdns329676:0``width``crwdnd329676:0``height``crwdne329676:0 (crwdns329674:0crwdne329674:0) + def __init__( + self, width: int = 5, height: int = 5, buffer: ReadableBuffer = None + ) -> None: + """Create an empty image with ``width`` columns and ``height`` rows. -:param width: (crwdns329686:0crwdne329686:0) crwdns329688:0crwdne329688:0 -:param height: (crwdns329682:0crwdne329682:0) crwdns329684:0crwdne329684:0 -:param buffer: (crwdns329678:0crwdne329678:0) crwdns329680:0``width``crwdnd329680:0``height``crwdne329680:0 + :param width: Optional width of the image + :param height: Optional height of the image + :param buffer: Optional array or bytes of ``width``×``height`` integers in range 0-9 to initialize the image -Examples:: + Examples:: - Image(2, 2, b'\x08\x08\x08\x08') - Image(2, 2, bytearray([9,9,9,9])) + Image(2, 2, b'\x08\x08\x08\x08') + Image(2, 2, bytearray([9,9,9,9])) -These create 2 x 2 pixel images at full brightness.""" + These create 2 x 2 pixel images at full brightness. + """ ... - def width(self) -> int: - """crwdns329692:0crwdne329692:0 (crwdns329690:0crwdne329690:0) + """Get the number of columns. -:return: The number of columns in the image""" + :return: The number of columns in the image + """ ... - def height(self) -> int: - """crwdns329696:0crwdne329696:0 (crwdns329694:0crwdne329694:0) + """Get the number of rows. -:return: The number of rows in the image""" + :return: The number of rows in the image + """ ... - def set_pixel(self, x: int, y: int, value: int) -> None: - """crwdns329700:0crwdne329700:0 (crwdns329698:0crwdne329698:0) + """Set the brightness of a pixel. -Example: ``my_image.set_pixel(0, 0, 9)`` + Example: ``my_image.set_pixel(0, 0, 9)`` -:param x: (crwdns329706:0crwdne329706:0) crwdns329708:0crwdne329708:0 -:param y: (crwdns329710:0crwdne329710:0) crwdns329712:0crwdne329712:0 -:param value: (crwdns329702:0crwdne329702:0) crwdns329704:0crwdne329704:0 + :param x: The column number + :param y: The row number + :param value: The brightness as an integer 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``.""" + 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: - """crwdns329716:0crwdne329716:0 (crwdns329714:0crwdne329714:0) + """Get the brightness of a pixel. -Example: ``my_image.get_pixel(0, 0)`` + Example: ``my_image.get_pixel(0, 0)`` -:param x: (crwdns329718:0crwdne329718:0) crwdns329720:0crwdne329720:0 -:param y: (crwdns329722:0crwdne329722:0) crwdns329724:0crwdne329724:0 -:return: The brightness as an integer between 0 and 9.""" + :param x: The column number + :param y: The row number + :return: The brightness as an integer between 0 and 9. + """ ... - def shift_left(self, n: int) -> Image: - """crwdns329728:0crwdne329728:0 (crwdns329726:0crwdne329726:0) + """Create a new image by shifting the picture left. -Example: ``Image.HEART_SMALL.shift_left(1)`` + Example: ``Image.HEART_SMALL.shift_left(1)`` -:param n: (crwdns329730:0crwdne329730:0) crwdns329732:0crwdne329732:0 -:return: The shifted image""" + :param n: The number of columns to shift by + :return: The shifted image + """ ... - def shift_right(self, n: int) -> Image: - """crwdns329736:0crwdne329736:0 (crwdns329734:0crwdne329734:0) + """Create a new image by shifting the picture right. -Example: ``Image.HEART_SMALL.shift_right(1)`` + Example: ``Image.HEART_SMALL.shift_right(1)`` -:param n: (crwdns329738:0crwdne329738:0) crwdns329740:0crwdne329740:0 -:return: The shifted image""" + :param n: The number of columns to shift by + :return: The shifted image + """ ... - def shift_up(self, n: int) -> Image: - """crwdns329744:0crwdne329744:0 (crwdns329742:0crwdne329742:0) + """Create a new image by shifting the picture up. -Example: ``Image.HEART_SMALL.shift_up(1)`` + Example: ``Image.HEART_SMALL.shift_up(1)`` -:param n: (crwdns329746:0crwdne329746:0) crwdns329748:0crwdne329748:0 -:return: The shifted image""" + :param n: The number of rows to shift by + :return: The shifted image + """ ... - def shift_down(self, n: int) -> Image: - """crwdns329752:0crwdne329752:0 (crwdns329750:0crwdne329750:0) + """Create a new image by shifting the picture down. -Example: ``Image.HEART_SMALL.shift_down(1)`` + Example: ``Image.HEART_SMALL.shift_down(1)`` -:param n: (crwdns329754:0crwdne329754:0) crwdns329756:0crwdne329756:0 -:return: The shifted image""" + :param n: The number of rows to shift by + :return: The shifted image + """ ... - def crop(self, x: int, y: int, w: int, h: int) -> Image: - """crwdns329760:0crwdne329760:0 (crwdns329758:0crwdne329758:0) + """Create a new image by cropping the picture. -Example: ``Image.HEART.crop(1, 1, 3, 3)`` + Example: ``Image.HEART.crop(1, 1, 3, 3)`` -:param x: (crwdns329770:0crwdne329770:0) crwdns329772:0crwdne329772:0 -:param y: (crwdns329774:0crwdne329774:0) crwdns329776:0crwdne329776:0 -:param w: (crwdns329766:0crwdne329766:0) crwdns329768:0crwdne329768:0 -:param h: (crwdns329762:0crwdne329762:0) crwdns329764:0crwdne329764:0 -:return: The new image""" + :param x: The crop offset column + :param y: The crop offset row + :param w: The crop width + :param h: The crop height + :return: The new image + """ ... - def copy(self) -> Image: - """crwdns329780:0crwdne329780:0 (crwdns329778:0crwdne329778:0) + """Create an exact copy of the image. -Example: ``Image.HEART.copy()`` + Example: ``Image.HEART.copy()`` -:return: The new image""" + :return: The new image + """ ... - def invert(self) -> Image: - """crwdns329784:0crwdne329784:0 (crwdns329782:0crwdne329782:0) + """Create a new image by inverting the brightness of the pixels in the + source image. -Example: ``Image.SMALL_HEART.invert()`` + Example: ``Image.SMALL_HEART.invert()`` -:return: The new image.""" + :return: The new image. + """ ... - def fill(self, value: int) -> None: - """crwdns329788:0crwdne329788:0 (crwdns329786:0crwdne329786:0) + """Set the brightness of all the pixels in the image. -Example: ``my_image.fill(5)`` + Example: ``my_image.fill(5)`` -:param value: (crwdns329790:0crwdne329790:0) crwdns329792:0crwdne329792:0 + :param value: The new brightness as a number 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``.""" + 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: - """crwdns329796:0crwdne329796:0 (crwdns329794:0crwdne329794:0) - -Example: ``my_image.blit(Image.HEART, 1, 1, 3, 3, 1, 1)`` - -:param src: (crwdns329802:0crwdne329802:0) crwdns329804:0crwdne329804:0 -:param x: (crwdns329810:0crwdne329810:0) crwdns329812:0crwdne329812:0 -:param y: (crwdns329818:0crwdne329818:0) crwdns329820:0crwdne329820:0 -:param w: (crwdns329806:0crwdne329806:0) crwdns329808:0crwdne329808:0 -:param h: (crwdns329798:0crwdne329798:0) crwdns329800:0crwdne329800:0 -:param xdest: (crwdns329814:0crwdne329814:0) crwdns329816:0crwdne329816:0 -:param ydest: (crwdns329822:0crwdne329822:0) crwdns329824:0crwdne329824:0 - -Pixels outside the source image are treated as having a brightness 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 blit( + self, + src: Image, + x: int, + y: int, + w: int, + h: int, + xdest: int = 0, + ydest: int = 0, + ) -> None: + """Copy an area from another image into this image. + + Example: ``my_image.blit(Image.HEART, 1, 1, 3, 3, 1, 1)`` + + :param src: The source image + :param x: The starting column offset in the source image + :param y: The starting row offset in the source image + :param w: The number of columns to copy + :param h: The number of rows to copy + :param xdest: The column offset to modify in this image + :param ydest: The row offset to modify in this image + + Pixels outside the source image are treated as having a brightness 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: - """crwdns329828:0crwdne329828:0 (crwdns329826:0crwdne329826:0)""" + """Get a compact string representation of the image.""" ... - def __str__(self) -> str: - """crwdns329832:0crwdne329832:0 (crwdns329830:0crwdne329830:0)""" + """Get a readable string representation of the image.""" ... - def __add__(self, other: Image) -> Image: - """crwdns329836:0crwdne329836:0 (crwdns329834:0crwdne329834:0) + """Create a new image by adding the brightness values from the two + images for each pixel. -Example: ``Image.HEART + Image.HAPPY`` + Example: ``Image.HEART + Image.HAPPY`` -:param other: (crwdns329838:0crwdne329838:0) crwdns329840:0crwdne329840:0""" + :param other: The image to add. + """ ... - def __sub__(self, other: Image) -> Image: - """crwdns329844:0crwdne329844:0 (crwdns329842:0crwdne329842:0) + """Create a new image by subtracting the brightness values of the + other image from this image. -Example: ``Image.HEART - Image.HEART_SMALL`` + Example: ``Image.HEART - Image.HEART_SMALL`` -:param other: (crwdns329846:0crwdne329846:0) crwdns329848:0crwdne329848:0""" + :param other: The image to subtract. + """ ... - def __mul__(self, n: float) -> Image: - """crwdns329852:0``n``crwdne329852:0 (crwdns329850:0crwdne329850:0) + """Create a new image by multiplying the brightness of each pixel by + ``n``. -Example: ``Image.HEART * 0.5`` + Example: ``Image.HEART * 0.5`` -:param n: (crwdns329854:0crwdne329854:0) crwdns329856:0crwdne329856:0""" + :param n: The value to multiply by. + """ ... - def __truediv__(self, n: float) -> Image: - """crwdns329860:0``n``crwdne329860:0 (crwdns329858:0crwdne329858:0) + """Create a new image by dividing the brightness of each pixel by + ``n``. -Example: ``Image.HEART / 2`` + Example: ``Image.HEART / 2`` -:param n: (crwdns329862:0crwdne329862:0) crwdns329864:0crwdne329864:0""" + :param n: The value to divide by. + """ ... class SoundEvent: LOUD: SoundEvent - """crwdns334408:0``quiet``crwdnd334408:0``loud``crwdne334408:0 (crwdns329866:0crwdne329866:0)""" + """Represents the transition of sound events, from ``quiet`` to ``loud`` like clapping or shouting.""" + QUIET: SoundEvent - """crwdns334410:0``loud``crwdnd334410:0``quiet``crwdne334410:0 (crwdns329870:0crwdne329870:0)""" + """Represents the transition of sound events, from ``loud`` to ``quiet`` like speaking or background music.""" class Sound: - """crwdns329876:0``audio.play(Sound.NAME)``crwdne329876:0 (crwdns329874:0crwdne329874:0)""" + """The built-in sounds can be called using ``audio.play(Sound.NAME)``.""" + GIGGLE: Sound - """crwdns329880:0crwdne329880:0 (crwdns329878:0crwdne329878:0)""" + """Giggling sound.""" + HAPPY: Sound - """crwdns329884:0crwdne329884:0 (crwdns329882:0crwdne329882:0)""" + """Happy sound.""" + HELLO: Sound - """crwdns329888:0crwdne329888:0 (crwdns329886:0crwdne329886:0)""" + """Greeting sound.""" + MYSTERIOUS: Sound - """crwdns329892:0crwdne329892:0 (crwdns329890:0crwdne329890:0)""" + """Mysterious sound.""" + SAD: Sound - """crwdns329896:0crwdne329896:0 (crwdns329894:0crwdne329894:0)""" + """Sad sound.""" + SLIDE: Sound - """crwdns329900:0crwdne329900:0 (crwdns329898:0crwdne329898:0)""" + """Sliding sound.""" + SOARING: Sound - """crwdns329904:0crwdne329904:0 (crwdns329902:0crwdne329902:0)""" + """Soaring sound.""" + SPRING: Sound - """crwdns329908:0crwdne329908:0 (crwdns329906:0crwdne329906:0)""" + """Spring sound.""" + TWINKLE: Sound - """crwdns329912:0crwdne329912:0 (crwdns329910:0crwdne329910:0)""" + """Twinkling sound.""" + YAWN: Sound - """crwdns329916:0crwdne329916:0 (crwdns329914:0crwdne329914:0)""" \ No newline at end of file + """Yawning sound.""" diff --git a/lang/lol/typeshed/stdlib/microbit/accelerometer.pyi b/lang/lol/typeshed/stdlib/microbit/accelerometer.pyi index 23c0aee..bac82c0 100644 --- a/lang/lol/typeshed/stdlib/microbit/accelerometer.pyi +++ b/lang/lol/typeshed/stdlib/microbit/accelerometer.pyi @@ -1,103 +1,115 @@ -"""crwdns329920:0crwdne329920:0 (crwdns329918:0crwdne329918:0)""" +"""Measure the acceleration of the micro:bit and recognise gestures. +""" + from typing import Tuple def get_x() -> int: - """crwdns329924:0``x``crwdne329924:0 (crwdns329922:0crwdne329922:0) + """Get the acceleration measurement in the ``x`` axis in milli-g. -Example: ``accelerometer.get_x()`` + Example: ``accelerometer.get_x()`` -:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" + :return: A positive or negative integer depending on direction in the range +/- 2000mg. + """ ... def get_y() -> int: - """crwdns329928:0``y``crwdne329928:0 (crwdns329926:0crwdne329926:0) + """Get the acceleration measurement in the ``y`` axis in milli-g. -Example: ``accelerometer.get_y()`` + Example: ``accelerometer.get_y()`` -:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" + :return: A positive or negative integer depending on direction in the range +/- 2000mg. + """ ... def get_z() -> int: - """crwdns329932:0``z``crwdne329932:0 (crwdns329930:0crwdne329930:0) + """Get the acceleration measurement in the ``z`` axis in milli-g. -Example: ``accelerometer.get_z()`` + Example: ``accelerometer.get_z()`` -:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" + :return: A positive or negative integer depending on direction in the range +/- 2000mg. + """ ... def get_values() -> Tuple[int, int, int]: - """crwdns329936:0crwdne329936:0 (crwdns329934:0crwdne329934:0) + """Get the acceleration measurements in all axes at once as a tuple. -Example: ``x, y, z = accelerometer.get_values()`` + Example: ``x, y, z = accelerometer.get_values()`` -:return: a three-element tuple of integers ordered as X, Y, Z, each value a positive or negative integer depending on direction in the range +/- 2000mg""" + :return: a three-element tuple of integers ordered as X, Y, Z, each value a positive or negative integer depending on direction in the range +/- 2000mg + """ ... def get_strength() -> int: - """crwdns335824:0crwdne335824:0 (crwdns335822:0crwdne335822:0) + """Get the acceleration measurement of all axes combined, as a positive integer. This is the Pythagorean sum of the X, Y and Z axes. -Example: ``accelerometer.get_strength()`` + Example: ``accelerometer.get_strength()`` -:return: The combined acceleration strength of all the axes, in milli-g.""" + :return: The combined acceleration strength of all the axes, in milli-g. + """ ... def current_gesture() -> str: - """crwdns329940:0crwdne329940:0 (crwdns329938:0crwdne329938:0) + """Get the name of the current gesture. -Example: ``accelerometer.current_gesture()`` + Example: ``accelerometer.current_gesture()`` -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. + 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. -:return: The current gesture""" + :return: The current gesture + """ ... def is_gesture(name: str) -> bool: - """crwdns329944:0crwdne329944:0 (crwdns329942:0crwdne329942:0) + """Check if the named gesture is currently active. -Example: ``accelerometer.is_gesture('shake')`` + Example: ``accelerometer.is_gesture('shake')`` -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. + 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. -:param name: (crwdns329946:0crwdne329946:0) crwdns329948:0crwdne329948:0 -:return: ``True`` if the gesture is active, ``False`` otherwise.""" + :param name: The gesture name. + :return: ``True`` if the gesture is active, ``False`` otherwise. + """ ... def was_gesture(name: str) -> bool: - """crwdns329952:0crwdne329952:0 (crwdns329950:0crwdne329950:0) + """Check if the named gesture was active since the last call. -Example: ``accelerometer.was_gesture('shake')`` + Example: ``accelerometer.was_gesture('shake')`` -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. + 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. -:param name: (crwdns329954:0crwdne329954:0) crwdns329956:0crwdne329956:0 -:return: ``True`` if the gesture was active since the last call, ``False`` otherwise.""" + :param name: The gesture name. + :return: ``True`` if the gesture was active since the last call, ``False`` otherwise. + """ def get_gestures() -> Tuple[str, ...]: - """crwdns329960:0crwdne329960:0 (crwdns329958:0crwdne329958:0) + """Return a tuple of the gesture history. -Example: ``accelerometer.get_gestures()`` + Example: ``accelerometer.get_gestures()`` -Clears the gesture history before returning. + Clears the gesture history before returning. -Gestures are not updated in the background so there needs to be constant -calls to some accelerometer method to do the gesture detection. Usually -gestures can be detected using a loop with a small :func:`microbit.sleep` delay. + Gestures are not updated in the background so there needs to be constant + calls to some accelerometer method to do the gesture detection. Usually + gestures can be detected using a loop with a small :func:`microbit.sleep` delay. -:return: The history as a tuple, most recent last.""" + :return: The history as a tuple, most recent last. + """ ... def set_range(value: int) -> None: - """crwdns335828:0``2``crwdnd335828:0``4``crwdnd335828:0``8``crwdne335828:0 (crwdns335826:0crwdne335826:0) + """Set the accelerometer sensitivity range, in g (standard gravity), to the closest values supported by the hardware, so it rounds to either ``2``, ``4``, or ``8`` g. -Example: ``accelerometer.set_range(8)`` + Example: ``accelerometer.set_range(8)`` -:param value: (crwdns335830:0crwdne335830:0) crwdns335832:0``g``crwdne335832:0""" \ No newline at end of file + :param value: New range for the accelerometer, an integer in ``g``. + """ diff --git a/lang/lol/typeshed/stdlib/microbit/audio.pyi b/lang/lol/typeshed/stdlib/microbit/audio.pyi index 8cbcbf8..3b1e327 100644 --- a/lang/lol/typeshed/stdlib/microbit/audio.pyi +++ b/lang/lol/typeshed/stdlib/microbit/audio.pyi @@ -1,123 +1,160 @@ -"""crwdns329964:0``audio``crwdne329964:0 (crwdns329962:0crwdne329962:0)""" +"""Play sounds using the micro:bit (import ``audio`` for V1 compatibility). +""" + from ..microbit import MicroBitDigitalPin, Sound, pin0 from typing import ClassVar, Iterable, Union -def play(source: Union[Iterable[AudioFrame], Sound, SoundEffect], wait: bool=True, pin: MicroBitDigitalPin=pin0, return_pin: Union[MicroBitDigitalPin, None]=None) -> None: - """crwdns335834:0crwdne335834:0 (crwdns329966:0crwdne329966:0) +def play( + source: Union[Iterable[AudioFrame], Sound, SoundEffect], + wait: bool = True, + pin: MicroBitDigitalPin = pin0, + return_pin: Union[MicroBitDigitalPin, None] = None, +) -> None: + """Play a built-in sound, sound effect or custom audio frames. -Example: ``audio.play(Sound.GIGGLE)`` + Example: ``audio.play(Sound.GIGGLE)`` -:param source: (crwdns329978:0crwdne329978:0) crwdns335836:0``Sound``crwdnd335836:0``Sound.GIGGLE``crwdnd335836:0``SoundEffect``crwdnd335836:0``AudioFrame``crwdne335836:0 -:param wait: (crwdns329982:0crwdne329982:0) crwdns329984:0``wait``crwdnd329984:0``True``crwdne329984:0 -:param pin: (crwdns329970:0crwdne329970:0) crwdns329972:0``pin0``crwdne329972:0 -:param return_pin: (crwdns329974:0crwdne329974:0) crwdns329976:0crwdne329976:0""" + :param source: A built-in ``Sound`` such as ``Sound.GIGGLE``, a ``SoundEffect`` or sample data as an iterable of ``AudioFrame`` objects. + :param wait: If ``wait`` is ``True``, this function will block until the sound is complete. + :param pin: An optional argument to specify the output pin can be used to override the default of ``pin0``. If we do not want any sound to play we can use ``pin=None``. + :param return_pin: Specifies a differential edge connector pin to connect to an external speaker instead of ground. This is ignored for the **V2** revision. + """ def is_playing() -> bool: - """crwdns329988:0crwdne329988:0 (crwdns329986:0crwdne329986:0) + """Check whether a sound is playing. -Example: ``audio.is_playing()`` + Example: ``audio.is_playing()`` -:return: ``True`` if audio is playing, otherwise ``False``.""" + :return: ``True`` if audio is playing, otherwise ``False``.""" ... def stop() -> None: - """crwdns329992:0crwdne329992:0 (crwdns329990:0crwdne329990:0) + """Stop all audio playback. -Example: ``audio.stop()``""" + Example: ``audio.stop()`` + """ ... class SoundEffect: - """crwdns335840:0crwdne335840:0 (crwdns335838:0crwdne335838:0)""" + """A sound effect, composed by a set of parameters configured via the constructor or attributes.""" + WAVEFORM_SINE: ClassVar[int] - """crwdns335844:0``waveform``crwdne335844:0 (crwdns335842:0crwdne335842:0)""" + """Sine wave option used for the ``waveform`` parameter.""" + WAVEFORM_SAWTOOTH: ClassVar[int] - """crwdns335848:0``waveform``crwdne335848:0 (crwdns335846:0crwdne335846:0)""" + """Sawtooth wave option used for the ``waveform`` parameter.""" + WAVEFORM_TRIANGLE: ClassVar[int] - """crwdns335852:0``waveform``crwdne335852:0 (crwdns335850:0crwdne335850:0)""" + """Triangle wave option used for the ``waveform`` parameter.""" + WAVEFORM_SQUARE: ClassVar[int] - """crwdns335856:0``waveform``crwdne335856:0 (crwdns335854:0crwdne335854:0)""" + """Square wave option used for the ``waveform`` parameter.""" + WAVEFORM_NOISE: ClassVar[int] - """crwdns335860:0``waveform``crwdne335860:0 (crwdns335858:0crwdne335858:0)""" + """Noise option used for the ``waveform`` parameter.""" + SHAPE_LINEAR: ClassVar[int] - """crwdns335864:0``shape``crwdne335864:0 (crwdns335862:0crwdne335862:0)""" + """Linear interpolation option used for the ``shape`` parameter.""" + SHAPE_CURVE: ClassVar[int] - """crwdns335868:0``shape``crwdne335868:0 (crwdns335866:0crwdne335866:0)""" + """Curve interpolation option used for the ``shape`` parameter.""" + SHAPE_LOG: ClassVar[int] - """crwdns335872:0``shape``crwdne335872:0 (crwdns335870:0crwdne335870:0)""" + """Logarithmic interpolation option used for the ``shape`` parameter.""" + FX_NONE: ClassVar[int] - """crwdns335876:0``fx``crwdne335876:0 (crwdns335874:0crwdne335874:0)""" + """No effect option used for the ``fx`` parameter.""" + FX_TREMOLO: ClassVar[int] - """crwdns335880:0``fx``crwdne335880:0 (crwdns335878:0crwdne335878:0)""" + """Tremolo effect option used for the ``fx`` parameter.""" + FX_VIBRATO: ClassVar[int] - """crwdns335884:0``fx``crwdne335884:0 (crwdns335882:0crwdne335882:0)""" + """Vibrato effect option used for the ``fx`` parameter.""" + FX_WARBLE: ClassVar[int] - """crwdns335888:0``fx``crwdne335888:0 (crwdns335886:0crwdne335886:0)""" + """Warble effect option used for the ``fx`` parameter.""" + freq_start: int - """crwdns335892:0``0``crwdnd335892:0``9999``crwdne335892:0 (crwdns335890:0crwdne335890:0)""" + """Start frequency in Hertz (Hz), a number between ``0`` and ``9999``""" + freq_end: int - """crwdns335896:0``0``crwdnd335896:0``9999``crwdne335896:0 (crwdns335894:0crwdne335894:0)""" + """End frequency in Hertz (Hz), a number between ``0`` and ``9999``""" + duration: int - """crwdns335900:0``0``crwdnd335900:0``9999``crwdne335900:0 (crwdns335898:0crwdne335898:0)""" - vol_start: int - """crwdns335904:0``0``crwdnd335904:0``255``crwdne335904:0 (crwdns335902:0crwdne335902:0)""" - vol_end: int - """crwdns335908:0``0``crwdnd335908:0``255``crwdne335908:0 (crwdns335906:0crwdne335906:0)""" - waveform: int - """crwdns335912:0``WAVEFORM_SINE``crwdnd335912:0``WAVEFORM_SAWTOOTH``crwdnd335912:0``WAVEFORM_TRIANGLE``crwdnd335912:0``WAVEFORM_SQUARE``crwdnd335912:0``WAVEFORM_NOISE``crwdne335912:0 (crwdns335910:0crwdne335910:0)""" - fx: int - """crwdns335916:0``FX_TREMOLO``crwdnd335916:0``FX_VIBRATO``crwdnd335916:0``FX_WARBLE``crwdnd335916:0``FX_NONE``crwdne335916:0 (crwdns335914:0crwdne335914:0)""" - shape: int - """crwdns335920:0``SHAPE_LINEAR``crwdnd335920:0``SHAPE_CURVE``crwdnd335920:0``SHAPE_LOG``crwdne335920:0 (crwdns335918:0crwdne335918:0)""" + """Duration of the sound in milliseconds, a number between ``0`` and ``9999``""" - def __init__(self, freq_start: int=500, freq_end: int=2500, duration: int=500, vol_start: int=255, vol_end: int=0, waveform: int=WAVEFORM_SQUARE, fx: int=FX_NONE, shape: int=SHAPE_LOG): - """crwdns335924:0crwdne335924:0 (crwdns335922:0crwdne335922:0) + vol_start: int + """Start volume value, a number between ``0`` and ``255``""" -Example: ``my_effect = SoundEffect(duration=1000)`` + vol_end: int + """End volume value, a number between ``0`` and ``255``""" -All the parameters are optional, with default values as shown above, and -they can all be modified via attributes of the same name. For example, we -can first create an effect ``my_effect = SoundEffect(duration=1000)``, -and then change its attributes ``my_effect.duration = 500``. + waveform: int + """Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise)""" -:param freq_start: (crwdns335934:0crwdne335934:0) crwdns335936:0``0``crwdnd335936:0``9999``crwdne335936:0 -:param freq_end: (crwdns335930:0crwdne335930:0) crwdns335932:0``0``crwdnd335932:0``9999``crwdne335932:0 -:param duration: (crwdns335926:0crwdne335926:0) crwdns335928:0``0``crwdnd335928:0``9999``crwdne335928:0 -:param vol_start: (crwdns335950:0crwdne335950:0) crwdns335952:0``0``crwdnd335952:0``255``crwdne335952:0 -:param vol_end: (crwdns335946:0crwdne335946:0) crwdns335948:0``0``crwdnd335948:0``255``crwdne335948:0 -:param waveform: (crwdns335954:0crwdne335954:0) crwdns335956:0``WAVEFORM_SINE``crwdnd335956:0``WAVEFORM_SAWTOOTH``crwdnd335956:0``WAVEFORM_TRIANGLE``crwdnd335956:0``WAVEFORM_SQUARE``crwdnd335956:0``WAVEFORM_NOISE``crwdne335956:0 -:param fx: (crwdns335938:0crwdne335938:0) crwdns335940:0``FX_TREMOLO``crwdnd335940:0``FX_VIBRATO``crwdnd335940:0``FX_WARBLE``crwdnd335940:0``FX_NONE``crwdne335940:0 -:param shape: (crwdns335942:0crwdne335942:0) crwdns335944:0``SHAPE_LINEAR``crwdnd335944:0``SHAPE_CURVE``crwdnd335944:0``SHAPE_LOG``crwdne335944:0""" + fx: int + """Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``""" + shape: int + """The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``""" + + def __init__( + self, + freq_start: int = 500, + freq_end: int = 2500, + duration: int = 500, + vol_start: int = 255, + vol_end: int = 0, + waveform: int = WAVEFORM_SQUARE, + fx: int = FX_NONE, + shape: int = SHAPE_LOG, + ): + """Create a new sound effect. + + Example: ``my_effect = SoundEffect(duration=1000)`` + + All the parameters are optional, with default values as shown above, and + they can all be modified via attributes of the same name. For example, we + can first create an effect ``my_effect = SoundEffect(duration=1000)``, + and then change its attributes ``my_effect.duration = 500``. + + :param freq_start: Start frequency in Hertz (Hz), a number between ``0`` and ``9999``. + :param freq_end: End frequency in Hertz (Hz), a number between ``0`` and ``9999``. + :param duration: Duration of the sound in milliseconds, a number between ``0`` and ``9999``. + :param vol_start: Start volume value, a number between ``0`` and ``255``. + :param vol_end: End volume value, a number between ``0`` and ``255``. + :param waveform: Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise). + :param fx: Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``. + :param shape: The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``. + """ def copy(self) -> SoundEffect: - """crwdns335960:0``SoundEffect``crwdne335960:0 (crwdns335958:0crwdne335958:0) + """Create a copy of this ``SoundEffect``. -Example: ``sound_2 = sound_1.copy()`` + Example: ``sound_2 = sound_1.copy()`` -:return: A copy of the SoundEffect.""" + :return: A copy of the SoundEffect. + """ class AudioFrame: - """crwdns329996:0``AudioFrame``crwdne329996:0 (crwdns329994:0crwdne329994:0) + """An ``AudioFrame`` object is a list of 32 samples each of which is a unsigned byte + (whole number between 0 and 255). -It takes just over 4 ms to play a single frame. + It takes just over 4 ms to play a single frame. -Example:: + Example:: - frame = AudioFrame() - for i in range(len(frame)): - frame[i] = 252 - i * 8""" + frame = AudioFrame() + for i in range(len(frame)): + frame[i] = 252 - i * 8 + """ def copyfrom(self, other: AudioFrame) -> None: - """crwdns335964:0``AudioFrame``crwdnd335964:0``AudioFrame``crwdne335964:0 (crwdns335962:0crwdne335962:0) - -Example: ``my_frame.copyfrom(source_frame)`` - -:param other: (crwdns335966:0crwdne335966:0) crwdns335968:0``AudioFrame``crwdne335968:0""" - - def __len__(self) -> int: - ... + """Overwrite the data in this ``AudioFrame`` with the data from another ``AudioFrame`` instance. - def __setitem__(self, key: int, value: int) -> None: - ... + Example: ``my_frame.copyfrom(source_frame)`` - def __getitem__(self, key: int) -> int: - ... \ No newline at end of file + :param other: ``AudioFrame`` instance from which to copy the data. + """ + def __len__(self) -> int: ... + def __setitem__(self, key: int, value: int) -> None: ... + def __getitem__(self, key: int) -> int: ... diff --git a/lang/lol/typeshed/stdlib/microbit/compass.pyi b/lang/lol/typeshed/stdlib/microbit/compass.pyi index 38bf5a4..c74a47b 100644 --- a/lang/lol/typeshed/stdlib/microbit/compass.pyi +++ b/lang/lol/typeshed/stdlib/microbit/compass.pyi @@ -1,70 +1,78 @@ -"""crwdns330004:0crwdne330004:0 (crwdns330002:0crwdne330002:0)""" +"""Use the built-in compass. +""" def calibrate() -> None: - """crwdns330008:0crwdne330008:0 (crwdns330006:0crwdne330006:0) + """Starts the calibration process. -Example: ``compass.calibrate()`` + Example: ``compass.calibrate()`` -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.""" + 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: - """crwdns330012:0crwdne330012:0 (crwdns330010:0crwdne330010:0) + """Check is the compass is calibrated. -Example: ``compass.is_calibrated()`` + Example: ``compass.is_calibrated()`` -:return: ``True`` if the compass has been successfully calibrated, ``False`` otherwise.""" + :return: ``True`` if the compass has been successfully calibrated, ``False`` otherwise. + """ ... def clear_calibration() -> None: - """crwdns330016:0crwdne330016:0 (crwdns330014:0crwdne330014:0) + """Undoes the calibration, making the compass uncalibrated again. -Example: ``compass.clear_calibration()``""" + Example: ``compass.clear_calibration()`` + """ ... def get_x() -> int: - """crwdns330020:0``x``crwdne330020:0 (crwdns330018:0crwdne330018:0) + """Get the magnetic field strength on the ``x`` axis. -Example: ``compass.get_x()`` + Example: ``compass.get_x()`` -Call ``calibrate`` first or the results will be inaccurate. + Call ``calibrate`` first or the results will be inaccurate. -:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" + :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. + """ ... def get_y() -> int: - """crwdns330024:0``y``crwdne330024:0 (crwdns330022:0crwdne330022:0) + """Get the magnetic field strength on the ``y`` axis. -Example: ``compass.get_y()`` + Example: ``compass.get_y()`` -Call ``calibrate`` first or the results will be inaccurate. + Call ``calibrate`` first or the results will be inaccurate. -:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" + :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. + """ ... def get_z() -> int: - """crwdns330028:0``z``crwdne330028:0 (crwdns330026:0crwdne330026:0) + """Get the magnetic field strength on the ``z`` axis. -Example: ``compass.get_z()`` + Example: ``compass.get_z()`` -Call ``calibrate`` first or the results will be inaccurate. + Call ``calibrate`` first or the results will be inaccurate. -:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" + :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. + """ ... def heading() -> int: - """crwdns330032:0crwdne330032:0 (crwdns330030:0crwdne330030:0) + """Get the compass heading. -Example: ``compass.heading()`` + Example: ``compass.heading()`` -:return: An integer in the range from 0 to 360, representing the angle in degrees, clockwise, with north as 0.""" + :return: An integer in the range from 0 to 360, representing the angle in degrees, clockwise, with north as 0. + """ ... def get_field_strength() -> int: - """crwdns330036:0crwdne330036:0 (crwdns330034:0crwdne330034:0) + """Get the magnitude of the magnetic field around the device. -Example: ``compass.get_field_strength()`` + Example: ``compass.get_field_strength()`` -:return: An integer indication of the magnitude of the magnetic field in nano tesla.""" - ... \ No newline at end of file + :return: An integer indication of the magnitude of the magnetic field in nano tesla.""" + ... diff --git a/lang/lol/typeshed/stdlib/microbit/display.pyi b/lang/lol/typeshed/stdlib/microbit/display.pyi index cf2dd2e..aa4013e 100644 --- a/lang/lol/typeshed/stdlib/microbit/display.pyi +++ b/lang/lol/typeshed/stdlib/microbit/display.pyi @@ -1,92 +1,115 @@ -"""crwdns330040:0crwdne330040:0 (crwdns330038:0crwdne330038:0)""" +"""Show text, images and animations on the 5×5 LED display. +""" + from ..microbit import Image from typing import Union, overload, Iterable def get_pixel(x: int, y: int) -> int: - """crwdns330044:0``x``crwdnd330044:0``y``crwdne330044:0 (crwdns330042:0crwdne330042:0) + """Get the brightness of the LED at column ``x`` and row ``y``. -Example: ``display.get_pixel(0, 0)`` + Example: ``display.get_pixel(0, 0)`` -:param x: (crwdns330046:0crwdne330046:0) crwdns330048:0crwdne330048:0 -:param y: (crwdns330050:0crwdne330050:0) crwdns330052:0crwdne330052:0 -:return: A number between 0 (off) and 9 (bright)""" + :param x: The display column (0..4) + :param y: The display row (0..4) + :return: A number between 0 (off) and 9 (bright) + """ ... def set_pixel(x: int, y: int, value: int) -> None: - """crwdns330056:0``x``crwdnd330056:0``y``crwdne330056:0 (crwdns330054:0crwdne330054:0) + """Set the brightness of the LED at column ``x`` and row ``y``. -Example: ``display.set_pixel(0, 0, 9)`` + Example: ``display.set_pixel(0, 0, 9)`` -:param x: (crwdns330062:0crwdne330062:0) crwdns330064:0crwdne330064:0 -:param y: (crwdns330066:0crwdne330066:0) crwdns330068:0crwdne330068:0 -:param value: (crwdns330058:0crwdne330058:0) crwdns330060:0crwdne330060:0""" + :param x: The display column (0..4) + :param y: The display row (0..4) + :param value: The brightness between 0 (off) and 9 (bright) + """ ... def clear() -> None: - """crwdns330072:0crwdne330072:0 (crwdns330070:0crwdne330070:0) + """Set the brightness of all LEDs to 0 (off). -Example: ``display.clear()``""" + Example: ``display.clear()`` + """ ... -def show(image: Union[str, float, int, Image, Iterable[Image]], delay: int=400, wait: bool=True, loop: bool=False, clear: bool=False) -> None: - """crwdns330076:0crwdne330076:0 (crwdns330074:0crwdne330074:0) +def show( + image: Union[str, float, int, Image, Iterable[Image]], + delay: int = 400, + wait: bool = True, + loop: bool = False, + clear: bool = False, +) -> None: + """Shows images, letters or digits on the LED display. -Example: ``display.show(Image.HEART)`` + Example: ``display.show(Image.HEART)`` -When ``image`` is an image or a list of images then each image is displayed in turn. -If ``image`` is a string or number, each letter or digit is displayed in turn. + When ``image`` is an image or a list of images then each image is displayed in turn. + If ``image`` is a string or number, each letter or digit is displayed in turn. -:param image: (crwdns330086:0crwdne330086:0) crwdns330088:0crwdne330088:0 -:param delay: (crwdns330082:0crwdne330082:0) crwdns330084:0``delay``crwdne330084:0 -:param wait: (crwdns330094:0crwdne330094:0) crwdns330096:0``wait``crwdnd330096:0``True``crwdne330096:0 -:param loop: (crwdns330090:0crwdne330090:0) crwdns330092:0``loop``crwdnd330092:0``True``crwdne330092:0 -:param clear: (crwdns330078:0crwdne330078:0) crwdns330080:0``clear``crwdnd330080:0``True``crwdne330080:0 + :param image: A string, number, image or list of images to show. + :param delay: Each letter, digit or image is shown with ``delay`` milliseconds between them. + :param wait: If ``wait`` is ``True``, this function will block until the animation is finished, otherwise the animation will happen in the background. + :param loop: If ``loop`` is ``True``, the animation will repeat forever. + :param clear: If ``clear`` is ``True``, the display will be cleared after the sequence has finished. -The ``wait``, ``loop`` and ``clear`` arguments must be specified using their keyword.""" + The ``wait``, ``loop`` and ``clear`` arguments must be specified using their keyword. + """ ... -def scroll(text: Union[str, float, int], delay: int=150, wait: bool=True, loop: bool=False, monospace: bool=False) -> None: - """crwdns330100:0crwdne330100:0 (crwdns330098:0crwdne330098:0) - -Example: ``display.scroll('micro:bit')`` - -:param text: (crwdns330114:0crwdne330114:0) crwdns330116:0``text``crwdnd330116:0``str()``crwdne330116:0 -:param delay: (crwdns330102:0crwdne330102:0) crwdns330104:0``delay``crwdne330104:0 -:param wait: (crwdns330118:0crwdne330118:0) crwdns330120:0``wait``crwdnd330120:0``True``crwdne330120:0 -:param loop: (crwdns330106:0crwdne330106:0) crwdns330108:0``loop``crwdnd330108:0``True``crwdne330108:0 -:param monospace: (crwdns330110:0crwdne330110:0) crwdns330112:0``monospace``crwdnd330112:0``True``crwdne330112:0 - -The ``wait``, ``loop`` and ``monospace`` arguments must be specified -using their keyword.""" +def scroll( + text: Union[str, float, int], + delay: int = 150, + wait: bool = True, + loop: bool = False, + monospace: bool = False, +) -> None: + """Scrolls a number or text on the LED display. + + Example: ``display.scroll('micro:bit')`` + + :param text: The string to scroll. If ``text`` is an integer or float it is first converted to a string using ``str()``. + :param delay: The ``delay`` parameter controls how fast the text is scrolling. + :param wait: If ``wait`` is ``True``, this function will block until the animation is finished, otherwise the animation will happen in the background. + :param loop: If ``loop`` is ``True``, the animation will repeat forever. + :param monospace: 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. + + The ``wait``, ``loop`` and ``monospace`` arguments must be specified + using their keyword. + """ ... def on() -> None: - """crwdns330124:0crwdne330124:0 (crwdns330122:0crwdne330122:0) + """Turn on the LED display. -Example: ``display.on()``""" + Example: ``display.on()`` + """ ... def off() -> None: - """crwdns330128:0crwdne330128:0 (crwdns330126:0crwdne330126:0) + """Turn off the LED display (disabling the display allows you to re-use the GPIO pins for other purposes). -Example: ``display.off()``""" + Example: ``display.off()`` + """ ... def is_on() -> bool: - """crwdns330132:0crwdne330132:0 (crwdns330130:0crwdne330130:0) + """Check whether the LED display is enabled. -Example: ``display.is_on()`` + Example: ``display.is_on()`` -:return: ``True`` if the display is on, otherwise returns ``False``.""" + :return: ``True`` if the display is on, otherwise returns ``False``. + """ ... def read_light_level() -> int: - """crwdns330136:0crwdne330136:0 (crwdns330134:0crwdne330134:0) + """Read the light level. -Example: ``display.read_light_level()`` + Example: ``display.read_light_level()`` -Uses the display's LEDs in reverse-bias mode to sense the amount of light -falling on the display. + Uses the display's LEDs in reverse-bias mode to sense the amount of light + falling on the display. -:return: An integer between 0 and 255 representing the light level, with larger meaning more light.""" - ... \ No newline at end of file + :return: An integer between 0 and 255 representing the light level, with larger meaning more light. + """ + ... diff --git a/lang/lol/typeshed/stdlib/microbit/i2c.pyi b/lang/lol/typeshed/stdlib/microbit/i2c.pyi index c126204..df26efa 100644 --- a/lang/lol/typeshed/stdlib/microbit/i2c.pyi +++ b/lang/lol/typeshed/stdlib/microbit/i2c.pyi @@ -1,49 +1,57 @@ -"""crwdns330140:0crwdne330140:0 (crwdns330138:0crwdne330138:0)""" +"""Communicate with devices using the I²C bus protocol. +""" + from _typeshed import ReadableBuffer from ..microbit import MicroBitDigitalPin, pin19, pin20 from typing import List -def init(freq: int=100000, sda: MicroBitDigitalPin=pin20, scl: MicroBitDigitalPin=pin19) -> None: - """crwdns330144:0crwdne330144:0 (crwdns330142:0crwdne330142:0) +def init( + freq: int = 100000, sda: MicroBitDigitalPin = pin20, scl: MicroBitDigitalPin = pin19 +) -> None: + """Re-initialize a peripheral. -Example: ``i2c.init()`` + Example: ``i2c.init()`` -:param freq: (crwdns330146:0crwdne330146:0) crwdns330148:0crwdne330148:0 -:param sda: (crwdns330154:0crwdne330154:0) crwdns330156:0``sda``crwdne330156:0 -:param scl: (crwdns330150:0crwdne330150:0) crwdns330152:0``scl``crwdne330152:0 + :param freq: clock frequency + :param sda: ``sda`` pin (default 20) + :param scl: ``scl`` pin (default 19) -On a micro:bit V1 board, changing the I²C pins from defaults will make -the accelerometer and compass stop working, as they are connected -internally to those pins. This warning does not apply to the **V2** -revision of the micro:bit as this has `separate I²C lines `_ -for the motion sensors and the edge connector.""" + On a micro:bit V1 board, changing the I²C pins from defaults will make + the accelerometer and compass stop working, as they are connected + internally to those pins. This warning does not apply to the **V2** + revision of the micro:bit as this has `separate I²C lines `_ + for the motion sensors and the edge connector. + """ ... def scan() -> List[int]: - """crwdns330160:0crwdne330160:0 (crwdns330158:0crwdne330158:0) + """Scan the bus for devices. -Example: ``i2c.scan()`` + Example: ``i2c.scan()`` -:return: A list of 7-bit addresses corresponding to those devices that responded to the scan.""" + :return: A list of 7-bit addresses corresponding to those devices that responded to the scan. + """ ... -def read(addr: int, n: int, repeat: bool=False) -> bytes: - """crwdns330164:0crwdne330164:0 (crwdns330162:0crwdne330162:0) +def read(addr: int, n: int, repeat: bool = False) -> bytes: + """Read bytes from a device. -Example: ``i2c.read(0x50, 64)`` + Example: ``i2c.read(0x50, 64)`` -:param addr: (crwdns330166:0crwdne330166:0) crwdns330168:0crwdne330168:0 -:param n: (crwdns330170:0crwdne330170:0) crwdns330172:0crwdne330172:0 -:param repeat: (crwdns330174:0crwdne330174:0) crwdns330176:0``True``crwdne330176:0 -:return: The bytes read""" + :param addr: The 7-bit address of the device + :param n: The number of bytes to read + :param repeat: If ``True``, no stop bit will be sent + :return: The bytes read + """ ... -def write(addr: int, buf: ReadableBuffer, repeat: bool=False) -> None: - """crwdns330180:0crwdne330180:0 (crwdns330178:0crwdne330178:0) +def write(addr: int, buf: ReadableBuffer, repeat: bool = False) -> None: + """Write bytes to a device. -Example: ``i2c.write(0x50, bytes([1, 2, 3]))`` + Example: ``i2c.write(0x50, bytes([1, 2, 3]))`` -:param addr: (crwdns330182:0crwdne330182:0) crwdns330184:0crwdne330184:0 -:param buf: (crwdns330186:0crwdne330186:0) crwdns330188:0crwdne330188:0 -:param repeat: (crwdns330190:0crwdne330190:0) crwdns330192:0``True``crwdne330192:0""" - ... \ No newline at end of file + :param addr: The 7-bit address of the device + :param buf: A buffer containing the bytes to write + :param repeat: If ``True``, no stop bit will be sent + """ + ... diff --git a/lang/lol/typeshed/stdlib/microbit/microphone.pyi b/lang/lol/typeshed/stdlib/microbit/microphone.pyi index bc5d3a3..68e8f3a 100644 --- a/lang/lol/typeshed/stdlib/microbit/microphone.pyi +++ b/lang/lol/typeshed/stdlib/microbit/microphone.pyi @@ -1,62 +1,70 @@ -"""crwdns330196:0crwdne330196:0 (crwdns330194:0crwdne330194:0)""" +"""Respond to sound using the built-in microphone (V2 only). +""" + from typing import Optional, Tuple from ..microbit import SoundEvent def current_event() -> Optional[SoundEvent]: - """crwdns330200:0crwdne330200:0 (crwdns330198:0crwdne330198:0) + """Get the last recorded sound event -Example: ``microphone.current_event()`` + Example: ``microphone.current_event()`` -:return: The event, ``SoundEvent('loud')`` or ``SoundEvent('quiet')``.""" + :return: The event, ``SoundEvent('loud')`` or ``SoundEvent('quiet')``. + """ ... def was_event(event: SoundEvent) -> bool: - """crwdns330204:0crwdne330204:0 (crwdns330202:0crwdne330202:0) + """Check if a sound was heard at least once since the last call. -Example: ``microphone.was_event(SoundEvent.LOUD)`` + Example: ``microphone.was_event(SoundEvent.LOUD)`` -This call clears the sound history before returning. + This call clears the sound history before returning. -:param event: (crwdns330206:0crwdne330206:0) crwdns330208:0``SoundEvent.LOUD``crwdnd330208:0``SoundEvent.QUIET``crwdne330208:0 -:return: ``True`` if sound was heard at least once since the last call, otherwise ``False``.""" + :param event: The event to check for, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET`` + :return: ``True`` if sound was heard at least once since the last call, otherwise ``False``. + """ ... def is_event(event: SoundEvent) -> bool: - """crwdns330212:0crwdne330212:0 (crwdns330210:0crwdne330210:0) + """Check the most recent sound event detected. -Example: ``microphone.is_event(SoundEvent.LOUD)`` + Example: ``microphone.is_event(SoundEvent.LOUD)`` -This call does not clear the sound event history. + This call does not clear the sound event history. -:param event: (crwdns330214:0crwdne330214:0) crwdns330216:0``SoundEvent.LOUD``crwdnd330216:0``SoundEvent.QUIET``crwdne330216:0 -:return: ``True`` if sound was the most recent heard, ``False`` otherwise.""" + :param event: The event to check for, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET`` + :return: ``True`` if sound was the most recent heard, ``False`` otherwise. + """ ... def get_events() -> Tuple[SoundEvent, ...]: - """crwdns330220:0crwdne330220:0 (crwdns330218:0crwdne330218:0) + """Get the sound event history as a tuple. -Example: ``microphone.get_events()`` + Example: ``microphone.get_events()`` -This call clears the sound history before returning. + This call clears the sound history before returning. -:return: A tuple of the event history with the most recent event last.""" + :return: A tuple of the event history with the most recent event last. + """ ... def set_threshold(event: SoundEvent, value: int) -> None: - """crwdns330224:0crwdne330224:0 (crwdns330222:0crwdne330222:0) + """Set the threshold for a sound event. -Example: ``microphone.set_threshold(SoundEvent.LOUD, 250)`` + Example: ``microphone.set_threshold(SoundEvent.LOUD, 250)`` -A high threshold means the event will only trigger if the sound is very loud (>= 250 in the example). + A high threshold means the event will only trigger if the sound is very loud (>= 250 in the example). -:param event: (crwdns330226:0crwdne330226:0) crwdns330228:0``SoundEvent.LOUD``crwdnd330228:0``SoundEvent.QUIET``crwdne330228:0 -:param value: (crwdns330230:0crwdne330230:0) crwdns330232:0crwdne330232:0""" + :param event: A sound event, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET``. + :param value: The threshold level in the range 0-255. + """ ... def sound_level() -> int: - """crwdns330236:0crwdne330236:0 (crwdns330234:0crwdne330234:0) + """Get the sound pressure level. -Example: ``microphone.sound_level()`` + Example: ``microphone.sound_level()`` -:return: A representation of the sound pressure level in the range 0 to 255.""" - ... \ No newline at end of file + :return: A representation of the sound pressure level in the range 0 to 255. + """ + ... diff --git a/lang/lol/typeshed/stdlib/microbit/speaker.pyi b/lang/lol/typeshed/stdlib/microbit/speaker.pyi index b5c339e..5a74a4d 100644 --- a/lang/lol/typeshed/stdlib/microbit/speaker.pyi +++ b/lang/lol/typeshed/stdlib/microbit/speaker.pyi @@ -1,15 +1,18 @@ -"""crwdns330240:0crwdne330240:0 (crwdns330238:0crwdne330238:0)""" +"""Control the built-in speaker (V2 only). +""" def off() -> None: - """crwdns330244:0crwdne330244:0 (crwdns330242:0crwdne330242:0) + """Turn the speaker off. -Example: ``speaker.off()`` + Example: ``speaker.off()`` -This does not disable sound output to an edge connector pin.""" + This does not disable sound output to an edge connector pin. + """ ... def on() -> None: - """crwdns330248:0crwdne330248:0 (crwdns330246:0crwdne330246:0) + """Turn the speaker on. -Example: ``speaker.on()``""" - ... \ No newline at end of file + Example: ``speaker.on()`` + """ + ... diff --git a/lang/lol/typeshed/stdlib/microbit/spi.pyi b/lang/lol/typeshed/stdlib/microbit/spi.pyi index d68ba4f..09c4046 100644 --- a/lang/lol/typeshed/stdlib/microbit/spi.pyi +++ b/lang/lol/typeshed/stdlib/microbit/spi.pyi @@ -1,47 +1,60 @@ -"""crwdns330252:0crwdne330252:0 (crwdns330250:0crwdne330250:0)""" +"""Communicate with devices using the serial peripheral interface (SPI) bus. +""" + from _typeshed import ReadableBuffer, WriteableBuffer from ..microbit import pin13, pin14, pin15, MicroBitDigitalPin -def init(baudrate: int=1000000, bits: int=8, mode: int=0, sclk: MicroBitDigitalPin=pin13, mosi: MicroBitDigitalPin=pin15, miso: MicroBitDigitalPin=pin14) -> None: - """crwdns330256:0crwdne330256:0 (crwdns330254:0crwdne330254:0) - -Example: ``spi.init()`` - -For correct communication, the parameters have to be the same on both communicating devices. - -:param baudrate: (crwdns330258:0crwdne330258:0) crwdns330260:0crwdne330260:0 -:param bits: (crwdns330262:0crwdne330262:0) crwdns334412:0crwdne334412:0 -:param mode: (crwdns330270:0crwdne330270:0) crwdns330272:0crwdne330272:0 -:param sclk: (crwdns330278:0crwdne330278:0) crwdns330280:0crwdne330280:0 -:param mosi: (crwdns330274:0crwdne330274:0) crwdns330276:0crwdne330276:0 -:param miso: (crwdns330266:0crwdne330266:0) crwdns330268:0crwdne330268:0""" +def init( + baudrate: int = 1000000, + bits: int = 8, + mode: int = 0, + sclk: MicroBitDigitalPin = pin13, + mosi: MicroBitDigitalPin = pin15, + miso: MicroBitDigitalPin = pin14, +) -> None: + """Initialize SPI communication. + + Example: ``spi.init()`` + + For correct communication, the parameters have to be the same on both communicating devices. + + :param baudrate: The speed of communication. + :param bits: The width in bits of each transfer. Currently only ``bits=8`` is supported. However, this may change in the future. + :param mode: Determines the combination of clock polarity and phase - `see online table `_. + :param sclk: sclk pin (default 13) + :param mosi: mosi pin (default 15) + :param miso: miso pin (default 14) + """ ... -def read(nbytes: int, out: int=0) -> bytes: - """crwdns330284:0``nbytes``crwdnd330284:0``out``crwdne330284:0 (crwdns330282:0crwdne330282:0) +def read(nbytes: int, out: int = 0) -> bytes: + """Read at most ``nbytes`` while continuously writing the single byte given by ``out``. -Example: ``spi.read(64)`` + Example: ``spi.read(64)`` -:param nbytes: (crwdns330286:0crwdne330286:0) crwdns330288:0crwdne330288:0 -:param out: (crwdns360362:0crwdne360362:0) crwdns360364:0crwdne360364:0 -:return: The bytes read.""" + :param nbytes: Maximum number of bytes to read. + :param out: The byte value to write (default 0). + :return: The bytes read. + """ ... def write(buffer: ReadableBuffer) -> None: - """crwdns330292:0crwdne330292:0 (crwdns330290:0crwdne330290:0) + """Write bytes to the bus. -Example: ``spi.write(bytes([1, 2, 3]))`` + Example: ``spi.write(bytes([1, 2, 3]))`` -:param buffer: (crwdns330294:0crwdne330294:0) crwdns330296:0crwdne330296:0""" + :param buffer: A buffer to read data from. + """ ... def write_readinto(out: WriteableBuffer, in_: ReadableBuffer) -> None: - """crwdns330300:0``out``crwdnd330300:0``in_``crwdne330300:0 (crwdns330298:0crwdne330298:0) + """Write the ``out`` buffer to the bus and read any response into the ``in_`` buffer. -Example: ``spi.write_readinto(out_buffer, in_buffer)`` + Example: ``spi.write_readinto(out_buffer, in_buffer)`` -The length of the buffers should be the same. The buffers can be the same object. + The length of the buffers should be the same. The buffers can be the same object. -:param out: (crwdns330306:0crwdne330306:0) crwdns330308:0crwdne330308:0 -:param in_: (crwdns330302:0crwdne330302:0) crwdns330304:0crwdne330304:0""" - ... \ No newline at end of file + :param out: The buffer to write any response to. + :param in_: The buffer to read data from. + """ + ... diff --git a/lang/lol/typeshed/stdlib/microbit/uart.pyi b/lang/lol/typeshed/stdlib/microbit/uart.pyi index 3f791aa..2ab650f 100644 --- a/lang/lol/typeshed/stdlib/microbit/uart.pyi +++ b/lang/lol/typeshed/stdlib/microbit/uart.pyi @@ -1,79 +1,96 @@ -"""crwdns330312:0crwdne330312:0 (crwdns330310:0crwdne330310:0)""" +"""Communicate with a device using a serial interface. +""" + from _typeshed import WriteableBuffer from ..microbit import MicroBitDigitalPin from typing import Optional, Union -ODD: int -"""crwdns330316:0crwdne330316:0 (crwdns330314:0crwdne330314:0)""" -EVEN: int -"""crwdns330320:0crwdne330320:0 (crwdns330318:0crwdne330318:0)""" - -def init(baudrate: int=9600, bits: int=8, parity: Optional[int]=None, stop: int=1, tx: Optional[MicroBitDigitalPin]=None, rx: Optional[MicroBitDigitalPin]=None) -> None: - """crwdns330324:0crwdne330324:0 (crwdns330322:0crwdne330322:0) - -Example: ``uart.init(115200, tx=pin0, rx=pin1)`` -:param baudrate: (crwdns330326:0crwdne330326:0) crwdns330328:0crwdne330328:0 -:param bits: (crwdns330330:0crwdne330330:0) crwdns330332:0crwdne330332:0 -:param parity: (crwdns330334:0crwdne330334:0) crwdns330336:0``None``crwdnd330336:0``uart.ODD``crwdnd330336:0``uart.EVEN``crwdne330336:0 -:param stop: (crwdns330342:0crwdne330342:0) crwdns330344:0crwdne330344:0 -:param tx: (crwdns330346:0crwdne330346:0) crwdns330348:0crwdne330348:0 -:param rx: (crwdns330338:0crwdne330338:0) crwdns330340:0crwdne330340:0 - -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. +ODD: int +"""Odd parity""" -For more details see `the online documentation `_.""" +EVEN: int +"""Even parity""" + +def init( + baudrate: int = 9600, + bits: int = 8, + parity: Optional[int] = None, + stop: int = 1, + tx: Optional[MicroBitDigitalPin] = None, + rx: Optional[MicroBitDigitalPin] = None, +) -> None: + """Initialize serial communication. + + Example: ``uart.init(115200, tx=pin0, rx=pin1)`` + + :param baudrate: The speed of communication. + :param bits: The size of bytes being transmitted. micro:bit only supports 8. + :param parity: How parity is checked, ``None``, ``uart.ODD`` or ``uart.EVEN``. + :param stop: The number of stop bits, has to be 1 for micro:bit. + :param tx: Transmitting pin. + :param rx: Receiving pin. + + 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. + + For more details see `the online documentation `_. + """ ... def any() -> bool: - """crwdns334688:0crwdne334688:0 (crwdns330350:0crwdne330350:0) + """Check if any data is waiting. -Example: ``uart.any()`` + Example: ``uart.any()`` -:return: ``True`` if any data is waiting, else ``False``.""" + :return: ``True`` if any data is waiting, else ``False``. + """ ... -def read(nbytes: Optional[int]=None) -> Optional[bytes]: - """crwdns330356:0crwdne330356:0 (crwdns330354:0crwdne330354:0) +def read(nbytes: Optional[int] = None) -> Optional[bytes]: + """Read bytes. -Example: ``uart.read()`` + Example: ``uart.read()`` -:param nbytes: (crwdns330358:0crwdne330358:0) crwdns330360:0``nbytes``crwdne330360:0 -:return: A bytes object or ``None`` on timeout""" + :param nbytes: If ``nbytes`` is specified then read at most that many bytes, otherwise read as many bytes as possible + :return: A bytes object or ``None`` on timeout + """ ... -def readinto(buf: WriteableBuffer, nbytes: Optional[int]=None) -> Optional[int]: - """crwdns330364:0``buf``crwdne330364:0 (crwdns330362:0crwdne330362:0) +def readinto(buf: WriteableBuffer, nbytes: Optional[int] = None) -> Optional[int]: + """Read bytes into the ``buf``. -Example: ``uart.readinto(input_buffer)`` + Example: ``uart.readinto(input_buffer)`` -:param buf: (crwdns330366:0crwdne330366:0) crwdns330368:0crwdne330368:0 -:param nbytes: (crwdns330370:0crwdne330370:0) crwdns330372:0``nbytes``crwdnd330372:0``len(buf)``crwdne330372:0 -:return: number of bytes read and stored into ``buf`` or ``None`` on timeout.""" + :param buf: The buffer to write to. + :param nbytes: If ``nbytes`` is specified then read at most that many bytes, otherwise read ``len(buf)`` bytes. + :return: number of bytes read and stored into ``buf`` or ``None`` on timeout. + """ ... def readline() -> Optional[bytes]: - """crwdns330376:0crwdne330376:0 (crwdns330374:0crwdne330374:0) + """Read a line, ending in a newline character. -Example: ``uart.readline()`` + Example: ``uart.readline()`` -:return: The line read or ``None`` on timeout. The newline character is included in the returned bytes.""" + :return: The line read or ``None`` on timeout. The newline character is included in the returned bytes. + """ ... def write(buf: Union[bytes, str]) -> Optional[int]: - """crwdns330380:0crwdne330380:0 (crwdns330378:0crwdne330378:0) + """Write a buffer to the bus. -Example: ``uart.write('hello world')`` + Example: ``uart.write('hello world')`` -:param buf: (crwdns330382:0crwdne330382:0) crwdns330384:0crwdne330384:0 -:return: The number of bytes written, or ``None`` on timeout. + :param buf: A bytes object or a string. + :return: The number of bytes written, or ``None`` on timeout. -Examples:: + Examples:: - uart.write('hello world') - uart.write(b'hello world') - uart.write(bytes([1, 2, 3]))""" - ... \ No newline at end of file + uart.write('hello world') + uart.write(b'hello world') + uart.write(bytes([1, 2, 3])) + """ + ... diff --git a/lang/lol/typeshed/stdlib/micropython.pyi b/lang/lol/typeshed/stdlib/micropython.pyi index 014befe..7a6079f 100644 --- a/lang/lol/typeshed/stdlib/micropython.pyi +++ b/lang/lol/typeshed/stdlib/micropython.pyi @@ -1,131 +1,144 @@ -"""crwdns330388:0crwdne330388:0 (crwdns330386:0crwdne330386:0)""" +"""MicroPython internals.""" + from typing import Any, TypeVar, overload -_T = TypeVar('_T') + +_T = TypeVar("_T") def const(expr: _T) -> _T: - """crwdns330392:0crwdne330392:0 (crwdns330390:0crwdne330390:0) + """Used to declare that the expression is a constant so that the compiler can + optimise it. -The use of this function should be as follows:: + The use of this function should be as follows:: - from micropython import const - CONST_X = const(123) - CONST_Y = const(2 * CONST_X + 1) + from micropython import const + CONST_X = const(123) + CONST_Y = const(2 * CONST_X + 1) -Constants declared this way are still accessible as global variables from -outside the module they are declared in. On the other hand, if a constant -begins with an underscore then it is hidden, it is not available as a -global variable, and does not take up any memory during execution. + Constants declared this way are still accessible as global variables from + outside the module they are declared in. On the other hand, if a constant + begins with an underscore then it is hidden, it is not available as a + global variable, and does not take up any memory during execution. -:param expr: (crwdns330394:0crwdne330394:0) crwdns330396:0crwdne330396:0""" + :param expr: A constant expression. + """ ... @overload def opt_level() -> int: - """crwdns330400:0crwdne330400:0 (crwdns330398:0crwdne330398:0) + """Get the current optimisation level for the compilation of scripts. -Example: ``micropython.opt_level()`` + Example: ``micropython.opt_level()`` -The optimisation level controls the following compilation features: + The optimisation level controls the following compilation features: -- Assertions: at level 0 assertion statements are enabled and compiled - into the bytecode; at levels 1 and higher assertions are not compiled. + - Assertions: at level 0 assertion statements are enabled and compiled + into the bytecode; at levels 1 and higher assertions are not compiled. -- Built-in ``__debug__`` variable: at level 0 this variable expands to - True; at levels 1 and higher it expands to False. + - Built-in ``__debug__`` variable: at level 0 this variable expands to + True; at levels 1 and higher it expands to False. -- Source-code line numbers: at levels 0, 1 and 2 source-code line number - are stored along with the bytecode so that exceptions can report the - line number they occurred at; at levels 3 and higher line numbers are - not stored. + - Source-code line numbers: at levels 0, 1 and 2 source-code line number + are stored along with the bytecode so that exceptions can report the + line number they occurred at; at levels 3 and higher line numbers are + not stored. -:return: An integer representing the current level.""" + :return: An integer representing the current level. + """ ... @overload def opt_level(level: int) -> None: - """crwdns330404:0crwdne330404:0 (crwdns330402:0crwdne330402:0) + """Sets the optimisation level for subsequent compilation of scripts. -Example: ``micropython.opt_level(1)`` + Example: ``micropython.opt_level(1)`` -The optimisation level controls the following compilation features: + The optimisation level controls the following compilation features: -- Assertions: at level 0 assertion statements are enabled and compiled - into the bytecode; at levels 1 and higher assertions are not compiled. + - Assertions: at level 0 assertion statements are enabled and compiled + into the bytecode; at levels 1 and higher assertions are not compiled. -- Built-in ``__debug__`` variable: at level 0 this variable expands to - True; at levels 1 and higher it expands to False. + - Built-in ``__debug__`` variable: at level 0 this variable expands to + True; at levels 1 and higher it expands to False. -- Source-code line numbers: at levels 0, 1 and 2 source-code line number - are stored along with the bytecode so that exceptions can report the - line number they occurred at; at levels 3 and higher line numbers are - not stored. + - Source-code line numbers: at levels 0, 1 and 2 source-code line number + are stored along with the bytecode so that exceptions can report the + line number they occurred at; at levels 3 and higher line numbers are + not stored. -The default optimisation level is usually level 0. + The default optimisation level is usually level 0. -:param level: (crwdns330406:0crwdne330406:0) crwdns330408:0crwdne330408:0""" + :param level: An integer optimisation level. + """ ... -def mem_info(verbose: Any=None) -> None: - """crwdns330412:0crwdne330412:0 (crwdns330410:0crwdne330410:0) +def mem_info(verbose: Any = None) -> None: + """Print information about currently used memory. -Example: ``micropython.mem_info()`` + Example: ``micropython.mem_info()`` -:param verbose: (crwdns330414:0crwdne330414:0) crwdns330416:0``verbose``crwdne330416:0""" + :param verbose: If the ``verbose`` argument is given then extra information is printed. + """ ... -def qstr_info(verbose: Any=None) -> None: - """crwdns330420:0crwdne330420:0 (crwdns330418:0crwdne330418:0) +def qstr_info(verbose: Any = None) -> None: + """Print information about currently interned strings. -Example: ``micropython.qstr_info()`` + Example: ``micropython.qstr_info()`` -:param verbose: (crwdns330422:0crwdne330422:0) crwdns330424:0``verbose``crwdne330424:0 + :param verbose: If the ``verbose`` argument is given then extra information is printed. -The information that is printed is implementation dependent, but currently -includes the number of interned strings and the amount of RAM they use. In -verbose mode it prints out the names of all RAM-interned strings.""" + The information that is printed is implementation dependent, but currently + includes the number of interned strings and the amount of RAM they use. In + verbose mode it prints out the names of all RAM-interned strings. + """ ... def stack_use() -> int: - """crwdns330428:0crwdne330428:0 (crwdns330426:0crwdne330426:0) + """Return an integer representing the current amount of stack that is being + used. -Example: ``micropython.stack_use()`` + Example: ``micropython.stack_use()`` -The absolute value of this is not particularly useful, rather it -should be used to compute differences in stack usage at different points. + The absolute value of this is not particularly useful, rather it + should be used to compute differences in stack usage at different points. -:return: An integer representing current stack use.""" + :return: An integer representing current stack use. + """ ... def heap_lock() -> None: - """crwdns330432:0crwdne330432:0 (crwdns330430:0crwdne330430:0) + """Lock the heap. -Example: ``micropython.heap_lock()`` + Example: ``micropython.heap_lock()`` -When locked no memory allocation can occur and a ``MemoryError`` will be -raised if any heap allocation is attempted.""" + When locked no memory allocation can occur and a ``MemoryError`` will be + raised if any heap allocation is attempted. + """ ... def heap_unlock() -> None: - """crwdns330436:0crwdne330436:0 (crwdns330434:0crwdne330434:0) + """Unlock the heap. -Example: ``micropython.heap_unlock()`` + Example: ``micropython.heap_unlock()`` -When locked no memory allocation can occur and a ``MemoryError`` will be -raised if any heap allocation is attempted.""" + When locked no memory allocation can occur and a ``MemoryError`` will be + raised if any heap allocation is attempted. + """ ... def kbd_intr(chr: int) -> None: - """crwdns330440:0``KeyboardInterrupt``crwdne330440:0 (crwdns330438:0crwdne330438:0) + """Set the character that will raise a ``KeyboardInterrupt`` exception. -Example: ``micropython.kbd_intr(-1)`` + Example: ``micropython.kbd_intr(-1)`` -:param chr: (crwdns330442:0crwdne330442:0) crwdns330444:0crwdne330444:0 + :param chr: Character code to raise the interrupt or -1 to disable capture of Ctrl-C. -By default this is set to 3 during script execution, corresponding to Ctrl-C. -Passing -1 to this function will disable capture of Ctrl-C, and passing 3 -will restore it. + By default this is set to 3 during script execution, corresponding to Ctrl-C. + Passing -1 to this function will disable capture of Ctrl-C, and passing 3 + will restore it. -This function can be used to prevent the capturing of Ctrl-C on the -incoming stream of characters that is usually used for the REPL, in case -that stream is used for other purposes.""" - ... \ No newline at end of file + This function can be used to prevent the capturing of Ctrl-C on the + incoming stream of characters that is usually used for the REPL, in case + that stream is used for other purposes. + """ + ... diff --git a/lang/lol/typeshed/stdlib/music.pyi b/lang/lol/typeshed/stdlib/music.pyi index e432421..5f4778b 100644 --- a/lang/lol/typeshed/stdlib/music.pyi +++ b/lang/lol/typeshed/stdlib/music.pyi @@ -1,128 +1,167 @@ -"""crwdns330448:0crwdne330448:0 (crwdns330446:0crwdne330446:0)""" +"""Create and play melodies. +""" from typing import Optional, Tuple, Union, List + from .microbit import MicroBitDigitalPin, pin0 + DADADADUM: Tuple[str, ...] -"""crwdns330452:0crwdne330452:0 (crwdns330450:0crwdne330450:0)""" +"""Melody: the opening to Beethoven’s 5th Symphony in C minor.""" + ENTERTAINER: Tuple[str, ...] -"""crwdns330456:0crwdne330456:0 (crwdns330454:0crwdne330454:0)""" +"""Melody: the opening fragment of Scott Joplin’s Ragtime classic “The Entertainer”.""" + PRELUDE: Tuple[str, ...] -"""crwdns330460:0crwdne330460:0 (crwdns330458:0crwdne330458:0)""" +"""Melody: the opening of the first Prelude in C Major of J.S.Bach’s 48 Preludes and Fugues.""" + ODE: Tuple[str, ...] -"""crwdns330464:0crwdne330464:0 (crwdns330462:0crwdne330462:0)""" +"""Melody: the “Ode to Joy” theme from Beethoven’s 9th Symphony in D minor.""" + NYAN: Tuple[str, ...] -"""crwdns330468:0crwdne330468:0 (crwdns330466:0crwdne330466:0) +"""Melody: the Nyan Cat theme (http://www.nyan.cat/). The composer is unknown. This is fair use for educational porpoises (as they say in New York).""" + RINGTONE: Tuple[str, ...] -"""crwdns330472:0crwdne330472:0 (crwdns330470:0crwdne330470:0) +"""Melody: something that sounds like a mobile phone ringtone. To be used to indicate an incoming message. """ + FUNK: Tuple[str, ...] -"""crwdns330476:0crwdne330476:0 (crwdns330474:0crwdne330474:0)""" +"""Melody: a funky bass line for secret agents and criminal masterminds.""" + BLUES: Tuple[str, ...] -"""crwdns330480:0crwdne330480:0 (crwdns330478:0crwdne330478:0)""" +"""Melody: a boogie-woogie 12-bar blues walking bass.""" + BIRTHDAY: Tuple[str, ...] -"""crwdns330484:0crwdne330484:0 (crwdns330482:0crwdne330482:0) +"""Melody: “Happy Birthday to You…” For copyright status see: http://www.bbc.co.uk/news/world-us-canada-34332853 """ + WEDDING: Tuple[str, ...] -"""crwdns330488:0crwdne330488:0 (crwdns330486:0crwdne330486:0)""" +"""Melody: the bridal chorus from Wagner’s opera “Lohengrin”.""" + FUNERAL: Tuple[str, ...] -"""crwdns330492:0crwdne330492:0 (crwdns330490:0crwdne330490:0)""" +"""Melody: the “funeral march” otherwise known as Frédéric Chopin’s Piano Sonata No. 2 in B♭ minor, Op. 35.""" + PUNCHLINE: Tuple[str, ...] -"""crwdns330496:0crwdne330496:0 (crwdns330494:0crwdne330494:0)""" +"""Melody: a fun fragment that signifies a joke has been made.""" + PYTHON: Tuple[str, ...] -"""crwdns330500:0crwdne330500:0 (crwdns330498:0crwdne330498:0)""" +"""Melody: John Philip Sousa’s march “Liberty Bell” aka, the theme for “Monty Python’s Flying Circus” (after which the Python programming language is named).""" + BADDY: Tuple[str, ...] -"""crwdns330504:0crwdne330504:0 (crwdns330502:0crwdne330502:0)""" +"""Melody: silent movie era entrance of a baddy.""" + CHASE: Tuple[str, ...] -"""crwdns330508:0crwdne330508:0 (crwdns330506:0crwdne330506:0)""" +"""Melody: silent movie era chase scene.""" + BA_DING: Tuple[str, ...] -"""crwdns330512:0crwdne330512:0 (crwdns330510:0crwdne330510:0)""" +"""Melody: a short signal to indicate something has happened.""" + WAWAWAWAA: Tuple[str, ...] -"""crwdns330516:0crwdne330516:0 (crwdns330514:0crwdne330514:0)""" +"""Melody: a very sad trombone.""" + JUMP_UP: Tuple[str, ...] -"""crwdns330520:0crwdne330520:0 (crwdns330518:0crwdne330518:0)""" +"""Melody: for use in a game, indicating upward movement.""" + JUMP_DOWN: Tuple[str, ...] -"""crwdns330524:0crwdne330524:0 (crwdns330522:0crwdne330522:0)""" +"""Melody: for use in a game, indicating downward movement.""" + POWER_UP: Tuple[str, ...] -"""crwdns330528:0crwdne330528:0 (crwdns330526:0crwdne330526:0)""" +"""Melody: a fanfare to indicate an achievement unlocked.""" + POWER_DOWN: Tuple[str, ...] -"""crwdns330532:0crwdne330532:0 (crwdns330530:0crwdne330530:0)""" +"""Melody: a sad fanfare to indicate an achievement lost.""" -def set_tempo(ticks: int=4, bpm: int=120) -> None: - """crwdns330536:0crwdne330536:0 (crwdns330534:0crwdne330534:0) +def set_tempo(ticks: int = 4, bpm: int = 120) -> None: + """Sets the approximate tempo for playback. -Example: ``music.set_tempo(bpm=120)`` + Example: ``music.set_tempo(bpm=120)`` -:param ticks: (crwdns330542:0crwdne330542:0) crwdns330544:0crwdne330544:0 -:param bpm: (crwdns330538:0crwdne330538:0) crwdns330540:0crwdne330540:0 + :param ticks: The number of ticks constituting a beat. + :param bpm: An integer determining how many beats per minute. -Suggested default values allow the following useful behaviour: + Suggested default values allow the following useful behaviour: -- music.set_tempo() – reset the tempo to default of ticks = 4, bpm = 120 -- music.set_tempo(ticks=8) – change the “definition” of a beat -- music.set_tempo(bpm=180) – just change the tempo + - music.set_tempo() – reset the tempo to default of ticks = 4, bpm = 120 + - music.set_tempo(ticks=8) – change the “definition” of a beat + - music.set_tempo(bpm=180) – just change the tempo -To work out the length of a tick in milliseconds is very simple arithmetic: -60000/bpm/ticks_per_beat. For the default values that’s -60000/120/4 = 125 milliseconds or 1 beat = 500 milliseconds.""" + To work out the length of a tick in milliseconds is very simple arithmetic: + 60000/bpm/ticks_per_beat. For the default values that’s + 60000/120/4 = 125 milliseconds or 1 beat = 500 milliseconds. + """ ... def get_tempo() -> Tuple[int, int]: - """crwdns330548:0``(ticks, bpm)``crwdne330548:0 (crwdns330546:0crwdne330546:0) + """Gets the current tempo as a tuple of integers: ``(ticks, bpm)``. -Example: ``ticks, beats = music.get_tempo()`` + Example: ``ticks, beats = music.get_tempo()`` -:return: The temp as a tuple with two integer values, the ticks then the beats per minute.""" + :return: The temp as a tuple with two integer values, the ticks then the beats per minute. + """ ... -def play(music: Union[str, List[str], Tuple[str, ...]], pin: Optional[MicroBitDigitalPin]=pin0, wait: bool=True, loop: bool=False) -> None: - """crwdns330552:0crwdne330552:0 (crwdns330550:0crwdne330550:0) +def play( + music: Union[str, List[str], Tuple[str, ...]], + pin: Optional[MicroBitDigitalPin] = pin0, + wait: bool = True, + loop: bool = False, +) -> None: + """Plays music. -Example: ``music.play(music.NYAN)`` + Example: ``music.play(music.NYAN)`` -:param music: (crwdns330558:0crwdne330558:0) crwdns330560:0crwdne330560:0 -:param pin: (crwdns330562:0crwdne330562:0) crwdns330564:0``pin0``crwdnd330564:0``None``crwdne330564:0 -:param wait: (crwdns330566:0crwdne330566:0) crwdns330568:0``wait``crwdnd330568:0``True``crwdne330568:0 -:param loop: (crwdns330554:0crwdne330554:0) crwdns330556:0``loop``crwdnd330556:0``True``crwdnd330556:0``stop``crwdne330556:0 + :param music: music specified in `a special notation `_ + :param pin: the output pin for use with an external speaker (default ``pin0``), ``None`` for no sound. + :param wait: If ``wait`` is set to ``True``, this function is blocking. + :param loop: If ``loop`` is set to ``True``, the tune repeats until ``stop`` is called or the blocking call is interrupted. -Many built-in melodies are defined in this module.""" + Many built-in melodies are defined in this module. + """ ... -def pitch(frequency: int, duration: int=-1, pin: Optional[MicroBitDigitalPin]=pin0, wait: bool=True) -> None: - """crwdns330572:0crwdne330572:0 (crwdns330570:0crwdne330570:0) +def pitch( + frequency: int, + duration: int = -1, + pin: Optional[MicroBitDigitalPin] = pin0, + wait: bool = True, +) -> None: + """Play a note. -Example: ``music.pitch(185, 1000)`` + Example: ``music.pitch(185, 1000)`` -:param frequency: (crwdns330578:0crwdne330578:0) crwdns330580:0crwdne330580:0 -:param duration: (crwdns330574:0crwdne330574:0) crwdns330576:0``stop``crwdne330576:0 -:param pin: (crwdns330582:0crwdne330582:0) crwdns330584:0``pin0``crwdne330584:0 -:param wait: (crwdns330586:0crwdne330586:0) crwdns330588:0``wait``crwdnd330588:0``True``crwdne330588:0 + :param frequency: An integer frequency + :param duration: A millisecond duration. If negative then sound is continuous until the next call or a call to ``stop``. + :param pin: Optional output pin (default ``pin0``). + :param wait: If ``wait`` is set to ``True``, this function is blocking. -For example, if the frequency is set to 440 and the length to -1000 then we hear a standard concert A for one second. + For example, if the frequency is set to 440 and the length to + 1000 then we hear a standard concert A for one second. -You can only play one pitch on one pin at any one time.""" + You can only play one pitch on one pin at any one time. + """ ... -def stop(pin: Optional[MicroBitDigitalPin]=pin0) -> None: - """crwdns330592:0crwdne330592:0 (crwdns330590:0crwdne330590:0) +def stop(pin: Optional[MicroBitDigitalPin] = pin0) -> None: + """Stops all music playback on the built-in speaker and any pin outputting sound. -Example: ``music.stop()`` + Example: ``music.stop()`` -:param pin: (crwdns330594:0crwdne330594:0) crwdns330596:0``music.stop(pin1)``crwdne330596:0""" + :param pin: An optional argument can be provided to specify a pin, e.g. ``music.stop(pin1)``. + """ def reset() -> None: - """crwdns330600:0crwdne330600:0 (crwdns330598:0crwdne330598:0) + """Resets ticks, bpm, duration and octave to their default values. -Example: ``music.reset()`` + Example: ``music.reset()`` -Values: -- ``ticks = 4`` -- ``bpm = 120`` -- ``duration = 4`` -- ``octave = 4``""" - ... \ No newline at end of file + Values: + - ``ticks = 4`` + - ``bpm = 120`` + - ``duration = 4`` + - ``octave = 4`` + """ + ... diff --git a/lang/lol/typeshed/stdlib/neopixel.pyi b/lang/lol/typeshed/stdlib/neopixel.pyi index 5ef04a8..2d5a749 100644 --- a/lang/lol/typeshed/stdlib/neopixel.pyi +++ b/lang/lol/typeshed/stdlib/neopixel.pyi @@ -1,81 +1,82 @@ -"""crwdns330604:0crwdne330604:0 (crwdns330602:0crwdne330602:0)""" +"""Individually addressable RGB and RGBW LED strips. +""" from .microbit import MicroBitDigitalPin from typing import Tuple class NeoPixel: + def __init__(self, pin: MicroBitDigitalPin, n: int, bpp: int = 3) -> None: + """Initialise a new strip of neopixel LEDs controlled via a pin. - def __init__(self, pin: MicroBitDigitalPin, n: int, bpp: int=3) -> None: - """crwdns330608:0crwdne330608:0 (crwdns330606:0crwdne330606:0) + Example: ``np = neopixel.NeoPixel(pin0, 8)`` -Example: ``np = neopixel.NeoPixel(pin0, 8)`` + To support RGBW neopixels, a third argument can be passed to + ``NeoPixel`` to indicate the number of bytes per pixel (``bpp``). + For RGBW, this is is 4 rather than the default of 3 for RGB and GRB. -To support RGBW neopixels, a third argument can be passed to -``NeoPixel`` to indicate the number of bytes per pixel (``bpp``). -For RGBW, this is is 4 rather than the default of 3 for RGB and GRB. + Each pixel is addressed by a position (starting from 0). Neopixels are + given RGB (red, green, blue) / RGBW (red, green, blue, white) values + between 0-255 as a tuple. For example, in RGB, ``(255,255,255)`` is + white. In RGBW, ``(255,255,255,0)`` or ``(0,0,0,255)`` is white. -Each pixel is addressed by a position (starting from 0). Neopixels are -given RGB (red, green, blue) / RGBW (red, green, blue, white) values -between 0-255 as a tuple. For example, in RGB, ``(255,255,255)`` is -white. In RGBW, ``(255,255,255,0)`` or ``(0,0,0,255)`` is white. + See `the online docs `_ for warnings and other advice. -See `the online docs `_ for warnings and other advice. - -:param pin: (crwdns330618:0crwdne330618:0) crwdns330620:0crwdne330620:0 -:param n: (crwdns330614:0crwdne330614:0) crwdns330616:0crwdne330616:0 -:param bpp: (crwdns330610:0crwdne330610:0) crwdns355240:0crwdne355240:0""" + :param pin: The pin controlling the neopixel strip. + :param n: The number of neopixels in the strip. + :param bpp: Bytes per pixel. For RGBW neopixel support, pass 4 rather than the default of 3 for RGB and GRB. + """ ... - def clear(self) -> None: - """crwdns330624:0crwdne330624:0 (crwdns330622:0crwdne330622:0) + """Clear all the pixels. -Example: ``np.clear()``""" + Example: ``np.clear()`` + """ ... - def show(self) -> None: - """crwdns330628:0crwdne330628:0 (crwdns330626:0crwdne330626:0) + """Show the pixels. -Example: ``np.show()`` + Example: ``np.show()`` -Must be called for any updates to become visible.""" + Must be called for any updates to become visible. + """ ... - def write(self) -> None: - """crwdns330632:0crwdne330632:0 (crwdns330630:0crwdne330630:0) + """Show the pixels (micro:bit V2 only). -Example: ``np.write()`` + Example: ``np.write()`` -Must be called for any updates to become visible. + Must be called for any updates to become visible. -Equivalent to ``show``.""" + Equivalent to ``show``. + """ ... - def fill(self, colour: Tuple[int, ...]) -> None: - """crwdns330636:0crwdne330636:0 (crwdns330634:0crwdne330634:0) + """Colour all pixels a given RGB/RGBW value (micro:bit V2 only). -Example: ``np.fill((0, 0, 255))`` + Example: ``np.fill((0, 0, 255))`` -:param colour: (crwdns330638:0crwdne330638:0) crwdns330640:0crwdne330640:0 + :param colour: A tuple of the same length as the number of bytes per pixel (bpp). -Use in conjunction with ``show()`` to update the neopixels.""" + Use in conjunction with ``show()`` to update the neopixels. + """ ... - def __setitem__(self, key: int, value: Tuple[int, ...]) -> None: - """crwdns330644:0crwdne330644:0 (crwdns330642:0crwdne330642:0) + """Set a pixel colour. -Example: ``np[0] = (255, 0, 0)`` - -:param key: (crwdns330646:0crwdne330646:0) crwdns330648:0crwdne330648:0 -:param value: (crwdns330650:0crwdne330650:0) crwdns330652:0crwdne330652:0""" + Example: ``np[0] = (255, 0, 0)`` + :param key: The pixel number. + :param value: The colour. + """ def __getitem__(self, key: int) -> Tuple[int, ...]: - """crwdns330656:0crwdne330656:0 (crwdns330654:0crwdne330654:0) - -Example: ``r, g, b = np[0]`` + """Get a pixel colour. -:param key: (crwdns330658:0crwdne330658:0) crwdns330660:0crwdne330660:0 -:return: The colour tuple.""" + Example: ``r, g, b = np[0]`` + :param key: The pixel number. + :return: The colour tuple. + """ def __len__(self) -> int: - """crwdns330664:0crwdne330664:0 (crwdns330662:0crwdne330662:0) + """Get length of this pixel strip. -Example: ``len(np)``""" \ No newline at end of file + Example: ``len(np)`` + """ diff --git a/lang/lol/typeshed/stdlib/os.pyi b/lang/lol/typeshed/stdlib/os.pyi index 24170cf..2f2db77 100644 --- a/lang/lol/typeshed/stdlib/os.pyi +++ b/lang/lol/typeshed/stdlib/os.pyi @@ -1,63 +1,73 @@ -"""crwdns330668:0crwdne330668:0 (crwdns330666:0crwdne330666:0)""" +"""Access the file system. +""" + from typing import Tuple from typing import List def listdir() -> List[str]: - """crwdns330672:0crwdne330672:0 (crwdns330670:0crwdne330670:0) + """List files. -Example: ``os.listdir()`` + Example: ``os.listdir()`` -:return: A list of the names of all the files contained within the local -persistent on-device file system.""" + :return: A list of the names of all the files contained within the local + persistent on-device file system. + """ ... def remove(filename: str) -> None: - """crwdns330676:0crwdne330676:0 (crwdns330674:0crwdne330674:0) + """Remove (delete) a file. -Example: ``os.remove('data.txt')`` + Example: ``os.remove('data.txt')`` -:param filename: (crwdns330678:0crwdne330678:0) crwdns330680:0crwdne330680:0 + :param filename: The file to delete. -If the file does not exist an ``OSError`` exception will occur.""" + If the file does not exist an ``OSError`` exception will occur. + """ ... def size(filename: str) -> int: - """crwdns330684:0crwdne330684:0 (crwdns330682:0crwdne330682:0) + """Returns the size of a file. -Example: ``os.size('data.txt')`` + Example: ``os.size('data.txt')`` -:param filename: (crwdns330686:0crwdne330686:0) crwdns330688:0crwdne330688:0 -:return: The size in bytes. + :param filename: The file + :return: The size in bytes. -If the file does not exist an ``OSError`` exception will occur.""" + If the file does not exist an ``OSError`` exception will occur. + """ class uname_result(Tuple[str, str, str, str, str]): - """crwdns330692:0``os.uname()``crwdne330692:0 (crwdns330690:0crwdne330690:0)""" + """Result of ``os.uname()``""" sysname: str - """crwdns330696:0crwdne330696:0 (crwdns330694:0crwdne330694:0)""" + """Operating system name.""" + nodename: str - """crwdns330700:0crwdne330700:0 (crwdns330698:0crwdne330698:0)""" + """Name of machine on network (implementation-defined).""" + release: str - """crwdns330704:0crwdne330704:0 (crwdns330702:0crwdne330702:0)""" + """Operating system release.""" + version: str - """crwdns330708:0crwdne330708:0 (crwdns330706:0crwdne330706:0)""" + """Operating system version.""" + machine: str - """crwdns330712:0crwdne330712:0 (crwdns330710:0crwdne330710:0)""" + """Hardware identifier.""" def uname() -> uname_result: - """crwdns330716:0crwdne330716:0 (crwdns330714:0crwdne330714:0) + """Returns information identifying the current operating system. -Example: ``os.uname()`` + Example: ``os.uname()`` -The return value is an object with five attributes: + The return value is an object with five attributes: -- ``sysname`` - operating system name -- ``nodename`` - name of machine on network (implementation-defined) -- ``release`` - operating system release -- ``version`` - operating system version -- ``machine`` - hardware identifier + - ``sysname`` - operating system name + - ``nodename`` - name of machine on network (implementation-defined) + - ``release`` - operating system release + - ``version`` - operating system version + - ``machine`` - hardware identifier -There is no underlying operating system in MicroPython. As a result the -information returned by the ``uname`` function is mostly useful for -versioning details.""" - ... \ No newline at end of file + There is no underlying operating system in MicroPython. As a result the + information returned by the ``uname`` function is mostly useful for + versioning details. + """ + ... diff --git a/lang/lol/typeshed/stdlib/radio.pyi b/lang/lol/typeshed/stdlib/radio.pyi index 079f747..8dd0267 100644 --- a/lang/lol/typeshed/stdlib/radio.pyi +++ b/lang/lol/typeshed/stdlib/radio.pyi @@ -1,123 +1,152 @@ -"""crwdns330720:0crwdne330720:0 (crwdns330718:0crwdne330718:0)""" +"""Communicate between micro:bits with the built-in radio. +""" + from _typeshed import WriteableBuffer from typing import Optional, Tuple + RATE_1MBIT: int -"""crwdns330724:0crwdne330724:0 (crwdns330722:0crwdne330722:0)""" +"""Constant used to indicate a throughput of 1 MBit a second.""" + RATE_2MBIT: int -"""crwdns330728:0crwdne330728:0 (crwdns330726:0crwdne330726:0)""" +"""Constant used to indicate a throughput of 2 MBit a second.""" def on() -> None: - """crwdns330732:0crwdne330732:0 (crwdns330730:0crwdne330730:0) + """Turns the radio on. -Example: ``radio.on()`` + Example: ``radio.on()`` -This needs to be explicitly called since the radio draws power and takes -up memory that you may otherwise need.""" + This needs to be explicitly called since the radio draws power and takes + up memory that you may otherwise need. + """ ... def off() -> None: - """crwdns330736:0crwdne330736:0 (crwdns330734:0crwdne330734:0) + """Turns off the radio, saving power and memory. -Example: ``radio.off()``""" + Example: ``radio.off()`` + """ ... -def config(length: int=32, queue: int=3, channel: int=7, power: int=6, address: int=1969383796, group: int=0, data_rate: int=RATE_1MBIT) -> None: - """crwdns330740:0crwdne330740:0 (crwdns330738:0crwdne330738:0) - -Example: ``radio.config(group=42)`` - -The default configuration is suitable for most use. - -:param length: (crwdns330758:0crwdne330758:0) crwdns330760:0crwdne330760:0 -:param queue: (crwdns330766:0crwdne330766:0) crwdns330768:0crwdne330768:0 -:param channel: (crwdns330746:0crwdne330746:0) crwdns330748:0crwdne330748:0 -:param power: (crwdns330762:0crwdne330762:0) crwdns330764:0crwdne330764:0 -:param address: (crwdns330742:0crwdne330742:0) crwdns330744:0crwdne330744:0 -:param group: (crwdns330754:0crwdne330754:0) crwdns330756:0``address``crwdne330756:0 -:param data_rate: (crwdns330750:0crwdne330750:0) crwdns330752:0``radio.RATE_1MBIT``crwdnd330752:0``radio``crwdnd330752:0``RATE_250KBIT``crwdnd330752:0``RATE_1MBIT``crwdnd330752:0``RATE_2MBIT``crwdne330752:0 - -If ``config`` is not called then the defaults described above are assumed.""" +def config( + length: int = 32, + queue: int = 3, + channel: int = 7, + power: int = 6, + address: int = 0x75626974, + group: int = 0, + data_rate: int = RATE_1MBIT, +) -> None: + """Configures the radio. + + Example: ``radio.config(group=42)`` + + The default configuration is suitable for most use. + + :param length: (default=32) defines the maximum length, in bytes, of a message sent via the radio. + It can be up to 251 bytes long (254 - 3 bytes for S0, LENGTH and S1 preamble). + :param queue: (default=3) specifies the number of messages that can be stored on the incoming message queue. + If there are no spaces left on the queue for incoming messages, then the incoming message is dropped. + :param channel: (default=7) an integer value from 0 to 83 (inclusive) that defines an arbitrary "channel" to which the radio is tuned. + Messages will be sent via this channel and only messages received via this channel will be put onto the incoming message queue. Each step is 1MHz wide, based at 2400MHz. + :param power: (default=6) is an integer value from 0 to 7 (inclusive) to indicate the strength of signal used when broadcasting a message. + The higher the value the stronger the signal, but the more power is consumed by the device. The numbering translates to positions in the following list of dBm (decibel milliwatt) values: -30, -20, -16, -12, -8, -4, 0, 4. + :param address: (default=0x75626974) an arbitrary name, expressed as a 32-bit address, that's used to filter incoming packets at the hardware level, keeping only those that match the address you set. + The default used by other micro:bit related platforms is the default setting used here. + :param group: (default=0) an 8-bit value (0-255) used with the ``address`` when filtering messages. + Conceptually, "address" is like a house/office address and "group" is like the person at that address to which you want to send your message. + :param data_rate: (default=``radio.RATE_1MBIT``) indicates the speed at which data throughput takes place. + Can be one of the following constants defined in the ``radio`` module: ``RATE_250KBIT``, ``RATE_1MBIT`` or ``RATE_2MBIT``. + + If ``config`` is not called then the defaults described above are assumed. + """ ... def reset() -> None: - """crwdns330772:0crwdne330772:0 (crwdns330770:0crwdne330770:0) + """Reset the settings to their default values. -Example: ``radio.reset()`` + Example: ``radio.reset()`` -The defaults as as per the ``config`` function above.""" + The defaults as as per the ``config`` function above. + """ ... def send_bytes(message: bytes) -> None: - """crwdns330776:0crwdne330776:0 (crwdns330774:0crwdne330774:0) + """Sends a message containing bytes. -Example: ``radio.send_bytes(b'hello')`` + Example: ``radio.send_bytes(b'hello')`` -:param message: (crwdns330778:0crwdne330778:0) crwdns330780:0crwdne330780:0""" + :param message: The bytes to send. + """ ... def receive_bytes() -> Optional[bytes]: - """crwdns330784:0crwdne330784:0 (crwdns330782:0crwdne330782:0) + """Receive the next incoming message on the message queue. -Example: ``radio.receive_bytes()`` + Example: ``radio.receive_bytes()`` -:return: The message bytes if any, otherwise ``None``.""" + :return: The message bytes if any, otherwise ``None``. + """ ... def receive_bytes_into(buffer: WriteableBuffer) -> Optional[int]: - """crwdns330788:0crwdne330788:0 (crwdns330786:0crwdne330786:0) + """Copy the next incoming message on the message queue into a buffer. -Example: ``radio.receive_bytes_info(buffer)`` + Example: ``radio.receive_bytes_info(buffer)`` -:param buffer: (crwdns330790:0crwdne330790:0) crwdns330792:0crwdne330792:0 -:return: ``None`` if there are no pending messages, otherwise it returns the length of the message (which might be more than the length of the buffer).""" + :param buffer: The target buffer. The message is truncated if larger than the buffer. + :return: ``None`` if there are no pending messages, otherwise it returns the length of the message (which might be more than the length of the buffer). + """ ... def send(message: str) -> None: - """crwdns330796:0crwdne330796:0 (crwdns330794:0crwdne330794:0) + """Sends a message string. -Example: ``radio.send('hello')`` + Example: ``radio.send('hello')`` -This is the equivalent of ``radio.send_bytes(bytes(message, 'utf8'))`` but with ``b'\x01\x00\x01'`` -prepended to the front (to make it compatible with other platforms that target the micro:bit). + This is the equivalent of ``radio.send_bytes(bytes(message, 'utf8'))`` but with ``b'\x01\x00\x01'`` + prepended to the front (to make it compatible with other platforms that target the micro:bit). -:param message: (crwdns330798:0crwdne330798:0) crwdns330800:0crwdne330800:0""" + :param message: The string to send. + """ ... def receive() -> Optional[str]: - """crwdns330804:0``receive_bytes``crwdne330804:0 (crwdns330802:0crwdne330802:0) + """Works in exactly the same way as ``receive_bytes`` but returns whatever was sent. -Example: ``radio.receive()`` + Example: ``radio.receive()`` -Equivalent to ``str(receive_bytes(), 'utf8')`` but with a check that the the first -three bytes are ``b'\x01\x00\x01'`` (to make it compatible with other platforms that -may target the micro:bit). + Equivalent to ``str(receive_bytes(), 'utf8')`` but with a check that the the first + three bytes are ``b'\x01\x00\x01'`` (to make it compatible with other platforms that + may target the micro:bit). -:return: The message with the prepended bytes stripped and converted to a string. + :return: The message with the prepended bytes stripped and converted to a string. -A ``ValueError`` exception is raised if conversion to string fails.""" + A ``ValueError`` exception is raised if conversion to string fails. + """ ... def receive_full() -> Optional[Tuple[bytes, int, int]]: - """crwdns330808:0crwdne330808:0 (crwdns330806:0crwdne330806:0) + """Returns a tuple containing three values representing the next incoming message on the message queue. -Example: ``radio.receive_full()`` + Example: ``radio.receive_full()`` -If there are no pending messages then ``None`` is returned. + If there are no pending messages then ``None`` is returned. -The three values in the tuple represent: + The three values in the tuple represent: -- the next incoming message on the message queue as bytes. -- the RSSI (signal strength): a value between 0 (strongest) and -255 (weakest) as measured in dBm. -- a microsecond timestamp: the value returned by ``time.ticks_us()`` when the message was received. + - the next incoming message on the message queue as bytes. + - the RSSI (signal strength): a value between 0 (strongest) and -255 (weakest) as measured in dBm. + - a microsecond timestamp: the value returned by ``time.ticks_us()`` when the message was received. -For example:: + For example:: - details = radio.receive_full() - if details: - msg, rssi, timestamp = details + details = radio.receive_full() + if details: + msg, rssi, timestamp = details -This function is useful for providing information needed for triangulation -and/or trilateration with other micro:bit devices. + This function is useful for providing information needed for triangulation + and/or trilateration with other micro:bit devices. -:return: ``None`` if there is no message, otherwise a tuple of length three with the bytes, strength and timestamp values.""" - ... \ No newline at end of file + :return: ``None`` if there is no message, otherwise a tuple of length three with the bytes, strength and timestamp values. + """ + ... diff --git a/lang/lol/typeshed/stdlib/random.pyi b/lang/lol/typeshed/stdlib/random.pyi index 319aa4d..a2c2ef3 100644 --- a/lang/lol/typeshed/stdlib/random.pyi +++ b/lang/lol/typeshed/stdlib/random.pyi @@ -1,80 +1,93 @@ -"""crwdns330812:0crwdne330812:0 (crwdns330810:0crwdne330810:0)""" +"""Generate random numbers. +""" from typing import TypeVar, Sequence, Union, overload def getrandbits(n: int) -> int: - """crwdns330816:0``n``crwdne330816:0 (crwdns330814:0crwdne330814:0) + """Generate an integer with ``n`` random bits. -Example: ``random.getrandbits(1)`` + Example: ``random.getrandbits(1)`` -:param n: (crwdns330818:0crwdne330818:0) crwdns330820:0crwdne330820:0""" + :param n: A value between 1-30 (inclusive). + """ ... def seed(n: int) -> None: - """crwdns330824:0crwdne330824:0 (crwdns330822:0crwdne330822:0) + """Initialize the random number generator. -Example: ``random.seed(0)`` + Example: ``random.seed(0)`` -:param n: (crwdns330826:0crwdne330826:0) crwdns330828:0crwdne330828:0 + :param n: The integer seed -This will give you reproducibly deterministic randomness from a given starting -state (``n``).""" + This will give you reproducibly deterministic randomness from a given starting + state (``n``). + """ ... def randint(a: int, b: int) -> int: - """crwdns330832:0``a``crwdnd330832:0``b``crwdne330832:0 (crwdns330830:0crwdne330830:0) + """Choose a random integer between ``a`` and ``b`` inclusive. -Example: ``random.randint(0, 9)`` + Example: ``random.randint(0, 9)`` -:param a: (crwdns330834:0crwdne330834:0) crwdns330836:0crwdne330836:0 -:param b: (crwdns330838:0crwdne330838:0) crwdns330840:0crwdne330840:0 + :param a: Start value for the range (inclusive) + :param b: End value for the range (inclusive) -Alias for ``randrange(a, b + 1)``.""" + Alias for ``randrange(a, b + 1)``. + """ ... @overload def randrange(stop: int) -> int: - """crwdns330844:0``stop``crwdne330844:0 (crwdns330842:0crwdne330842:0) + """Choose a randomly selected integer between zero and up to (but not + including) ``stop``. -Example: ``random.randrange(10)`` + Example: ``random.randrange(10)`` -:param stop: (crwdns330846:0crwdne330846:0) crwdns330848:0crwdne330848:0""" + :param stop: End value for the range (exclusive) + """ ... @overload -def randrange(start: int, stop: int, step: int=1) -> int: - """crwdns330852:0``range(start, stop, step)``crwdne330852:0 (crwdns330850:0crwdne330850:0) +def randrange(start: int, stop: int, step: int = 1) -> int: + """ + Choose a randomly selected element from ``range(start, stop, step)``. -Example: ``random.randrange(0, 10)`` + Example: ``random.randrange(0, 10)`` -:param start: (crwdns330854:0crwdne330854:0) crwdns330856:0crwdne330856:0 -:param stop: (crwdns330862:0crwdne330862:0) crwdns330864:0crwdne330864:0 -:param step: (crwdns330858:0crwdne330858:0) crwdns330860:0crwdne330860:0""" + :param start: The start of the range (inclusive) + :param stop: The end of the range (exclusive) + :param step: The step. + """ ... -_T = TypeVar('_T') + +_T = TypeVar("_T") def choice(seq: Sequence[_T]) -> _T: - """crwdns330868:0``seq``crwdne330868:0 (crwdns330866:0crwdne330866:0) + """Choose a random element from the non-empty sequence ``seq``. -Example: ``random.choice([Image.HAPPY, Image.SAD])`` + Example: ``random.choice([Image.HAPPY, Image.SAD])`` -:param seq: (crwdns330870:0crwdne330870:0) crwdns330872:0crwdne330872:0 + :param seq: A sequence. -If ``seq`` is empty, raises ``IndexError``.""" + If ``seq`` is empty, raises ``IndexError``. + """ ... def random() -> float: - """crwdns330876:0crwdne330876:0 (crwdns330874:0crwdne330874:0) + """Generate a random floating point number in the range [0.0, 1.0). -Example: ``random.random()`` + Example: ``random.random()`` -:return: The random floating point number""" + :return: The random floating point number + """ ... def uniform(a: float, b: float) -> float: - """crwdns330880:0``a``crwdnd330880:0``b``crwdne330880:0 (crwdns330878:0crwdne330878:0) + """ + Return a random floating point number between ``a`` and ``b`` inclusive. -Example: ``random.uniform(0, 9)`` + Example: ``random.uniform(0, 9)`` -:param a: (crwdns330882:0crwdne330882:0) crwdns330884:0crwdne330884:0 -:param b: (crwdns330886:0crwdne330886:0) crwdns330888:0crwdne330888:0""" - ... \ No newline at end of file + :param a: Start value for the range (inclusive) + :param b: End value for the range (inclusive) + """ + ... diff --git a/lang/lol/typeshed/stdlib/speech.pyi b/lang/lol/typeshed/stdlib/speech.pyi index bbd286f..349d188 100644 --- a/lang/lol/typeshed/stdlib/speech.pyi +++ b/lang/lol/typeshed/stdlib/speech.pyi @@ -1,76 +1,106 @@ -"""crwdns330892:0crwdne330892:0 (crwdns330890:0crwdne330890:0)""" +"""Make the micro:bit talk, sing and make other speech like sounds. +""" + from typing import Optional from .microbit import MicroBitDigitalPin, pin0 def translate(words: str) -> str: - """crwdns330896:0crwdne330896:0 (crwdns330894:0crwdne330894:0) + """Translate English words to phonemes. -Example: ``speech.translate('hello world')`` + Example: ``speech.translate('hello world')`` -:param words: (crwdns330898:0crwdne330898:0) crwdns330900:0crwdne330900:0 -:return: A string containing a best guess at the appropriate phonemes to pronounce. -The output is generated from this `text to phoneme translation table `_. + :param words: A string of English words. + :return: A string containing a best guess at the appropriate phonemes to pronounce. + The output is generated from this `text to phoneme translation table `_. -This function should be used to generate a first approximation of phonemes -that can be further hand-edited to improve accuracy, inflection and -emphasis. + This function should be used to generate a first approximation of phonemes + that can be further hand-edited to improve accuracy, inflection and + emphasis. -See `the online documentation `_ for detailed information.""" + See `the online documentation `_ for detailed information. + """ ... -def pronounce(phonemes: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: Optional[MicroBitDigitalPin]=pin0) -> None: - """crwdns330904:0crwdne330904:0 (crwdns330902:0crwdne330902:0) - -Example: ``speech.pronounce(' /HEHLOW WERLD')`` - -:param phonemes: (crwdns330910:0crwdne330910:0) crwdns330912:0crwdne330912:0 -:param pitch: (crwdns330918:0crwdne330918:0) crwdns330920:0crwdne330920:0 -:param speed: (crwdns330922:0crwdne330922:0) crwdns330924:0crwdne330924:0 -:param mouth: (crwdns330906:0crwdne330906:0) crwdns330908:0crwdne330908:0 -:param throat: (crwdns330926:0crwdne330926:0) crwdns330928:0crwdne330928:0 -:param pin: (crwdns330914:0crwdne330914:0) crwdns330916:0``pin0``crwdne330916:0 - -Override the optional pitch, speed, mouth and throat settings to change the -timbre (quality) of the voice. - -See `the online documentation `_ for detailed information.""" +def pronounce( + phonemes: str, + pitch: int = 64, + speed: int = 72, + mouth: int = 128, + throat: int = 128, + pin: Optional[MicroBitDigitalPin] = pin0, +) -> None: + """Pronounce phonemes. + + Example: ``speech.pronounce(' /HEHLOW WERLD')`` + + :param phonemes: The string of phonemes to pronounce + :param pitch: A number representing the pitch of the voice + :param speed: A number representing the speed of the voice + :param mouth: A number representing the mouth of the voice + :param throat: A number representing the throat of the voice + :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. + If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. + + Override the optional pitch, speed, mouth and throat settings to change the + timbre (quality) of the voice. + + See `the online documentation `_ for detailed information. + """ ... -def say(words: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: MicroBitDigitalPin=pin0) -> None: - """crwdns330932:0crwdne330932:0 (crwdns330930:0crwdne330930:0) - -Example: ``speech.say('hello world')`` - -:param words: (crwdns330954:0crwdne330954:0) crwdns330956:0crwdne330956:0 -:param pitch: (crwdns330942:0crwdne330942:0) crwdns330944:0crwdne330944:0 -:param speed: (crwdns330946:0crwdne330946:0) crwdns330948:0crwdne330948:0 -:param mouth: (crwdns330934:0crwdne330934:0) crwdns330936:0crwdne330936:0 -:param throat: (crwdns330950:0crwdne330950:0) crwdns330952:0crwdne330952:0 -:param pin: (crwdns330938:0crwdne330938:0) crwdns330940:0``pin0``crwdne330940:0 - -The result is semi-accurate for English. Override the optional pitch, speed, -mouth and throat settings to change the timbre (quality) of the voice. - -This is a short-hand equivalent of: -``speech.pronounce(speech.translate(words))`` - -See `the online documentation `_ for detailed information.""" +def say( + words: str, + pitch: int = 64, + speed: int = 72, + mouth: int = 128, + throat: int = 128, + pin: MicroBitDigitalPin = pin0, +) -> None: + """Say English words. + + Example: ``speech.say('hello world')`` + + :param words: The string of words to say. + :param pitch: A number representing the pitch of the voice + :param speed: A number representing the speed of the voice + :param mouth: A number representing the mouth of the voice + :param throat: A number representing the throat of the voice + :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. + If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. + + The result is semi-accurate for English. Override the optional pitch, speed, + mouth and throat settings to change the timbre (quality) of the voice. + + This is a short-hand equivalent of: + ``speech.pronounce(speech.translate(words))`` + + See `the online documentation `_ for detailed information. + """ ... -def sing(phonemes: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: MicroBitDigitalPin=pin0) -> None: - """crwdns330960:0crwdne330960:0 (crwdns330958:0crwdne330958:0) - -Example: ``speech.sing(' /HEHLOW WERLD')`` - -:param phonemes: (crwdns330966:0crwdne330966:0) crwdns330968:0crwdne330968:0 -:param pitch: (crwdns330974:0crwdne330974:0) crwdns330976:0crwdne330976:0 -:param speed: (crwdns330978:0crwdne330978:0) crwdns330980:0crwdne330980:0 -:param mouth: (crwdns330962:0crwdne330962:0) crwdns330964:0crwdne330964:0 -:param throat: (crwdns330982:0crwdne330982:0) crwdns330984:0crwdne330984:0 -:param pin: (crwdns330970:0crwdne330970:0) crwdns330972:0``pin0``crwdne330972:0 - -Override the optional pitch, speed, mouth and throat settings to change -the timbre (quality) of the voice. - -See `the online documentation `_ for detailed information.""" - ... \ No newline at end of file +def sing( + phonemes: str, + pitch: int = 64, + speed: int = 72, + mouth: int = 128, + throat: int = 128, + pin: MicroBitDigitalPin = pin0, +) -> None: + """Sing phonemes. + + Example: ``speech.sing(' /HEHLOW WERLD')`` + + :param phonemes: The string of words to sing. + :param pitch: A number representing the pitch of the voice + :param speed: A number representing the speed of the voice + :param mouth: A number representing the mouth of the voice + :param throat: A number representing the throat of the voice + :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. + If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. + + Override the optional pitch, speed, mouth and throat settings to change + the timbre (quality) of the voice. + + See `the online documentation `_ for detailed information. + """ + ... diff --git a/lang/lol/typeshed/stdlib/struct.pyi b/lang/lol/typeshed/stdlib/struct.pyi index 8725186..53b3e0b 100644 --- a/lang/lol/typeshed/stdlib/struct.pyi +++ b/lang/lol/typeshed/stdlib/struct.pyi @@ -1,56 +1,65 @@ -"""crwdns330988:0crwdne330988:0 (crwdns330986:0crwdne330986:0)""" +"""Pack and unpack primitive data types. +""" + from _typeshed import ReadableBuffer, WriteableBuffer from typing import Any, Tuple, Union def calcsize(fmt: str) -> int: - """crwdns330992:0``fmt``crwdne330992:0 (crwdns330990:0crwdne330990:0) + """Get the number of bytes needed to store the given ``fmt``. -Example: ``struct.calcsize('hf')`` + Example: ``struct.calcsize('hf')`` -:param fmt: (crwdns330994:0crwdne330994:0) crwdns330996:0crwdne330996:0 -:return The number of bytes needed to store such a value.""" + :param fmt: A format string. + :return The number of bytes needed to store such a value. + """ ... def pack(fmt: str, v1: Any, *vn: Any) -> bytes: - """crwdns331000:0crwdne331000:0 (crwdns330998:0crwdne330998:0) + """Pack values according to a format string. -Example: ``struct.pack('hf', 1, 3.1415)`` + Example: ``struct.pack('hf', 1, 3.1415)`` -:param fmt: (crwdns331006:0crwdne331006:0) crwdns331008:0crwdne331008:0 -:param v1: (crwdns331010:0crwdne331010:0) crwdns331012:0crwdne331012:0 -:param *vn: (crwdns331002:0crwdne331002:0) crwdns331004:0crwdne331004:0 -:return A bytes object encoding the values.""" + :param fmt: The format string. + :param v1: The first value. + :param *vn: The remaining values. + :return A bytes object encoding the values. + """ ... -def pack_into(fmt: str, buffer: WriteableBuffer, offset: int, v1: Any, *vn: Any) -> None: - """crwdns331016:0crwdne331016:0 (crwdns331014:0crwdne331014:0) +def pack_into( + fmt: str, buffer: WriteableBuffer, offset: int, v1: Any, *vn: Any +) -> None: + """Pack values according to a format string. -Example: ``struct.pack_info('hf', buffer, 1, 3.1415)`` + Example: ``struct.pack_info('hf', buffer, 1, 3.1415)`` -:param fmt: (crwdns331026:0crwdne331026:0) crwdns331028:0crwdne331028:0 -:param buffer: (crwdns331022:0crwdne331022:0) crwdns331024:0crwdne331024:0 -:param offset: (crwdns331030:0crwdne331030:0) crwdns331032:0crwdne331032:0 -:param v1: (crwdns331034:0crwdne331034:0) crwdns331036:0crwdne331036:0 -:param *vn: (crwdns331018:0crwdne331018:0) crwdns331020:0crwdne331020:0""" + :param fmt: The format string. + :param buffer: The target buffer to write into. + :param offset: The offset into the buffer. May be negative to count from the end of the buffer. + :param v1: The first value. + :param *vn: The remaining values. + """ ... def unpack(fmt: str, data: ReadableBuffer) -> Tuple[Any, ...]: - """crwdns331040:0crwdne331040:0 (crwdns331038:0crwdne331038:0) + """Unpack data according to a format string. -Example: ``v1, v2 = struct.unpack('hf', buffer)`` + Example: ``v1, v2 = struct.unpack('hf', buffer)`` -:param fmt: (crwdns331046:0crwdne331046:0) crwdns331048:0crwdne331048:0 -:param data: (crwdns331042:0crwdne331042:0) crwdns331044:0crwdne331044:0 -:return: A tuple of the unpacked values.""" + :param fmt: The format string. + :param data: The data. + :return: A tuple of the unpacked values. + """ ... -def unpack_from(fmt: str, buffer: ReadableBuffer, offset: int=0) -> Tuple: - """crwdns331052:0crwdne331052:0 (crwdns331050:0crwdne331050:0) +def unpack_from(fmt: str, buffer: ReadableBuffer, offset: int = 0) -> Tuple: + """Unpack data from a buffer according to a format string. -Example: ``v1, v2 = struct.unpack_from('hf', buffer)`` + Example: ``v1, v2 = struct.unpack_from('hf', buffer)`` -:param fmt: (crwdns331058:0crwdne331058:0) crwdns331060:0crwdne331060:0 -:param buffer: (crwdns331054:0crwdne331054:0) crwdns331056:0crwdne331056:0 -:param offset: (crwdns331062:0crwdne331062:0) crwdns331064:0crwdne331064:0 -:return: A tuple of the unpacked values.""" - ... \ No newline at end of file + :param fmt: The format string. + :param buffer: The source buffer to read from. + :param offset: The offset into the buffer. May be negative to count from the end of the buffer. + :return: A tuple of the unpacked values. + """ + ... diff --git a/lang/lol/typeshed/stdlib/sys.pyi b/lang/lol/typeshed/stdlib/sys.pyi index 9459fb9..320bac9 100644 --- a/lang/lol/typeshed/stdlib/sys.pyi +++ b/lang/lol/typeshed/stdlib/sys.pyi @@ -1,36 +1,43 @@ -"""crwdns331068:0crwdne331068:0 (crwdns331066:0crwdne331066:0)""" +"""System specific functions""" + from typing import Any, Dict, List, NoReturn, TextIO, Tuple -def exit(retval: object=...) -> NoReturn: - """crwdns331072:0crwdne331072:0 (crwdns331070:0crwdne331070:0) +def exit(retval: object = ...) -> NoReturn: + """Terminate current program with a given exit code. -Example: ``sys.exit(1)`` + Example: ``sys.exit(1)`` -This function raises a ``SystemExit`` exception. If an argument is given, its -value given as an argument to ``SystemExit``. + This function raises a ``SystemExit`` exception. If an argument is given, its + value given as an argument to ``SystemExit``. -:param retval: (crwdns331074:0crwdne331074:0) crwdns331076:0crwdne331076:0""" + :param retval: The exit code or message. + """ ... def print_exception(exc: Exception) -> None: - """crwdns331080:0crwdne331080:0 (crwdns331078:0crwdne331078:0) + """ + Print an exception with a traceback. + + Example: ``sys.print_exception(e)`` -Example: ``sys.print_exception(e)`` + :param exc: The exception to print -:param exc: (crwdns331082:0crwdne331082:0) crwdns331084:0crwdne331084:0 + This is simplified version of a function which appears in the + ``traceback`` module in CPython. + """ -This is simplified version of a function which appears in the -``traceback`` module in CPython.""" argv: List[str] -"""crwdns331088:0crwdne331088:0 (crwdns331086:0crwdne331086:0)""" +"""A mutable list of arguments the current program was started with.""" + byteorder: str -"""crwdns331092:0``"little"``crwdnd331092:0``"big"``crwdne331092:0 (crwdns331090:0crwdne331090:0)""" +"""The byte order of the system (``"little"`` or ``"big"``).""" class _implementation: name: str version: Tuple[int, int, int] + implementation: _implementation -"""crwdns331096:0crwdne331096:0 (crwdns331094:0crwdne331094:0) +"""Object with information about the current Python implementation. For MicroPython, it has following attributes: @@ -44,9 +51,13 @@ minimal ports). CPython mandates more attributes for this object, but the actual useful bare minimum is implemented in MicroPython. """ + maxsize: int """ -crwdns331100:0crwdne331100:0 (crwdns331098:0crwdne331098:0) +Maximum value which a native integer type can hold on the current platform, +or maximum value representable by MicroPython integer type, if it's smaller +than platform max value (that is the case for MicroPython ports without +long int support). This attribute is useful for detecting "bitness" of a platform (32-bit vs 64-bit, etc.). It's recommended to not compare this attribute to some @@ -66,14 +77,17 @@ value directly, but instead count number of bits in it:: # (e.g. 31) due to peculiarities described above, so use "> 16", # "> 32", "> 64" style of comparisons. """ + modules: Dict[str, Any] -"""crwdns331104:0crwdne331104:0 (crwdns331102:0crwdne331102:0) +"""Dictionary of loaded modules. On some ports, it may not include builtin modules.""" + path: List[str] -"""crwdns331108:0crwdne331108:0 (crwdns331106:0crwdne331106:0)""" +"""A mutable list of directories to search for imported modules.""" + platform: str -"""crwdns331112:0crwdne331112:0 (crwdns331110:0crwdne331110:0) +"""The platform that MicroPython is running on. For OS/RTOS ports, this is usually an identifier of the OS, e.g. ``"linux"``. For baremetal ports it is an identifier of a board, e.g. ``"pyboard"`` for @@ -83,11 +97,13 @@ distinguish one board from another. If you need to check whether your program runs on MicroPython (vs other Python implementation), use ``sys.implementation`` instead. """ + version: str -"""crwdns331116:0crwdne331116:0 (crwdns331114:0crwdne331114:0)""" +"""Python language version that this implementation conforms to, as a string.""" + version_info: Tuple[int, int, int] -"""crwdns331120:0crwdne331120:0 (crwdns331118:0crwdne331118:0) +"""Python language version that this implementation conforms to, as a tuple of ints. Only the first three version numbers (major, minor, micro) are supported and they can be referenced only by index, not by name. -""" \ No newline at end of file +""" diff --git a/lang/lol/typeshed/stdlib/time.pyi b/lang/lol/typeshed/stdlib/time.pyi index f2c472d..598c483 100644 --- a/lang/lol/typeshed/stdlib/time.pyi +++ b/lang/lol/typeshed/stdlib/time.pyi @@ -1,110 +1,132 @@ -"""crwdns331124:0crwdne331124:0 (crwdns331122:0crwdne331122:0)""" +"""Measure time and add delays to programs. +""" + from typing import Union def sleep(seconds: Union[int, float]) -> None: - """crwdns331128:0crwdne331128:0 (crwdns331126:0crwdne331126:0) + """ + Delay a number of seconds. -Example: ``time.sleep(1)`` + Example: ``time.sleep(1)`` -:param seconds: (crwdns331130:0crwdne331130:0) crwdns331132:0crwdne331132:0""" + :param seconds: The number of seconds to sleep for. + Use a floating-point number to sleep for a fractional number of seconds. + """ ... def sleep_ms(ms: int) -> None: - """crwdns331136:0crwdne331136:0 (crwdns331134:0crwdne331134:0) + """ + Delay for given number of milliseconds. -Example: ``time.sleep_ms(1_000_000)`` + Example: ``time.sleep_ms(1_000_000)`` -:param ms: (crwdns331138:0crwdne331138:0) crwdns331140:0crwdne331140:0""" + :param ms: The number of milliseconds delay (>= 0). + """ ... def sleep_us(us: int) -> None: - """crwdns331144:0crwdne331144:0 (crwdns331142:0crwdne331142:0) + """ + Delay for given number of microseconds. -Example: ``time.sleep_us(1000)`` + Example: ``time.sleep_us(1000)`` -:param us: (crwdns331146:0crwdne331146:0) crwdns331148:0crwdne331148:0""" + :param us: The number of microseconds delay (>= 0). + """ ... def ticks_ms() -> int: - """crwdns331152:0crwdne331152:0 (crwdns331150:0crwdne331150:0) + """ + Get an increasing, millisecond counter with an arbitrary reference point, + that wraps around after some value. -Example: ``time.ticks_ms()`` + Example: ``time.ticks_ms()`` -:return: The counter value in milliseconds.""" + :return: The counter value in milliseconds. + """ ... def ticks_us() -> int: - """crwdns331156:0crwdne331156:0 (crwdns331154:0crwdne331154:0) + """ + Get an increasing, microsecond counter with an arbitrary reference point, + that wraps around after some value. -Example: ``time.ticks_us()`` + Example: ``time.ticks_us()`` -:return: The counter value in microseconds.""" + :return: The counter value in microseconds. + """ ... def ticks_add(ticks: int, delta: int) -> int: - """crwdns331160:0crwdne331160:0 (crwdns331158:0crwdne331158:0) + """ + Offset ticks value by a given number, which can be either positive or + negative. -Example: ``time.ticks_add(time.ticks_ms(), 200)`` + Example: ``time.ticks_add(time.ticks_ms(), 200)`` -Given a ticks value, this function allows to calculate ticks -value delta ticks before or after it, following modular-arithmetic -definition of tick values. + Given a ticks value, this function allows to calculate ticks + value delta ticks before or after it, following modular-arithmetic + definition of tick values. -:param ticks: (crwdns331166:0crwdne331166:0) crwdns331168:0crwdne331168:0 -:param delta: (crwdns331162:0crwdne331162:0) crwdns331164:0crwdne331164:0 + :param ticks: A ticks value + :param delta: An integer offset -Example:: + Example:: - # Find out what ticks value there was 100ms ago - print(ticks_add(time.ticks_ms(), -100)) + # Find out what ticks value there was 100ms ago + print(ticks_add(time.ticks_ms(), -100)) - # Calculate deadline for operation and test for it - deadline = ticks_add(time.ticks_ms(), 200) - while ticks_diff(deadline, time.ticks_ms()) > 0: - do_a_little_of_something() + # Calculate deadline for operation and test for it + deadline = ticks_add(time.ticks_ms(), 200) + while ticks_diff(deadline, time.ticks_ms()) > 0: + do_a_little_of_something() - # Find out TICKS_MAX used by this port - print(ticks_add(0, -1))""" + # Find out TICKS_MAX used by this port + print(ticks_add(0, -1)) + """ ... def ticks_diff(ticks1: int, ticks2: int) -> int: - """crwdns331172:0``time.ticks_ms()``crwdnd331172:0``ticks_us()``crwdne331172:0 (crwdns331170:0crwdne331170:0) - -Example: ``time.ticks_diff(scheduled_time, now)`` - -:param ticks1: (crwdns331174:0crwdne331174:0) crwdns331176:0crwdne331176:0 -:param ticks2: (crwdns331178:0crwdne331178:0) crwdns331180:0crwdne331180:0 - -The argument order is the same as for subtraction operator, -``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. - -``ticks_diff()`` is designed to accommodate various usage -patterns, among them: - -Polling with timeout. In this case, the order of events is known, and you -will deal only with positive results of :func:`time.ticks_diff()`:: - - # Wait for GPIO pin to be asserted, but at most 500us - start = time.ticks_us() - while pin.value() == 0: - if time.ticks_diff(time.ticks_us(), start) > 500: - raise TimeoutError - - -Scheduling events. In this case, :func:`time.ticks_diff()` result may be -negative if an event is overdue:: - - # This code snippet is not optimized - now = time.ticks_ms() - scheduled_time = task.scheduled_time() - if ticks_diff(scheduled_time, now) > 0: - print("Too early, let's nap") - sleep_ms(ticks_diff(scheduled_time, now)) - task.run() - elif ticks_diff(scheduled_time, now) == 0: - print("Right at time!") - task.run() - elif ticks_diff(scheduled_time, now) < 0: - print("Oops, running late, tell task to run faster!") - task.run(run_faster=True)""" - ... \ No newline at end of file + """ + Measure ticks difference between values returned from + ``time.ticks_ms()`` or ``ticks_us()``, as a signed value + which may wrap around. + + Example: ``time.ticks_diff(scheduled_time, now)`` + + :param ticks1: The value to subtract from + :param ticks2: The value to subtract + + The argument order is the same as for subtraction operator, + ``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. + + ``ticks_diff()`` is designed to accommodate various usage + patterns, among them: + + Polling with timeout. In this case, the order of events is known, and you + will deal only with positive results of :func:`time.ticks_diff()`:: + + # Wait for GPIO pin to be asserted, but at most 500us + start = time.ticks_us() + while pin.value() == 0: + if time.ticks_diff(time.ticks_us(), start) > 500: + raise TimeoutError + + + Scheduling events. In this case, :func:`time.ticks_diff()` result may be + negative if an event is overdue:: + + # This code snippet is not optimized + now = time.ticks_ms() + scheduled_time = task.scheduled_time() + if ticks_diff(scheduled_time, now) > 0: + print("Too early, let's nap") + sleep_ms(ticks_diff(scheduled_time, now)) + task.run() + elif ticks_diff(scheduled_time, now) == 0: + print("Right at time!") + task.run() + elif ticks_diff(scheduled_time, now) < 0: + print("Oops, running late, tell task to run faster!") + task.run(run_faster=True) + """ + ... diff --git a/lang/nl/typeshed/stdlib/gc.pyi b/lang/nl/typeshed/stdlib/gc.pyi index b306502..1370abf 100644 --- a/lang/nl/typeshed/stdlib/gc.pyi +++ b/lang/nl/typeshed/stdlib/gc.pyi @@ -1,68 +1,73 @@ -"""Beheer de garbagecollector""" +"""Control the garbage collector""" + from typing import overload def enable() -> None: - """Automatische afvalcollectie inschakelen. (inschakelen)""" + """Enable automatic garbage collection.""" ... def disable() -> None: - """Automatische afvalinzameling uitschakelen. (uitschakelen) + """Disable automatic garbage collection. -Heap memory can still be allocated, -and garbage collection can still be initiated manually using ``gc.collect``.""" + Heap memory can still be allocated, + and garbage collection can still be initiated manually using ``gc.collect``.""" def collect() -> None: - """Voer een garbagecollectie uit. (verzamel)""" + """Run a garbage collection.""" ... def mem_alloc() -> int: - """Krijg het aantal bytes van heap RAM die toegewezen zijn. + """Get the number of bytes of heap RAM that are allocated. -:return: The number of bytes allocated. + :return: The number of bytes allocated. -This function is MicroPython extension.""" + This function is MicroPython extension. + """ ... def mem_free() -> int: - """Krijg het aantal bytes van beschikbare heap RAM, of -1 als dit bedrag niet bekend is. + """Get the number of bytes of available heap RAM, or -1 if this amount is not known. -:return: The number of bytes free. + :return: The number of bytes free. -This function is MicroPython extension.""" + This function is MicroPython extension. + """ ... @overload def threshold() -> int: - """Vraag de extra GC toewijzingsdrempel op. (drempelwaarde) + """Query the additional GC allocation threshold. -:return: The GC allocation threshold. + :return: The GC allocation threshold. -This function is a MicroPython extension. CPython has a similar -function - ``set_threshold()``, but due to different GC -implementations, its signature and semantics are different.""" + This function is a MicroPython extension. CPython has a similar + function - ``set_threshold()``, but due to different GC + implementations, its signature and semantics are different. + """ ... @overload def threshold(amount: int) -> None: - """Stel de extra GC toewijzingsdrempel in. (drempelwaarde) - -Normally, a collection is triggered only when a new allocation -cannot be satisfied, i.e. on an out-of-memory (OOM) condition. -If this function is called, in addition to OOM, a collection -will be triggered each time after ``amount`` bytes have been -allocated (in total, since the previous time such an amount of bytes -have been allocated). ``amount`` is usually specified as less than the -full heap size, with the intention to trigger a collection earlier than when the -heap becomes exhausted, and in the hope that an early collection will prevent -excessive memory fragmentation. This is a heuristic measure, the effect -of which will vary from application to application, as well as -the optimal value of the ``amount`` parameter. - -A value of -1 means a disabled allocation threshold. - -This function is a MicroPython extension. CPython has a similar -function - ``set_threshold()``, but due to different GC -implementations, its signature and semantics are different. - -:param amount: (bedrag) Het aantal bytes waarna een garbage collectie moet worden geactiveerd.""" - ... \ No newline at end of file + """Set the additional GC allocation threshold. + + Normally, a collection is triggered only when a new allocation + cannot be satisfied, i.e. on an out-of-memory (OOM) condition. + If this function is called, in addition to OOM, a collection + will be triggered each time after ``amount`` bytes have been + allocated (in total, since the previous time such an amount of bytes + have been allocated). ``amount`` is usually specified as less than the + full heap size, with the intention to trigger a collection earlier than when the + heap becomes exhausted, and in the hope that an early collection will prevent + excessive memory fragmentation. This is a heuristic measure, the effect + of which will vary from application to application, as well as + the optimal value of the ``amount`` parameter. + + A value of -1 means a disabled allocation threshold. + + This function is a MicroPython extension. CPython has a similar + function - ``set_threshold()``, but due to different GC + implementations, its signature and semantics are different. + + :param amount: The number of bytes after which a garbage collection should be triggered. + """ + ... diff --git a/lang/nl/typeshed/stdlib/log.pyi b/lang/nl/typeshed/stdlib/log.pyi index b204500..c9870fa 100644 --- a/lang/nl/typeshed/stdlib/log.pyi +++ b/lang/nl/typeshed/stdlib/log.pyi @@ -1,89 +1,104 @@ -"""Log gegevens in op je micro:bit V2.""" +"""Log data to your micro:bit V2.""" + from typing import Literal, Mapping, Optional, Union, overload + MILLISECONDS = 1 -"""Milliseconden tijdstempel formaat. (milliseconden)""" +"""Milliseconds timestamp format.""" + SECONDS = 10 -"""Seconden tijdstempel formaat. (seconden)""" +"""Seconds timestamp format.""" + MINUTES = 600 -"""Minuten tijdstempel formaat. (minuten)""" +"""Minutes timestamp format.""" + HOURS = 36000 -"""Uren tijdstempel formaat. (uren)""" +"""Hours timestamp format.""" + DAYS = 864000 -"""Dagen tijdstempel formaat. (dagen)""" +"""Days timestamp format.""" -def set_labels(*labels: str, timestamp: Optional[Literal[1, 10, 36000, 864000]]=SECONDS) -> None: - """Stel de logbestandheader in. (kies labels) +def set_labels( + *labels: str, timestamp: Optional[Literal[1, 10, 36000, 864000]] = SECONDS +) -> None: + """Set up the log file header. -Example: ``log.set_labels('X', 'Y', 'Z', timestamp=log.MINUTES)`` + Example: ``log.set_labels('X', 'Y', 'Z', timestamp=log.MINUTES)`` -Ideally this function should be called a single time, before any data is -logged, to configure the data table header once. + Ideally this function should be called a single time, before any data is + logged, to configure the data table header once. -If a log file already exists when the program starts, or if this function -is called multiple times, it will check the labels already defined in the -log file. If this function call contains any new labels not already -present, it will generate a new header row with the additional columns. + If a log file already exists when the program starts, or if this function + is called multiple times, it will check the labels already defined in the + log file. If this function call contains any new labels not already + present, it will generate a new header row with the additional columns. -By default the first column contains a timestamp for each row. The time -unit can be selected via the timestamp argument. + By default the first column contains a timestamp for each row. The time + unit can be selected via the timestamp argument. -:param *labels: Een willekeurig aantal positionele argumenten, elk corresponderend aan een vermelding in de log header. -:param timestamp: (tijdstempel) Selecteer de eenheid van de tijdsaanduiding die automatisch als eerste kolom in elke rij wordt toegevoegd. Tijdstempel waarden kunnen een van ``log.MILLISECONDS``, ``log.SECONDS``, ``log.MINUTES``, , , ``log.HOURS``, ``log.DAYS`` of ``None`` om de tijdstempel uit te schakelen. De standaardwaarde is ``log.SECONDS``.""" + :param *labels: Any number of positional arguments, each corresponding to an entry in the log header. + :param timestamp: Select the timestamp unit that will be automatically added as the first column in every row. Timestamp values can be one of ``log.MILLISECONDS``, ``log.SECONDS``, ``log.MINUTES``, ``log.HOURS``, ``log.DAYS`` or ``None`` to disable the timestamp. The default value is ``log.SECONDS``. + """ ... @overload -def add(data_dictionary: Optional[Mapping[str, Union[str, int, float]]]) -> None: - """Voeg een gegevensrij toe aan de log door een woordenboek van koppen en waarden te passeren. (toevoegen) +def add( + data_dictionary: Optional[Mapping[str, Union[str, int, float]]], +) -> None: + """Add a data row to the log by passing a dictionary of headers and values. -Example: ``log.add({ 'temp': temperature() })`` + Example: ``log.add({ 'temp': temperature() })`` -Each call to this function adds a row to the log. + Each call to this function adds a row to the log. -New labels not previously specified via the set_labels function, or by a -previous call to this function, will trigger a new header entry to be added -to the log with the extra labels. + New labels not previously specified via the set_labels function, or by a + previous call to this function, will trigger a new header entry to be added + to the log with the extra labels. -Labels previously specified and not present in a call to this function will -be skipped with an empty value in the log row. + Labels previously specified and not present in a call to this function will + be skipped with an empty value in the log row. -:param data_dictionary: (gegevenswoordenboek) De gegevens die moeten worden geregistreerd als woordenboek met een sleutel voor elke header.""" + :param data_dictionary: The data to log as a dictionary with a key for each header. + """ ... @overload def add(**kwargs: Union[str, int, float]) -> None: - """Voeg een gegevensrij toe aan het logboek met behulp van trefwoordargumenten. (toevoegen) + """Add a data row to the log using keyword arguments. -Example: ``log.add(temp=temperature())`` + Example: ``log.add(temp=temperature())`` -Each call to this function adds a row to the log. + Each call to this function adds a row to the log. -New labels not previously specified via the set_labels function, or by a -previous call to this function, will trigger a new header entry to be added -to the log with the extra labels. + New labels not previously specified via the set_labels function, or by a + previous call to this function, will trigger a new header entry to be added + to the log with the extra labels. -Labels previously specified and not present in a call to this function will -be skipped with an empty value in the log row.""" + Labels previously specified and not present in a call to this function will + be skipped with an empty value in the log row. + """ ... def delete(full=False): - """Verwijdert de inhoud van het log, inclusief headers. (verwijderen) + """Deletes the contents of the log, including headers. -Example: ``log.delete()`` + Example: ``log.delete()`` -To add the log headers again the ``set_labels`` function should to be called after this function. + To add the log headers again the ``set_labels`` function should to be called after this function. -There are two erase modes; “full” completely removes the data from the physical storage, -and “fast” invalidates the data without removing it. + There are two erase modes; “full” completely removes the data from the physical storage, + and “fast” invalidates the data without removing it. -:param full: (volledig) ``True`` selecteert een "volledige" wissen en ``False`` selecteert de "snel" wis methode.""" + :param full: ``True`` selects a “full” erase and ``False`` selects the “fast” erase method. + """ ... def set_mirroring(serial: bool): - """Configureer het spiegelen van de data logging activiteit naar de seriële uitgang. (stel spiegelen in) + """Configure mirroring of the data logging activity to the serial output. -Example: ``log.set_mirroring(True)`` + Example: ``log.set_mirroring(True)`` -Serial mirroring is disabled by default. When enabled, it will print to serial each row logged into the log file. + Serial mirroring is disabled by default. When enabled, it will print to serial each row logged into the log file. -:param serial: (serieel) ``True`` maakt het spiegelen van gegevens naar de seriële uitvoer mogelijk.""" - ... \ No newline at end of file + :param serial: ``True`` enables mirroring data to the serial output. + """ + ... diff --git a/lang/nl/typeshed/stdlib/machine.pyi b/lang/nl/typeshed/stdlib/machine.pyi index d5d2568..2e82f5b 100644 --- a/lang/nl/typeshed/stdlib/machine.pyi +++ b/lang/nl/typeshed/stdlib/machine.pyi @@ -1,84 +1,97 @@ -"""Hulpprogramma's op laag niveau.""" +"""Low-level utilities. +""" from typing import Any from .microbit import MicroBitDigitalPin def unique_id() -> bytes: - """Krijg een byte string met een uniek id van een bord. (uniek id) + """Get a byte string with a unique identifier of a board. -Example: ``machine.unique_id()`` + Example: ``machine.unique_id()`` -:return: An identifier that varies from one board instance to another.""" + :return: An identifier that varies from one board instance to another. + """ ... def reset() -> None: - """Reset het apparaat op een manier die lijkt op de externe RESET knop. + """Reset the device in a manner similar to pushing the external RESET button. -Example: ``machine.reset()``""" + Example: ``machine.reset()`` + """ ... def freq() -> int: - """Krijg de CPU frequentie in Hertz. (frequentie) + """Get the CPU frequency in hertz. -Example: ``machine.freq()`` + Example: ``machine.freq()`` -:return: The CPU frequency.""" + :return: The CPU frequency. + """ ... def disable_irq() -> Any: - """Interruptie verzoeken uitschakelen. (irq uitschakelen) + """Disable interrupt requests. -Example: ``interrupt_state = machine.disable_irq()`` + Example: ``interrupt_state = machine.disable_irq()`` -:return: the previous IRQ state which should be considered an opaque value + :return: the previous IRQ state which should be considered an opaque value -The return value should be passed to the ``enable_irq`` function to restore -interrupts to their original state.""" + The return value should be passed to the ``enable_irq`` function to restore + interrupts to their original state. + """ ... def enable_irq(state: Any) -> None: - """Zet interruptie verzoeken opnieuw aan. (irq inschakelen) + """Re-enable interrupt requests. -Example: ``machine.enable_irq(interrupt_state)`` + Example: ``machine.enable_irq(interrupt_state)`` -:param state: (staat) De waarde die is teruggestuurd van de meest recente oproep naar de ``disable_irq`` functie.""" + :param state: The value that was returned from the most recent call to the ``disable_irq`` function. + """ ... -def time_pulse_us(pin: MicroBitDigitalPin, pulse_level: int, timeout_us: int=1000000) -> int: - """Time een puls op een pin. (tijd pulse us) +def time_pulse_us( + pin: MicroBitDigitalPin, pulse_level: int, timeout_us: int = 1000000 +) -> int: + """Time a pulse on a pin. -Example: ``time_pulse_us(pin0, 1)`` + Example: ``time_pulse_us(pin0, 1)`` -If the current input value of the pin is different to ``pulse_level``, the -function first waits until the pin input becomes equal to -``pulse_level``, then times the duration that the pin is equal to -``pulse_level``. If the pin is already equal to ``pulse_level`` then timing -starts straight away. + If the current input value of the pin is different to ``pulse_level``, the + function first waits until the pin input becomes equal to + ``pulse_level``, then times the duration that the pin is equal to + ``pulse_level``. If the pin is already equal to ``pulse_level`` then timing + starts straight away. -:param pin: De pin om te gebruiken -:param pulse_level: (puls niveau) 0 om een lage puls te tikken of 1 om een hoge puls te tikken -:param timeout_us: Een microseconde time-out -:return: The duration of the pulse in microseconds, or -1 for a timeout waiting for the level to match ``pulse_level``, or -2 on timeout waiting for the pulse to end""" + :param pin: The pin to use + :param pulse_level: 0 to time a low pulse or 1 to time a high pulse + :param timeout_us: A microsecond timeout + :return: The duration of the pulse in microseconds, or -1 for a timeout waiting for the level to match ``pulse_level``, or -2 on timeout waiting for the pulse to end + """ ... class mem: - """De klasse van de ``mem8``, ``mem16`` en ``mem32`` geheugenweergaven.""" + """The class for the ``mem8``, ``mem16`` and ``mem32`` memory views.""" def __getitem__(self, address: int) -> int: - """Toegang tot een waarde uit het geheugen. + """Access a value from memory. -:param address: (adres) Het geheugenadres. -:return: The value at that address as an integer.""" + :param address: The memory address. + :return: The value at that address as an integer. + """ ... - def __setitem__(self, address: int, value: int) -> None: - """Stel een waarde in op het opgegeven adres. + """Set a value at the given address. -:param address: (adres) Het geheugen adres. -:param value: (waarde) De integerwaarde die moet worden ingesteld.""" + :param address: The memory address. + :param value: The integer value to set. + """ ... + mem8: mem -"""8-bit (byte) weergave van het geheugen.""" +"""8-bit (byte) view of memory.""" + mem16: mem -"""16-bit (byte) weergave van het geheugen.""" +"""16-bit view of memory.""" + mem32: mem -"""32-bit (byte) weergave van het geheugen.""" \ No newline at end of file +"""32-bit view of memory.""" diff --git a/lang/nl/typeshed/stdlib/math.pyi b/lang/nl/typeshed/stdlib/math.pyi index 38397fc..f82d4de 100644 --- a/lang/nl/typeshed/stdlib/math.pyi +++ b/lang/nl/typeshed/stdlib/math.pyi @@ -1,246 +1,273 @@ -"""Wiskundige functies. (wiskunde)""" +"""Mathematical functions. +""" + from typing import Tuple def acos(x: float) -> float: - """Bereken de inverse cosinus. + """Calculate the inverse cosine. -Example: ``math.acos(1)`` + Example: ``math.acos(1)`` -:param x: (х) Een getal -:return: The inverse cosine of ``x``""" + :param x: A number + :return: The inverse cosine of ``x`` + """ ... def asin(x: float) -> float: - """Bereken de inverse sinus. + """Calculate the inverse sine. -Example: ``math.asin(0)`` + Example: ``math.asin(0)`` -:param x: (х) Een getal -:return: The inverse sine of ``x``""" + :param x: A number + :return: The inverse sine of ``x`` + """ ... def atan(x: float) -> float: - """Bereken de inverse tangens. + """Calculate the inverse tangent. -Example: ``math.atan(0)`` + Example: ``math.atan(0)`` -:param x: (х) Een getal -:return: The inverse tangent of ``x``""" + :param x: A number + :return: The inverse tangent of ``x`` + """ ... def atan2(y: float, x: float) -> float: - """Bereken de hoofdwaarde van de inverse tangens van ``y/x``. + """Calculate the principal value of the inverse tangent of ``y/x``. -Example: ``math.atan2(0, -1)`` + Example: ``math.atan2(0, -1)`` -:param y: (х) Een getal -:param x: (х) Een getal -:return: The principal value of the inverse tangent of ``y/x``""" + :param y: A number + :param x: A number + :return: The principal value of the inverse tangent of ``y/x`` + """ ... def ceil(x: float) -> float: - """Rond een getal af op een positief oneindig. (plafond) + """Round a number towards positive infinity. -Example: ``math.ceil(0.1)`` + Example: ``math.ceil(0.1)`` -:param x: (х) Een getal -:return: ``x`` rounded towards positive infinity.""" + :param x: A number + :return: ``x`` rounded towards positive infinity. + """ ... def copysign(x: float, y: float) -> float: - """Bereken ``x`` met de teken van ``y``. + """Calculate ``x`` with the sign of ``y``. -Example: ``math.copysign(1, -1)`` + Example: ``math.copysign(1, -1)`` -:param x: (х) Een getal -:param y: De bron van het teken voor de retourwaarde -:return: ``x`` with the sign of ``y``""" + :param x: A number + :param y: The source of the sign for the return value + :return: ``x`` with the sign of ``y`` + """ ... def cos(x: float) -> float: - """Bereken de cosinus van ``x``. + """Calculate the cosine of ``x``. -Example: ``math.cos(0)`` + Example: ``math.cos(0)`` -:param x: (х) Een getal -:return: The cosine of ``x``""" + :param x: A number + :return: The cosine of ``x`` + """ ... def degrees(x: float) -> float: - """radialen converteren naar graden: (graden) + """Convert radians to degrees. -Example: ``math.degrees(2 * math.pi)`` + Example: ``math.degrees(2 * math.pi)`` -:param x: (х) Een waarde in radialen -:return: The value converted to degrees""" + :param x: A value in radians + :return: The value converted to degrees""" ... def exp(x: float) -> float: - """Bereken de exponentiële van ``x``. + """Calculate the exponential of ``x``. -Example: ``math.exp(1)`` + Example: ``math.exp(1)`` -:param x: (х) Een getal -:return: The exponential of ``x``.""" + :param x: A number + :return: The exponential of ``x``. + """ ... def fabs(x: float) -> float: - """Geeft de absolute waarde van ``x``. + """Return the absolute value of ``x``. -Example: ``math.fabs(-0.1)`` + Example: ``math.fabs(-0.1)`` -:param x: (х) Een getal -:return: The absolute value of ``x``""" + :param x: A number + :return: The absolute value of ``x`` + """ ... def floor(x: float) -> int: - """Rond een getal af op een negatief oneindig. + """Round a number towards negative infinity. -Example: ``math.floor(0.9)`` + Example: ``math.floor(0.9)`` -:param x: (х) Een getal -:return: ``x`` rounded towards negative infinity.""" + :param x: A number + :return: ``x`` rounded towards negative infinity. + """ ... def fmod(x: float, y: float) -> float: - """Bereken de rest van ``x/y``. + """Calculate the remainder of ``x/y``. -Example: ``math.fmod(10, 3)`` + Example: ``math.fmod(10, 3)`` -:param x: (х) De nummeraar -:param y: De noemer""" + :param x: The numerator + :param y: The denominator + """ ... def frexp(x: float) -> Tuple[float, int]: - """Ontleedt een getal met drijvende komma in zijn mantisse en exponent. + """Decomposes a floating-point number into its mantissa and exponent. -Example: ``mantissa, exponent = math.frexp(2)`` + Example: ``mantissa, exponent = math.frexp(2)`` -The returned value is the tuple ``(m, e)`` such that ``x == m * 2**e`` -exactly. If ``x == 0`` then the function returns ``(0.0, 0)``, otherwise -the relation ``0.5 <= abs(m) < 1`` holds. + The returned value is the tuple ``(m, e)`` such that ``x == m * 2**e`` + exactly. If ``x == 0`` then the function returns ``(0.0, 0)``, otherwise + the relation ``0.5 <= abs(m) < 1`` holds. -:param x: (х) Getal met drijvende komma -:return: A tuple of length two containing its mantissa then exponent""" + :param x: A floating-point number + :return: A tuple of length two containing its mantissa then exponent + """ ... def isfinite(x: float) -> bool: - """Controleer of een waarde eindig is. (is eindig) + """Check if a value is finite. -Example: ``math.isfinite(float('inf'))`` + Example: ``math.isfinite(float('inf'))`` -:param x: (х) Een getal. -:return: ``True`` if ``x`` is finite, ``False`` otherwise.""" + :param x: A number. + :return: ``True`` if ``x`` is finite, ``False`` otherwise. + """ ... def isinf(x: float) -> bool: - """Controleer of een waarde oneindig is. + """Check if a value is infinite. -Example: ``math.isinf(float('-inf'))`` + Example: ``math.isinf(float('-inf'))`` -:param x: (х) Een getal. -:return: ``True`` if ``x`` is infinite, ``False`` otherwise.""" + :param x: A number. + :return: ``True`` if ``x`` is infinite, ``False`` otherwise. + """ ... def isnan(x: float) -> bool: - """Check if is een waarde is geen getal (NaN). + """Check if a value is not-a-number (NaN). -Example: ``math.isnan(float('nan'))`` + Example: ``math.isnan(float('nan'))`` -:param x: (х) Een getal -:return: ``True`` if ``x`` is not-a-number (NaN), ``False`` otherwise.""" + :param x: A number + :return: ``True`` if ``x`` is not-a-number (NaN), ``False`` otherwise.""" ... def ldexp(x: float, exp: int) -> float: - """Bereken ``x * (2**exp)``. + """Calculate ``x * (2**exp)``. -Example: ``math.ldexp(0.5, 2)`` + Example: ``math.ldexp(0.5, 2)`` -:param x: (х) Een getal -:param exp: Integer exponent -:return: ``x * (2**exp)``""" + :param x: A number + :param exp: Integer exponent + :return: ``x * (2**exp)`` + """ ... -def log(x: float, base: float=e) -> float: - """Bereken het logaritme van ``x`` naar de opgegeven basis (standaard is het natuurlijke logalgoritme). +def log(x: float, base: float = e) -> float: + """Calculate the logarithm of ``x`` to the given base (defaults to natural logorithm). -Example: ``math.log(math.e)`` + Example: ``math.log(math.e)`` -With one argument, return the natural logarithm of x (to base e). + With one argument, return the natural logarithm of x (to base e). -With two arguments, return the logarithm of x to the given base, calculated as ``log(x)/log(base)``. + With two arguments, return the logarithm of x to the given base, calculated as ``log(x)/log(base)``. -:param x: (х) Een getal -:param base: (grondtal) Het grondtal om te gebruiken -:return: The natural logarithm of ``x``""" + :param x: A number + :param base: The base to use + :return: The natural logarithm of ``x`` + """ ... def modf(x: float) -> Tuple[float, float]: - """Bereken de fractionele en integrale onderdelen van ``x``. + """Calculate the fractional and integral parts of ``x``. -Example: ``fractional, integral = math.modf(1.5)`` + Example: ``fractional, integral = math.modf(1.5)`` -:param x: (х) Een getal -:return: A tuple of two floats representing the fractional then integral parts of ``x``. + :param x: A number + :return: A tuple of two floats representing the fractional then integral parts of ``x``. -Both the fractional and integral values have the same sign as ``x``.""" + Both the fractional and integral values have the same sign as ``x``. + """ ... def pow(x: float, y: float) -> float: - """Retourneert ``x`` naar de kracht van ``y``. + """Returns ``x`` to the power of ``y``. -Example: ``math.pow(4, 0.5)`` + Example: ``math.pow(4, 0.5)`` -:param x: (х) Een getal -:param y: De exponent -:return: ``x`` to the power of ``y``""" + :param x: A number + :param y: The exponent + :return: ``x`` to the power of ``y`` + """ ... def radians(x: float) -> float: - """Converteer graden naar radialen. (radialen) + """Convert a degrees to radians. -Example: ``math.radians(360)`` + Example: ``math.radians(360)`` -:param x: (х) Een waarde in graden -:return: The value converted to radians""" + :param x: A value in degrees + :return: The value converted to radians + """ ... def sin(x: float) -> float: - """Bereken de sinus van ``x``. + """Calculate the sine of ``x``. -Example: ``math.sin(math.pi/2)`` + Example: ``math.sin(math.pi/2)`` -:param x: (х) Een getal -:return: The sine of ``x``""" + :param x: A number + :return: The sine of ``x`` + """ ... def sqrt(x: float) -> float: - """Bereken de wortel van ``x``. (wortel) + """Calculate the square root of ``x``. -Example: ``math.sqrt(4)`` + Example: ``math.sqrt(4)`` -:param x: (х) Een getal -:return: The square root of ``x``""" + :param x: A number + :return: The square root of ``x`` + """ ... def tan(x: float) -> float: - """Bereken de tangens van ``x``. + """Calculate the tangent of ``x``. -Example: ``math.tan(0)`` + Example: ``math.tan(0)`` -:param x: (х) Een getal -:return: The tangent of ``x``.""" + :param x: A number + :return: The tangent of ``x``. + """ ... def trunc(x: float) -> int: - """Rond een getal af naar 0. + """Round a number towards 0. -Example: ``math.trunc(-0.9)`` + Example: ``math.trunc(-0.9)`` -:param x: (х) Een getal -:return: ``x`` rounded towards zero.""" + :param x: A number + :return: ``x`` rounded towards zero. + """ ... + e: float -"""Basis van het natuurlijke logaritme""" +"""Base of the natural logarithm""" + pi: float -"""De omtrek van een cirkel tot de diameter""" \ No newline at end of file +"""The ratio of a circle's circumference to its diameter""" diff --git a/lang/nl/typeshed/stdlib/microbit/__init__.pyi b/lang/nl/typeshed/stdlib/microbit/__init__.pyi index aa650d8..f12158f 100644 --- a/lang/nl/typeshed/stdlib/microbit/__init__.pyi +++ b/lang/nl/typeshed/stdlib/microbit/__init__.pyi @@ -1,6 +1,11 @@ -"""Pinnen, afbeeldingen, geluiden, temperatuur en volume.""" +"""Pins, images, sounds, temperature and volume. +""" + from typing import Any, Callable, List, Optional, Tuple, Union, overload + from _typeshed import ReadableBuffer + +# V2 only from . import accelerometer as accelerometer from . import audio as audio from . import compass as compass @@ -11,701 +16,831 @@ from . import speaker as speaker from . import spi as spi from . import uart as uart -def run_every(callback: Optional[Callable[[], None]]=None, days: int=0, h: int=0, min: int=0, s: int=0, ms: int=0) -> Callable[[Callable[[], None]], Callable[[], None]]: - """Plan om een functie uit te voeren volgens het interval dat gespecificeerd is door het time argument **V2 alleen**. (draai elke) +def run_every( + callback: Optional[Callable[[], None]] = None, + days: int = 0, + h: int = 0, + min: int = 0, + s: int = 0, + ms: int = 0, +) -> Callable[[Callable[[], None]], Callable[[], None]]: + """Schedule to run a function at the interval specified by the time arguments **V2 only**. -Example: ``run_every(my_logging, min=5)`` + Example: ``run_every(my_logging, min=5)`` -``run_every`` can be used in two ways: + ``run_every`` can be used in two ways: -As a Decorator - placed on top of the function to schedule. For example:: + As a Decorator - placed on top of the function to schedule. For example:: - @run_every(h=1, min=20, s=30, ms=50) - def my_function(): - # Do something here + @run_every(h=1, min=20, s=30, ms=50) + def my_function(): + # Do something here -As a Function - passing the callback as a positional argument. For example:: + As a Function - passing the callback as a positional argument. For example:: - def my_function(): - # Do something here - run_every(my_function, s=30) + def my_function(): + # Do something here + run_every(my_function, s=30) -Each argument corresponds to a different time unit and they are additive. -So ``run_every(min=1, s=30)`` schedules the callback every minute and a half. + Each argument corresponds to a different time unit and they are additive. + So ``run_every(min=1, s=30)`` schedules the callback every minute and a half. -When an exception is thrown inside the callback function it deschedules the -function. To avoid this you can catch exceptions with ``try/except``. + When an exception is thrown inside the callback function it deschedules the + function. To avoid this you can catch exceptions with ``try/except``. -:param callback: Functie om op te roepen bij de meegeleverde interval. Weglaten wanneer je als decorator gebruikt. -:param days: (dagen) Stelt de dag markering in voor de planning. -:param h: (uur) Stelt de urenmarkering in voor de planning. -:param min: Stelt de minuut markering in voor de planning. -:param s: Stelt de seconde markering in voor de planning. -:param ms: Stelt de milliseconde markering in voor de planning.""" + :param callback: Function to call at the provided interval. Omit when using as a decorator. + :param days: Sets the day mark for the scheduling. + :param h: Sets the hour mark for the scheduling. + :param min: Sets the minute mark for the scheduling. + :param s: Sets the second mark for the scheduling. + :param ms: Sets the millisecond mark for the scheduling. + """ def panic(n: int) -> None: - """Voer een paniekmodus in. (paniek) + """Enter a panic mode. -Example: ``panic(127)`` + Example: ``panic(127)`` -:param n: Een willekeurig geheel getal <= 255 om een status aan te geven. + :param n: An arbitrary integer <= 255 to indicate a status. -Requires restart.""" + Requires restart. + """ def reset() -> None: - """Herstart het bord.""" + """Restart the board.""" + @overload def scale(value: float, from_: Tuple[float, float], to: Tuple[int, int]) -> int: - """Zet een waarde om van een bereik naar een ander bereik van natuurlijke getallen. (schaal) + """Converts a value from a range to an integer range. -Example: ``volume = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255))`` + Example: ``volume = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255))`` -For example, to convert an accelerometer X value to a speaker volume. + For example, to convert an accelerometer X value to a speaker volume. -If one of the numbers in the ``to`` parameter is a floating point -(i.e a decimal number like ``10.0``), this function will return a -floating point number. + If one of the numbers in the ``to`` parameter is a floating point + (i.e a decimal number like ``10.0``), this function will return a + floating point number. - temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0)) + temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0)) -:param value: (waarde) Een getal om te converteren -:param from_: (van) Een getallen paar wat het bereik aangeeft vanwaar je wilt converteren -:param to: (naar) Een getallen paar om het bereik te definiëren waar je naar wilt converteren. -:return: The ``value`` converted to the ``to`` range.""" + :param value: A number to convert. + :param from_: A tuple to define the range to convert from. + :param to: A tuple to define the range to convert to. + :return: The ``value`` converted to the ``to`` range. + """ @overload def scale(value: float, from_: Tuple[float, float], to: Tuple[float, float]) -> float: - """Zet een waarde om van een bereik naar een ander bereik van decimale getallen. (schaal) + """Converts a value from a range to a floating point range. -Example: ``temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0))`` + Example: ``temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0))`` -For example, to convert temperature from a Celsius scale to Fahrenheit. + For example, to convert temperature from a Celsius scale to Fahrenheit. -If one of the numbers in the ``to`` parameter is a floating point -(i.e a decimal number like ``10.0``), this function will return a -floating point number. -If they are both integers (i.e ``10``), it will return an integer:: + If one of the numbers in the ``to`` parameter is a floating point + (i.e a decimal number like ``10.0``), this function will return a + floating point number. + If they are both integers (i.e ``10``), it will return an integer:: - returns_int = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255)) + returns_int = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255)) -:param value: (waarde) Een getal om te converteren -:param from_: (van) Een getallen paar wat het bereik aangeeft vanwaar je wilt converteren -:param to: (naar) Een getallen paar om het bereik te definiëren waar je naar wilt converteren. -:return: The ``value`` converted to the ``to`` range.""" + :param value: A number to convert. + :param from_: A tuple to define the range to convert from. + :param to: A tuple to define the range to convert to. + :return: The ``value`` converted to the ``to`` range. + """ def sleep(n: float) -> None: - """Wacht op ``n`` milliseconden. (slapen) + """Wait for ``n`` milliseconds. -Example: ``sleep(1000)`` + Example: ``sleep(1000)`` -:param n: Het aantal milliseconden te wachten + :param n: The number of milliseconds to wait -One second is 1000 milliseconds, so:: + One second is 1000 milliseconds, so:: - microbit.sleep(1000) + microbit.sleep(1000) -will pause the execution for one second.""" + will pause the execution for one second. + """ def running_time() -> int: - """Bekijk de looptijd van het bord. (looptijd) + """Get the running time of the board. -:return: The number of milliseconds since the board was switched on or restarted.""" + :return: The number of milliseconds since the board was switched on or restarted. + """ def temperature() -> int: - """Krijg de temperatuur van de micro:bit in graden Celsius. (temperatuur)""" + """Get the temperature of the micro:bit in degrees Celsius.""" def set_volume(v: int) -> None: - """Stelt het volume in. (stel volume in) + """Sets the volume. -Example: ``set_volume(127)`` + Example: ``set_volume(127)`` -:param v: een waarde tussen 0 (laag) en 255 (hoog). + :param v: a value between 0 (low) and 255 (high). -Out of range values will be clamped to 0 or 255. + Out of range values will be clamped to 0 or 255. -**V2** only.""" + **V2** only. + """ ... class Button: - """De klasse voor de knoppen ``button_a`` en ``button_b``. (knop)""" + """The class for the buttons ``button_a`` and ``button_b``.""" def is_pressed(self) -> bool: - """Controleer of op de knop wordt gedrukt. (is ingedrukt) + """Check if the button is pressed. -:return: ``True`` if the specified button ``button`` is pressed, and ``False`` otherwise.""" + :return: ``True`` if the specified button ``button`` is pressed, and ``False`` otherwise. + """ ... - def was_pressed(self) -> bool: - """Controleer of de knop was ingedrukt sinds het apparaat is gestart of de laatste keer dat deze methode is gebruikt. (was ingedrukt) + """Check if the button was pressed since the device started or the last time this method was called. -Calling this method will clear the press state so -that the button must be pressed again before this method will return -``True`` again. + Calling this method will clear the press state so + that the button must be pressed again before this method will return + ``True`` again. -:return: ``True`` if the specified button ``button`` was pressed, and ``False`` otherwise""" + :return: ``True`` if the specified button ``button`` was pressed, and ``False`` otherwise + """ ... - def get_presses(self) -> int: - """Krijg het totale aantal ingedrukte knoppen en reset dit totaal -naar nul voordat u terugkeert. (zie knop acties) + """Get the running total of button presses, and resets this total + to zero before returning. -:return: The number of presses since the device started or the last time this method was called""" + :return: The number of presses since the device started or the last time this method was called + """ ... + button_a: Button -"""Het object van de linker knop ``Button``. (knop a)""" +"""The left button ``Button`` object.""" + button_b: Button -"""Het object van de rechter knop ``Button``. (knop b)""" +"""The right button ``Button`` object.""" class MicroBitDigitalPin: - """Een digitale pin + """A digital pin. + + Some pins support analog and touch features using the ``MicroBitAnalogDigitalPin`` and ``MicroBitTouchPin`` subclasses. + """ -Some pins support analog and touch features using the ``MicroBitAnalogDigitalPin`` and ``MicroBitTouchPin`` subclasses.""" NO_PULL: int PULL_UP: int PULL_DOWN: int - def read_digital(self) -> int: - """Haal de digitale waarde van de pincode op. (digitaal lezen) + """Get the digital value of the pin. -Example: ``value = pin0.read_digital()`` + Example: ``value = pin0.read_digital()`` -:return: 1 if the pin is high, and 0 if it's low.""" + :return: 1 if the pin is high, and 0 if it's low. + """ ... - def write_digital(self, value: int) -> None: - """Stel de digitale waarde van de pin in. (digitaal schrijven) + """Set the digital value of the pin. -Example: ``pin0.write_digital(1)`` + Example: ``pin0.write_digital(1)`` -:param value: (waarde) 1 om de pin hoog of 0 om de pin laag in te stellen""" + :param value: 1 to set the pin high or 0 to set the pin low""" ... - def set_pull(self, value: int) -> None: - """Zet de pull-status op een van de drie mogelijke waarden: ``PULL_UP``, ``PULL_DOWN`` of ``NO_PULL``. (pull instellen) + """Set the pull state to one of three possible values: ``PULL_UP``, ``PULL_DOWN`` or ``NO_PULL``. -Example: ``pin0.set_pull(pin0.PULL_UP)`` + Example: ``pin0.set_pull(pin0.PULL_UP)`` -:param value: (waarde) De pull-status van de relevante pincode, bijvoorbeeld ``pin0.PULL_UP``.""" + :param value: The pull state from the relevant pin, e.g. ``pin0.PULL_UP``. + """ ... - def get_pull(self) -> int: - """Bekijk de pull status van een pin. (pull instellen) + """Get the pull state on a pin. -Example: ``pin0.get_pull()`` + Example: ``pin0.get_pull()`` -:return: ``NO_PULL``, ``PULL_DOWN``, or ``PULL_UP`` + :return: ``NO_PULL``, ``PULL_DOWN``, or ``PULL_UP`` -These are set using the ``set_pull()`` method or automatically configured -when a pin mode requires it.""" + These are set using the ``set_pull()`` method or automatically configured + when a pin mode requires it. + """ ... - def get_mode(self) -> str: - """Geeft de pinmodus weer. (Bekijk modus) + """Returns the pin mode. -Example: ``pin0.get_mode()`` + Example: ``pin0.get_mode()`` -When a pin is used for a specific function, like -writing a digital value, or reading an analog value, the pin mode -changes. + When a pin is used for a specific function, like + writing a digital value, or reading an analog value, the pin mode + changes. -:return: ``"unused"``, ``"analog"``, ``"read_digital"``, ``"write_digital"``, ``"display"``, ``"button"``, ``"music"``, ``"audio"``, ``"touch"``, ``"i2c"``, or ``"spi"``""" + :return: ``"unused"``, ``"analog"``, ``"read_digital"``, ``"write_digital"``, ``"display"``, ``"button"``, ``"music"``, ``"audio"``, ``"touch"``, ``"i2c"``, or ``"spi"`` + """ ... - def write_analog(self, value: int) -> None: - """Voer een PWM-signaal uit op de pin, waarbij de taakcyclus proportioneel is aan ``value``. (analoge schrijven) - -Example: ``pin0.write_analog(254)`` + """Output a PWM signal on the pin, with the duty cycle proportional to ``value``. -:param value: (waarde) Een geheel getal of een zwevend punt getal tussen 0 (0% tariefcyclus) en 1023 (100% belasting).""" + Example: ``pin0.write_analog(254)`` + :param value: An integer or a floating point number between 0 (0% duty cycle) and 1023 (100% duty). + """ def set_analog_period(self, period: int) -> None: - """Stel de periode in van het PWM-signaal dat uitgevoerd wordt naar ``period`` in milliseconden. (gebruik analoge periode) + """Set the period of the PWM signal being output to ``period`` in milliseconds. -Example: ``pin0.set_analog_period(10)`` - -:param period: (periode) De periode in milliseconden met een minimale geldige waarde van 1 ms.""" + Example: ``pin0.set_analog_period(10)`` + :param period: The period in milliseconds with a minimum valid value of 1ms. + """ def set_analog_period_microseconds(self, period: int) -> None: - """Stel de periode in van het PWM-signaal dat uitgevoerd wordt naar ``period`` in milliseconden. (microseconden analoge periode instellen) + """Set the period of the PWM signal being output to ``period`` in microseconds. -Example: ``pin0.set_analog_period_microseconds(512)`` + Example: ``pin0.set_analog_period_microseconds(512)`` -:param period: (periode) De periode in microseconden met een minimumwaarde van 256 mres.""" + :param period: The period in microseconds with a minimum valid value of 256µs. + """ class MicroBitAnalogDigitalPin(MicroBitDigitalPin): - """Een pin met analoge en digitale functies.""" + """A pin with analog and digital features.""" def read_analog(self) -> int: - """Lees de spanning op de pin. (lees analoge) + """Read the voltage applied to the pin. -Example: ``pin0.read_analog()`` + Example: ``pin0.read_analog()`` -:return: An integer between 0 (meaning 0V) and 1023 (meaning 3.3V).""" + :return: An integer between 0 (meaning 0V) and 1023 (meaning 3.3V). + """ class MicroBitTouchPin(MicroBitAnalogDigitalPin): - """Een pin met analoge, digitale en touch functies.""" + """A pin with analog, digital and touch features.""" + CAPACITIVE: int RESISTIVE: int - def is_touched(self) -> bool: - """Controleer of de pin aangeraakt wordt. (is aangeraakt) + """Check if the pin is being touched. -Example: ``pin0.is_touched()`` + Example: ``pin0.is_touched()`` -The default touch mode for the pins on the edge connector is ``resistive``. -The default for the logo pin **V2** is ``capacitive``. + The default touch mode for the pins on the edge connector is ``resistive``. + The default for the logo pin **V2** is ``capacitive``. -**Resistive touch** -This test is done by measuring how much resistance there is between the -pin and ground. A low resistance gives a reading of ``True``. To get -a reliable reading using a finger you may need to touch the ground pin -with another part of your body, for example your other hand. + **Resistive touch** + This test is done by measuring how much resistance there is between the + pin and ground. A low resistance gives a reading of ``True``. To get + a reliable reading using a finger you may need to touch the ground pin + with another part of your body, for example your other hand. -**Capacitive touch** -This test is done by interacting with the electric field of a capacitor -using a finger as a conductor. `Capacitive touch -`_ -does not require you to make a ground connection as part of a circuit. + **Capacitive touch** + This test is done by interacting with the electric field of a capacitor + using a finger as a conductor. `Capacitive touch + `_ + does not require you to make a ground connection as part of a circuit. -:return: ``True`` if the pin is being touched with a finger, otherwise return ``False``.""" + :return: ``True`` if the pin is being touched with a finger, otherwise return ``False``. + """ ... - def set_touch_mode(self, value: int) -> None: - """Stel de aanraakmodus voor de pin in. (aanraakmodus instellen) + """Set the touch mode for the pin. -Example: ``pin0.set_touch_mode(pin0.CAPACITIVE)`` + Example: ``pin0.set_touch_mode(pin0.CAPACITIVE)`` -The default touch mode for the pins on the edge connector is -``resistive``. The default for the logo pin **V2** is ``capacitive``. + The default touch mode for the pins on the edge connector is + ``resistive``. The default for the logo pin **V2** is ``capacitive``. -:param value: (waarde) ``CAPACITIVE`` of ``RESISTIVE`` van de relevante speler.""" + :param value: ``CAPACITIVE`` or ``RESISTIVE`` from the relevant pin. + """ ... + pin0: MicroBitTouchPin -"""Pin met digitale, analoge en touch functies.""" +"""Pin with digital, analog and touch features.""" + pin1: MicroBitTouchPin -"""Pin met digitale, analoge en aanraak functies.""" +"""Pin with digital, analog and touch features.""" + pin2: MicroBitTouchPin -"""Pin met digitale, analoge en aanraak functies.""" +"""Pin with digital, analog and touch features.""" + pin3: MicroBitAnalogDigitalPin -"""Pin met digitale, analoge en aanraak functies.""" +"""Pin with digital and analog features.""" + pin4: MicroBitAnalogDigitalPin -"""Pin met digitale, analoge en aanraak functies.""" +"""Pin with digital and analog features.""" + pin5: MicroBitDigitalPin -"""Pin met digitale, analoge en aanraak functies.""" +"""Pin with digital features.""" + pin6: MicroBitDigitalPin -"""Pin met digitale functies.""" +"""Pin with digital features.""" + pin7: MicroBitDigitalPin -"""Pin met digitale functies.""" +"""Pin with digital features.""" + pin8: MicroBitDigitalPin -"""Pin met digitale functies.""" +"""Pin with digital features.""" + pin9: MicroBitDigitalPin -"""Pin met digitale functies.""" +"""Pin with digital features.""" + pin10: MicroBitAnalogDigitalPin -"""Pin met digitale, analoge en aanraak functies.""" +"""Pin with digital and analog features.""" + pin11: MicroBitDigitalPin -"""Pin met digitale, analoge en aanraak functies.""" +"""Pin with digital features.""" + pin12: MicroBitDigitalPin -"""Pin met digitale, analoge en aanraak functies.""" +"""Pin with digital features.""" + pin13: MicroBitDigitalPin -"""Pin met digitale, analoge en aanraak functies.""" +"""Pin with digital features.""" + pin14: MicroBitDigitalPin -"""Pin met digitale, analoge en aanraak functies.""" +"""Pin with digital features.""" + pin15: MicroBitDigitalPin -"""Pin met digitale, analoge en aanraak functies.""" +"""Pin with digital features.""" + pin16: MicroBitDigitalPin -"""Pin met digitale, analoge en aanraak functies.""" +"""Pin with digital features.""" + pin19: MicroBitDigitalPin -"""Pin met digitale, analoge en aanraak functies.""" +"""Pin with digital features.""" + pin20: MicroBitDigitalPin -"""Pin met digitale, analoge en aanraak functies.""" +"""Pin with digital features.""" + pin_logo: MicroBitTouchPin -"""Een aanraak gevoelige logo pin op de voorkant van de micro:bit, die standaard is ingesteld op capacitieve aanraking modus.""" +"""A touch sensitive logo pin on the front of the micro:bit, which by default is set to capacitive touch mode.""" + pin_speaker: MicroBitAnalogDigitalPin -"""Een pin om de micro:bit luidspreker aan te spreken. (pin luidspreker) +"""A pin to address the micro:bit speaker. This API is intended only for use in Pulse-Width Modulation pin operations e.g. pin_speaker.write_analog(128). """ class Image: - """Een afbeelding om te laten zien op het micro:bit LED display. (afbeelding) + """An image to show on the micro:bit LED display. -Given an image object it's possible to display it via the ``display`` API:: + Given an image object it's possible to display it via the ``display`` API:: + + display.show(Image.HAPPY) + """ - display.show(Image.HAPPY)""" HEART: Image - """Hart afbeelding (hart)""" + """Heart image.""" + HEART_SMALL: Image - """Klein hart afbeelding. (hart klein)""" + """Small heart image.""" + HAPPY: Image - """Blije gezichtsafbeelding. (blij)""" + """Happy face image.""" + SMILE: Image - """Glimlach gezicht afbeelding. (glimlach)""" + """Smiling mouth image.""" + SAD: Image - """Droevige gezichtsafbeelding. (verdrietig)""" + """Sad face image.""" + CONFUSED: Image - """Verward gezichtsafbeelding. (verward)""" + """Confused face image.""" + ANGRY: Image - """Boos gezichtsafbeelding. (kwaad)""" + """Angry face image.""" + ASLEEP: Image - """Slapend gezicht afbeelding. (in slaap)""" + """Sleeping face image.""" + SURPRISED: Image - """Verraste gezichtsafbeelding. (verrast)""" + """Surprised face image.""" + SILLY: Image - """Gek gezichtsafbeelding. (gek)""" + """Silly face image.""" + FABULOUS: Image - """Zonnebril gezichtsafbeelding. (fantastisch)""" + """Sunglasses face image.""" + MEH: Image - """Niet onder de indruk gezichtsafbeelding.""" + """Unimpressed face image.""" + YES: Image - """Aanvinken afbeelding. (ja)""" + """Tick image.""" + NO: Image - """Kruis afbeelding. (nee)""" + """Cross image.""" + CLOCK12: Image - """Afbeelding met lijn die naar 12.00 uur wijst. (klok 12)""" + """Image with line pointing to 12 o'clock.""" + CLOCK11: Image - """Afbeelding met lijn die naar 11.00 uur wijst. (klok 11)""" + """Image with line pointing to 11 o'clock.""" + CLOCK10: Image - """Afbeelding met lijn die naar 10.00 uur wijst. (klok 10)""" + """Image with line pointing to 10 o'clock.""" + CLOCK9: Image - """Afbeelding met lijn die naar 9.00 uur wijst. (klok 9)""" + """Image with line pointing to 9 o'clock.""" + CLOCK8: Image - """Afbeelding met lijn die naar 8.00 uur wijst. (klok 8)""" + """Image with line pointing to 8 o'clock.""" + CLOCK7: Image - """Afbeelding met lijn die naar 7.00 uur wijst. (klok 7)""" + """Image with line pointing to 7 o'clock.""" + CLOCK6: Image - """Afbeelding met lijn die naar 6.00 uur wijst. (klok 6)""" + """Image with line pointing to 6 o'clock.""" + CLOCK5: Image - """Afbeelding met lijn die naar 5.00 uur wijst. (klok 5)""" + """Image with line pointing to 5 o'clock.""" + CLOCK4: Image - """Afbeelding met lijn die naar 4.00 uur wijst. (klok 4)""" + """Image with line pointing to 4 o'clock.""" + CLOCK3: Image - """Afbeelding met lijn die naar 3.00 uur wijst. (klok 3)""" + """Image with line pointing to 3 o'clock.""" + CLOCK2: Image - """Afbeelding met lijn die naar 2 uur wijst. (klok2)""" + """Image with line pointing to 2 o'clock.""" + CLOCK1: Image - """Afbeelding met lijn die naar 1 uur wijst. (klok1)""" + """Image with line pointing to 1 o'clock.""" + ARROW_N: Image - """Afbeelding van pijl richting het noorden. (pijl n)""" + """Image of arrow pointing north.""" + ARROW_NE: Image - """Afbeelding van pijl richting het noord oosten. (pijl NO)""" + """Image of arrow pointing north east.""" + ARROW_E: Image - """Afbeelding van pijl richting het oosten. (pijl e)""" + """Image of arrow pointing east.""" + ARROW_SE: Image - """Afbeelding van pijl richting het zuid-oosten. (pijl ZO)""" + """Image of arrow pointing south east.""" + ARROW_S: Image - """Afbeelding van pijltje richting het zuiden. (pijl z)""" + """Image of arrow pointing south.""" + ARROW_SW: Image - """Afbeelding van pijl richting het zuid-westen. (pijl ZW)""" + """Image of arrow pointing south west.""" + ARROW_W: Image - """Afbeelding van pijl richting het westen. (pijl w)""" + """Image of arrow pointing west.""" + ARROW_NW: Image - """Afbeelding van pijl richting het noord-westen. (pijl NW)""" + """Image of arrow pointing north west.""" + TRIANGLE: Image - """Afbeelding van een driehoek die naar boven wijst. (driehoek)""" + """Image of a triangle pointing up.""" + TRIANGLE_LEFT: Image - """Afbeelding van een driehoek in de linker hoek. (Driehoek links)""" + """Image of a triangle in the left corner.""" + CHESSBOARD: Image - """Alternatieve LED's verlichten in een schaakbord patroon. (schaakbord)""" + """Alternate LEDs lit in a chessboard pattern.""" + DIAMOND: Image - """Diamanten afbeelding. (diamant)""" + """Diamond image.""" + DIAMOND_SMALL: Image - """Kleine diamanten afbeelding. (diamant klein)""" + """Small diamond image.""" + SQUARE: Image - """Vierkante afbeelding (vierkant)""" + """Square image.""" + SQUARE_SMALL: Image - """Kleine vierkante afbeelding. (vierkant klein)""" + """Small square image.""" + RABBIT: Image - """Konijn afbeelding. (konijn)""" + """Rabbit image.""" + COW: Image - """Koe afbeelding. (koe)""" + """Cow image.""" + MUSIC_CROTCHET: Image - """Kwartnoot afbeelding. (muziek kwartnoot)""" + """Crotchet note image.""" + MUSIC_QUAVER: Image - """Kwartnoot afbeelding. (muziek kwartnoot)""" + """Quaver note image.""" + MUSIC_QUAVERS: Image - """Koppel van kwartnoten afbeelding. (muziek kwartnoten)""" + """Pair of quavers note image.""" + PITCHFORK: Image - """Stemvork afbeelding. (stemvork)""" + """Pitchfork image.""" + XMAS: Image - """Kerstboom afbeelding. (kerstmis)""" + """Christmas tree image.""" + PACMAN: Image - """Pac-Man arcade karakterafbeelding. (Pacman)""" + """Pac-Man arcade character image.""" + TARGET: Image - """Doel afbeelding. (doel)""" + """Target image.""" + TSHIRT: Image - """T-shirt afbeelding.""" + """T-shirt image.""" + ROLLERSKATE: Image - """Rolschaats afbeelding. (rolschaatsen)""" + """Rollerskate image.""" + DUCK: Image - """Eend afbeelding. (eend)""" + """Duck image.""" + HOUSE: Image - """Huis afbeelding. (huis)""" + """House image.""" + TORTOISE: Image - """Schildpad afbeelding. (schildpad)""" + """Tortoise image.""" + BUTTERFLY: Image - """Vlinder afbeelding. (vlinder)""" + """Butterfly image.""" + STICKFIGURE: Image - """Stok figuur afbeelding. (stok figuur)""" + """Stick figure image.""" + GHOST: Image - """Spook afbeelding. (spook)""" + """Ghost image.""" + SWORD: Image - """Zwaard afbeelding. (zwaard)""" + """Sword image.""" + GIRAFFE: Image - """Giraffe afbeelding.""" + """Giraffe image.""" + SKULL: Image - """Schedel afbeelding. (doodshoofd)""" + """Skull image.""" + UMBRELLA: Image - """Paraplu afbeelding. (paraplu)""" + """Umbrella image.""" + SNAKE: Image - """Slang afbeelding. (slang)""" + """Snake image.""" + SCISSORS: Image - """Schaar afbeelding. (schaar)""" + """Scissors image.""" + ALL_CLOCKS: List[Image] - """Een lijst met alle CLOCK_ afbeeldingen achter elkaar. (alle klokken)""" - ALL_ARROWS: List[Image] - """Een lijst met alle ARROW_ afbeeldingen in reeks. (alle pijlen)""" + """A list containing all the CLOCK_ images in sequence.""" + ALL_ARROWS: List[Image] + """A list containing all the ARROW_ images in sequence.""" @overload def __init__(self, string: str) -> None: - """Maak een afbeelding van een tekenreeks die beschrijft welke LED's zijn. (initialiseren) + """Create an image from a string describing which LEDs are lit. -``string`` has to consist of digits 0-9 arranged into lines, -describing the image, for example:: + ``string`` has to consist of digits 0-9 arranged into lines, + describing the image, for example:: - image = Image("90009:" - "09090:" - "00900:" - "09090:" - "90009") + 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 newlines (\\n) insead of the colons. + 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 newlines (\\n) insead of the colons. -:param string: (tekenreeks) De tekenreeks die de afbeelding beschrijft.""" + :param string: The string describing the image. + """ ... - @overload - def __init__(self, width: int=5, height: int=5, buffer: ReadableBuffer=None) -> None: - """Maak een lege afbeelding met ``width`` kolommen en ``height`` rijen. (initialiseren) + def __init__( + self, width: int = 5, height: int = 5, buffer: ReadableBuffer = None + ) -> None: + """Create an empty image with ``width`` columns and ``height`` rows. -:param width: (breedte) Optionele breedte van de afbeelding -:param height: (hoogte) Optionele hoogte van de afbeelding -:param buffer: Optionele array of bytes van ``width``×``height`` integers in bereik 0-9 om de afbeelding te initialiseren + :param width: Optional width of the image + :param height: Optional height of the image + :param buffer: Optional array or bytes of ``width``×``height`` integers in range 0-9 to initialize the image -Examples:: + Examples:: - Image(2, 2, b'\x08\x08\x08\x08') - Image(2, 2, bytearray([9,9,9,9])) + Image(2, 2, b'\x08\x08\x08\x08') + Image(2, 2, bytearray([9,9,9,9])) -These create 2 x 2 pixel images at full brightness.""" + These create 2 x 2 pixel images at full brightness. + """ ... - def width(self) -> int: - """Haal het aantal kolommen op. (breedte) + """Get the number of columns. -:return: The number of columns in the image""" + :return: The number of columns in the image + """ ... - def height(self) -> int: - """Krijg het aantal rijen. (hoogte) + """Get the number of rows. -:return: The number of rows in the image""" + :return: The number of rows in the image + """ ... - def set_pixel(self, x: int, y: int, value: int) -> None: - """Stel de helderheid van een pixel in. (pixel instellen) + """Set the brightness of a pixel. -Example: ``my_image.set_pixel(0, 0, 9)`` + Example: ``my_image.set_pixel(0, 0, 9)`` -:param x: (х) Het kolom nummer -:param y: Het rij nummer -:param value: (waarde) De helderheid als een geheel getal tussen 0 (donker) en 9 (helder) + :param x: The column number + :param y: The row number + :param value: The brightness as an integer 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``.""" + 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: - """Krijg de helderheid van een pixel. (verkrijg pixel) + """Get the brightness of a pixel. -Example: ``my_image.get_pixel(0, 0)`` + Example: ``my_image.get_pixel(0, 0)`` -:param x: (х) Het kolom nummer -:param y: Het rij nummer -:return: The brightness as an integer between 0 and 9.""" + :param x: The column number + :param y: The row number + :return: The brightness as an integer between 0 and 9. + """ ... - def shift_left(self, n: int) -> Image: - """Maak een nieuwe afbeelding door de afbeelding naar links te verschuiven. (verschuiving naar links) + """Create a new image by shifting the picture left. -Example: ``Image.HEART_SMALL.shift_left(1)`` + Example: ``Image.HEART_SMALL.shift_left(1)`` -:param n: Het aantal te verschuiven kolommen -:return: The shifted image""" + :param n: The number of columns to shift by + :return: The shifted image + """ ... - def shift_right(self, n: int) -> Image: - """Maak een nieuwe afbeelding door de afbeelding rechts te verschuiven. (verschuif Rechts) + """Create a new image by shifting the picture right. -Example: ``Image.HEART_SMALL.shift_right(1)`` + Example: ``Image.HEART_SMALL.shift_right(1)`` -:param n: Het aantal te verschuiven kolommen -:return: The shifted image""" + :param n: The number of columns to shift by + :return: The shifted image + """ ... - def shift_up(self, n: int) -> Image: - """Maak een nieuwe afbeelding door de afbeelding omhoog te schuiven. (verschuiving omhoog) + """Create a new image by shifting the picture up. -Example: ``Image.HEART_SMALL.shift_up(1)`` + Example: ``Image.HEART_SMALL.shift_up(1)`` -:param n: Het aantal rijen om te verschuiven met -:return: The shifted image""" + :param n: The number of rows to shift by + :return: The shifted image + """ ... - def shift_down(self, n: int) -> Image: - """Maak een nieuwe afbeelding door de afbeelding omlaag te verschuiven. (verschuif omlaag) + """Create a new image by shifting the picture down. -Example: ``Image.HEART_SMALL.shift_down(1)`` + Example: ``Image.HEART_SMALL.shift_down(1)`` -:param n: Het aantal rijen om te verschuiven met -:return: The shifted image""" + :param n: The number of rows to shift by + :return: The shifted image + """ ... - def crop(self, x: int, y: int, w: int, h: int) -> Image: - """Maak een nieuwe afbeelding door de afbeelding bij te snijden. (bij snijden) + """Create a new image by cropping the picture. -Example: ``Image.HEART.crop(1, 1, 3, 3)`` + Example: ``Image.HEART.crop(1, 1, 3, 3)`` -:param x: (х) De kolom verschuiving -:param y: De rij verschuiving -:param w: De bij snij breedte -:param h: (uur) Hoogte bijsnijden -:return: The new image""" + :param x: The crop offset column + :param y: The crop offset row + :param w: The crop width + :param h: The crop height + :return: The new image + """ ... - def copy(self) -> Image: - """Maak een exacte kopie van de afbeelding. (kopiëer) + """Create an exact copy of the image. -Example: ``Image.HEART.copy()`` + Example: ``Image.HEART.copy()`` -:return: The new image""" + :return: The new image + """ ... - def invert(self) -> Image: - """Maak een nieuwe afbeelding door de helderheid van de pixels in de -bronafbeelding om te draaien. (omkeren) + """Create a new image by inverting the brightness of the pixels in the + source image. -Example: ``Image.SMALL_HEART.invert()`` + Example: ``Image.SMALL_HEART.invert()`` -:return: The new image.""" + :return: The new image. + """ ... - def fill(self, value: int) -> None: - """Stel de helderheid van alle pixels in de afbeelding in. (opvullen) + """Set the brightness of all the pixels in the image. -Example: ``my_image.fill(5)`` + Example: ``my_image.fill(5)`` -:param value: (waarde) De nieuwe helderheid als een getal tussen 0 (donker) en 9 (helder). + :param value: The new brightness as a number 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``.""" + 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: - """Kopieer een gebied van een andere afbeelding naar deze afbeelding. - -Example: ``my_image.blit(Image.HEART, 1, 1, 3, 3, 1, 1)`` - -:param src: De bron afbeelding -:param x: (х) De begin kolom offset in de bron afbeelding -:param y: De beginkolom offset in de bronafbeelding -:param w: Het aantal te kopiëren kolommen -:param h: (uur) Het aantal te kopiëren rijen -:param xdest: De kolomverschuiving om aan te passen in deze afbeelding -:param ydest: De kolomverschuiving om aan te passen in deze afbeelding - -Pixels outside the source image are treated as having a brightness 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 blit( + self, + src: Image, + x: int, + y: int, + w: int, + h: int, + xdest: int = 0, + ydest: int = 0, + ) -> None: + """Copy an area from another image into this image. + + Example: ``my_image.blit(Image.HEART, 1, 1, 3, 3, 1, 1)`` + + :param src: The source image + :param x: The starting column offset in the source image + :param y: The starting row offset in the source image + :param w: The number of columns to copy + :param h: The number of rows to copy + :param xdest: The column offset to modify in this image + :param ydest: The row offset to modify in this image + + Pixels outside the source image are treated as having a brightness 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: - """Krijg een compacte tekenreeks die de afbeelding vertegenwoordigt.""" + """Get a compact string representation of the image.""" ... - def __str__(self) -> str: - """Krijg een leesbare tekenreeks die de afbeelding vertegenwoordigt.""" + """Get a readable string representation of the image.""" ... - def __add__(self, other: Image) -> Image: - """Maak een nieuwe afbeelding door de helderheidswaarden van de twee -afbeeldingen voor elke pixel toe te voegen. (toevoegen) + """Create a new image by adding the brightness values from the two + images for each pixel. -Example: ``Image.HEART + Image.HAPPY`` + Example: ``Image.HEART + Image.HAPPY`` -:param other: (overige) De afbeelding om toe te voegen.""" + :param other: The image to add. + """ ... - def __sub__(self, other: Image) -> Image: - """Maak een nieuw beeld door de helderheidswaarden van de andere afbeelding van deze afbeelding af te trekken. + """Create a new image by subtracting the brightness values of the + other image from this image. -Example: ``Image.HEART - Image.HEART_SMALL`` + Example: ``Image.HEART - Image.HEART_SMALL`` -:param other: (overige) De afbeelding om af te trekken.""" + :param other: The image to subtract. + """ ... - def __mul__(self, n: float) -> Image: - """Maak een nieuwe afbeelding door de helderheid van elke pixel te vermenigvuldigen met -``n``. + """Create a new image by multiplying the brightness of each pixel by + ``n``. -Example: ``Image.HEART * 0.5`` + Example: ``Image.HEART * 0.5`` -:param n: De waarde om te vermenigvuldigen.""" + :param n: The value to multiply by. + """ ... - def __truediv__(self, n: float) -> Image: - """Maak een nieuwe afbeelding door de helderheid van elke pixel te delen door -``n``. + """Create a new image by dividing the brightness of each pixel by + ``n``. -Example: ``Image.HEART / 2`` + Example: ``Image.HEART / 2`` -:param n: De waarde om mee te delen.""" + :param n: The value to divide by. + """ ... class SoundEvent: LOUD: SoundEvent - """Vertegenwoordigt de transitie van geluidsgebeurtenissen, van ``quiet`` tot ``loud`` zoals klappen of roepen. (luid)""" + """Represents the transition of sound events, from ``quiet`` to ``loud`` like clapping or shouting.""" + QUIET: SoundEvent - """Vertegenwoordigt de transitie van geluidsgebeurtenissen, van ``loud`` tot ``quiet`` zoals spreken of achtergrondmuziek. (stil)""" + """Represents the transition of sound events, from ``loud`` to ``quiet`` like speaking or background music.""" class Sound: - """De ingebouwde geluiden kunnen worden aangeroepen met ``audio.play(Sound.NAME)``. (geluid)""" + """The built-in sounds can be called using ``audio.play(Sound.NAME)``.""" + GIGGLE: Sound - """Giechelgeluidjes (giechelen)""" + """Giggling sound.""" + HAPPY: Sound - """Blij geluid. (blij)""" + """Happy sound.""" + HELLO: Sound - """Groet geluid. (hallo)""" + """Greeting sound.""" + MYSTERIOUS: Sound - """Mysterieus geluid. (mysterieus)""" + """Mysterious sound.""" + SAD: Sound - """Droevig geluid. (verdrietig)""" + """Sad sound.""" + SLIDE: Sound - """Glij geluid. (Veeg)""" + """Sliding sound.""" + SOARING: Sound - """Zweef geluid. (stijgend)""" + """Soaring sound.""" + SPRING: Sound - """Spring geluid. (veer)""" + """Spring sound.""" + TWINKLE: Sound - """Twinkel geluid. (twinkeling)""" + """Twinkling sound.""" + YAWN: Sound - """Geeuwgeluiden (geeuw)""" \ No newline at end of file + """Yawning sound.""" diff --git a/lang/nl/typeshed/stdlib/microbit/accelerometer.pyi b/lang/nl/typeshed/stdlib/microbit/accelerometer.pyi index 85a1426..bac82c0 100644 --- a/lang/nl/typeshed/stdlib/microbit/accelerometer.pyi +++ b/lang/nl/typeshed/stdlib/microbit/accelerometer.pyi @@ -1,103 +1,115 @@ -"""Meet de versnelling van de micro:bit en herken gebaren. (acceleratiemeter)""" +"""Measure the acceleration of the micro:bit and recognise gestures. +""" + from typing import Tuple def get_x() -> int: - """Krijg de acceleratiemeting in de ``x`` as in milli-g. (krijg x) + """Get the acceleration measurement in the ``x`` axis in milli-g. -Example: ``accelerometer.get_x()`` + Example: ``accelerometer.get_x()`` -:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" + :return: A positive or negative integer depending on direction in the range +/- 2000mg. + """ ... def get_y() -> int: - """Krijg de acceleratiemeting in de ``y`` as in milli-g. (krijg y) + """Get the acceleration measurement in the ``y`` axis in milli-g. -Example: ``accelerometer.get_y()`` + Example: ``accelerometer.get_y()`` -:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" + :return: A positive or negative integer depending on direction in the range +/- 2000mg. + """ ... def get_z() -> int: - """Krijg de acceleratiemeter meting in de ``z`` as in milli-g. (krijg z) + """Get the acceleration measurement in the ``z`` axis in milli-g. -Example: ``accelerometer.get_z()`` + Example: ``accelerometer.get_z()`` -:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" + :return: A positive or negative integer depending on direction in the range +/- 2000mg. + """ ... def get_values() -> Tuple[int, int, int]: - """Verkrijg de acceleratiemeter metingen in alle assen tegelijk als een tupel. (krijg waarden) + """Get the acceleration measurements in all axes at once as a tuple. -Example: ``x, y, z = accelerometer.get_values()`` + Example: ``x, y, z = accelerometer.get_values()`` -:return: a three-element tuple of integers ordered as X, Y, Z, each value a positive or negative integer depending on direction in the range +/- 2000mg""" + :return: a three-element tuple of integers ordered as X, Y, Z, each value a positive or negative integer depending on direction in the range +/- 2000mg + """ ... def get_strength() -> int: - """Krijg de versnelling meting van alle assen gecombineerd, als een positief getal. Dit is de Pythagorische som van de X, Y en Z assen. (krijg sterkte) + """Get the acceleration measurement of all axes combined, as a positive integer. This is the Pythagorean sum of the X, Y and Z axes. -Example: ``accelerometer.get_strength()`` + Example: ``accelerometer.get_strength()`` -:return: The combined acceleration strength of all the axes, in milli-g.""" + :return: The combined acceleration strength of all the axes, in milli-g. + """ ... def current_gesture() -> str: - """Verkrijg de naam van het huidige gebaar. (huidig gebaar) + """Get the name of the current gesture. -Example: ``accelerometer.current_gesture()`` + Example: ``accelerometer.current_gesture()`` -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. + 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. -:return: The current gesture""" + :return: The current gesture + """ ... def is_gesture(name: str) -> bool: - """Controleer of het benoemde gebaar momenteel actief is. (is gebaren) + """Check if the named gesture is currently active. -Example: ``accelerometer.is_gesture('shake')`` + Example: ``accelerometer.is_gesture('shake')`` -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. + 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. -:param name: (naam) De naam van het gebaar. -:return: ``True`` if the gesture is active, ``False`` otherwise.""" + :param name: The gesture name. + :return: ``True`` if the gesture is active, ``False`` otherwise. + """ ... def was_gesture(name: str) -> bool: - """Controleer of het benoemde gebaar actief was sinds het laatste gesprek. (was gebaren) + """Check if the named gesture was active since the last call. -Example: ``accelerometer.was_gesture('shake')`` + Example: ``accelerometer.was_gesture('shake')`` -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. + 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. -:param name: (naam) De naam van het gebaar. -:return: ``True`` if the gesture was active since the last call, ``False`` otherwise.""" + :param name: The gesture name. + :return: ``True`` if the gesture was active since the last call, ``False`` otherwise. + """ def get_gestures() -> Tuple[str, ...]: - """Geeft als resultaat een reeks van de gebaren geschiedenis. (verkrijg gebaren) + """Return a tuple of the gesture history. -Example: ``accelerometer.get_gestures()`` + Example: ``accelerometer.get_gestures()`` -Clears the gesture history before returning. + Clears the gesture history before returning. -Gestures are not updated in the background so there needs to be constant -calls to some accelerometer method to do the gesture detection. Usually -gestures can be detected using a loop with a small :func:`microbit.sleep` delay. + Gestures are not updated in the background so there needs to be constant + calls to some accelerometer method to do the gesture detection. Usually + gestures can be detected using a loop with a small :func:`microbit.sleep` delay. -:return: The history as a tuple, most recent last.""" + :return: The history as a tuple, most recent last. + """ ... def set_range(value: int) -> None: - """Stel het gevoeligheidsbereik van de acceleratiemeter, in g (standaard zwaartekracht), in op de dichtstbijzijnde waarden die door de hardware worden ondersteund, zodat het wordt afgerond op ``2``, ``4`` of ``8`` g. (kies bereik) + """Set the accelerometer sensitivity range, in g (standard gravity), to the closest values supported by the hardware, so it rounds to either ``2``, ``4``, or ``8`` g. -Example: ``accelerometer.set_range(8)`` + Example: ``accelerometer.set_range(8)`` -:param value: (waarde) Nieuwe bereik voor de acceleratiemeter, een geheel getal in ``g``.""" \ No newline at end of file + :param value: New range for the accelerometer, an integer in ``g``. + """ diff --git a/lang/nl/typeshed/stdlib/microbit/audio.pyi b/lang/nl/typeshed/stdlib/microbit/audio.pyi index ee2c412..3b1e327 100644 --- a/lang/nl/typeshed/stdlib/microbit/audio.pyi +++ b/lang/nl/typeshed/stdlib/microbit/audio.pyi @@ -1,124 +1,160 @@ -"""Geluid afspelen met behulp van de micro:bit (importeer ``audio`` voor V1 compatibiliteit).""" +"""Play sounds using the micro:bit (import ``audio`` for V1 compatibility). +""" + from ..microbit import MicroBitDigitalPin, Sound, pin0 from typing import ClassVar, Iterable, Union -def play(source: Union[Iterable[AudioFrame], Sound, SoundEffect], wait: bool=True, pin: MicroBitDigitalPin=pin0, return_pin: Union[MicroBitDigitalPin, None]=None) -> None: - """Een ingebouwde geluid, geluids effect of aangepaste audio frames afspelen. (afspelen) +def play( + source: Union[Iterable[AudioFrame], Sound, SoundEffect], + wait: bool = True, + pin: MicroBitDigitalPin = pin0, + return_pin: Union[MicroBitDigitalPin, None] = None, +) -> None: + """Play a built-in sound, sound effect or custom audio frames. -Example: ``audio.play(Sound.GIGGLE)`` + Example: ``audio.play(Sound.GIGGLE)`` -:param source: (bron) Een ingebouwde ``Sound`` zoals ``Sound.GIGGLE``, een ``SoundEffect`` of voorbeeldgegevens als een iteratie van ``AudioFrame`` objecten. -:param wait: (wacht) Als ``wait`` ``True``is, wordt deze functie geblokkeerd totdat het geluid is voltooid. -:param pin: Een optioneel argument om de uitvoerpin op te geven kan worden gebruikt om de standaard van ``pin0``te overschrijven. Als we geen geluid willen afspelen, kunnen we ``pin=None`` gebruiken. -:param return_pin: (retourneer pin) Specificeert een differentiële rand connector pin om verbinding te maken met een externe luidspreker in plaats van de grond. Dit wordt genegeerd voor de **V2** herziening.""" + :param source: A built-in ``Sound`` such as ``Sound.GIGGLE``, a ``SoundEffect`` or sample data as an iterable of ``AudioFrame`` objects. + :param wait: If ``wait`` is ``True``, this function will block until the sound is complete. + :param pin: An optional argument to specify the output pin can be used to override the default of ``pin0``. If we do not want any sound to play we can use ``pin=None``. + :param return_pin: Specifies a differential edge connector pin to connect to an external speaker instead of ground. This is ignored for the **V2** revision. + """ def is_playing() -> bool: - """Controleer of een geluid wordt gespeeld. (speelt af) + """Check whether a sound is playing. -Example: ``audio.is_playing()`` + Example: ``audio.is_playing()`` -:return: ``True`` if audio is playing, otherwise ``False``.""" + :return: ``True`` if audio is playing, otherwise ``False``.""" ... def stop() -> None: - """Stop het afspelen van de audio. + """Stop all audio playback. -Example: ``audio.stop()``""" + Example: ``audio.stop()`` + """ ... class SoundEffect: - """Een geluidseffect, bestaande uit een set parameters geconfigureerd via de constructor of attributen.""" + """A sound effect, composed by a set of parameters configured via the constructor or attributes.""" + WAVEFORM_SINE: ClassVar[int] - """De sinusgolf optie gebruikt voor de ``waveform`` parameter. (golfvorm sinus)""" + """Sine wave option used for the ``waveform`` parameter.""" + WAVEFORM_SAWTOOTH: ClassVar[int] - """Zaag golf optie gebruikt voor de ``waveform`` parameter. (golfvorm zaagtand)""" + """Sawtooth wave option used for the ``waveform`` parameter.""" + WAVEFORM_TRIANGLE: ClassVar[int] - """De drie hoeks golf optie gebruikt voor de ``waveform`` parameter. (golfvorm driehoek)""" + """Triangle wave option used for the ``waveform`` parameter.""" + WAVEFORM_SQUARE: ClassVar[int] - """Blok golf optie die wordt gebruikt voor de parameter ``waveform``. (golfvorm vierkant)""" + """Square wave option used for the ``waveform`` parameter.""" + WAVEFORM_NOISE: ClassVar[int] - """Noise optie gebruikt voor de ``waveform`` parameter. (golfvormig geluid)""" + """Noise option used for the ``waveform`` parameter.""" + SHAPE_LINEAR: ClassVar[int] - """Lineaire interpolatie optie die wordt gebruikt voor de ``shape`` parameter. (vorm lineair)""" + """Linear interpolation option used for the ``shape`` parameter.""" + SHAPE_CURVE: ClassVar[int] - """Curve interpolatie optie gebruikt voor de ``shape`` parameter. (vorm curve)""" + """Curve interpolation option used for the ``shape`` parameter.""" + SHAPE_LOG: ClassVar[int] - """Logaritmische interpolatie optie gebruikt voor de ``shape`` parameter. (vorm log)""" + """Logarithmic interpolation option used for the ``shape`` parameter.""" + FX_NONE: ClassVar[int] - """Geen effectoptie gebruikt voor de ``fx`` parameter. (geen fx)""" + """No effect option used for the ``fx`` parameter.""" + FX_TREMOLO: ClassVar[int] - """Tremolo effect optie die wordt gebruikt voor de ``fx`` parameter.""" + """Tremolo effect option used for the ``fx`` parameter.""" + FX_VIBRATO: ClassVar[int] - """Vibrato effect optie die wordt gebruikt voor de ``fx`` parameter.""" + """Vibrato effect option used for the ``fx`` parameter.""" + FX_WARBLE: ClassVar[int] - """Warble effect optie die wordt gebruikt voor de ``fx`` parameter .""" + """Warble effect option used for the ``fx`` parameter.""" + freq_start: int - """Start frequentie in Hertz (Hz), een getal tussen ``0`` en ``9999`` (frequentie start)""" + """Start frequency in Hertz (Hz), a number between ``0`` and ``9999``""" + freq_end: int - """Eind frequentie in Hertz (Hz), een getal tussen ``0`` en ``9999`` (frequentie einde)""" + """End frequency in Hertz (Hz), a number between ``0`` and ``9999``""" + duration: int - """Duur van het geluid in milliseconden, een getal tussen ``0`` en ``9999`` (Duur)""" - vol_start: int - """Start volume waarde, een getal tussen ``0`` en ``255``""" - vol_end: int - """Eind volume waarde, een getal tussen ``0`` en ``255`` (vol einde)""" - waveform: int - """Type van golfvorm, één van deze waarden: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (willekeurig gegenereerde lawaai) (golfvorm)""" - fx: int - """Effect om aan het geluid toe te voegen, een van de volgende waarden: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``of ``FX_NONE``""" - shape: int - """Het type van de interpolatie curve tussen de begin- en eind frequenties, verschillende golfvormen hebben verschillende snelheid bij het wijzigen van de frequentie. Een van de volgende waarden: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG`` (vorm)""" + """Duration of the sound in milliseconds, a number between ``0`` and ``9999``""" - def __init__(self, freq_start: int=500, freq_end: int=2500, duration: int=500, vol_start: int=255, vol_end: int=0, waveform: int=WAVEFORM_SQUARE, fx: int=FX_NONE, shape: int=SHAPE_LOG): - """Maak een nieuw geluidseffect. (initialiseren) + vol_start: int + """Start volume value, a number between ``0`` and ``255``""" -Example: ``my_effect = SoundEffect(duration=1000)`` + vol_end: int + """End volume value, a number between ``0`` and ``255``""" -All the parameters are optional, with default values as shown above, and -they can all be modified via attributes of the same name. For example, we -can first create an effect ``my_effect = SoundEffect(duration=1000)``, -and then change its attributes ``my_effect.duration = 500``. + waveform: int + """Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise)""" -:param freq_start: (frequentie start) Start frequentie in Hertz (Hz), een getal tussen ``0`` en ``9999``. -:param freq_end: (frequentie einde) Eind frequentie in Hertz (Hz), een getal tussen ``0`` en ``9999``. -:param duration: (duur) Duur van het geluid in milliseconden, een getal tussen ``0`` en ``9999``. -:param vol_start: Startvolumewaarde, een getal tussen ``0`` en ``255``. -:param vol_end: (vol einde) Eindvolumewaarde, een getal tussen ``0`` en ``255``. -:param waveform: (golfvorm) Type golfvorm, één van deze waarden: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (willekeurig gegenereerde geluid). -:param fx: Effect om het geluid toe te voegen, een van de volgende waarden: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``of ``FX_NONE``. -:param shape: (vorm) Het type van de interpolatie curve tussen de begin- en eind frequenties, verschillende golfvormen hebben verschillende snelheid bij het wijzigen van de frequentie. Een van de volgende waarden: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``.""" + fx: int + """Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``""" + shape: int + """The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``""" + + def __init__( + self, + freq_start: int = 500, + freq_end: int = 2500, + duration: int = 500, + vol_start: int = 255, + vol_end: int = 0, + waveform: int = WAVEFORM_SQUARE, + fx: int = FX_NONE, + shape: int = SHAPE_LOG, + ): + """Create a new sound effect. + + Example: ``my_effect = SoundEffect(duration=1000)`` + + All the parameters are optional, with default values as shown above, and + they can all be modified via attributes of the same name. For example, we + can first create an effect ``my_effect = SoundEffect(duration=1000)``, + and then change its attributes ``my_effect.duration = 500``. + + :param freq_start: Start frequency in Hertz (Hz), a number between ``0`` and ``9999``. + :param freq_end: End frequency in Hertz (Hz), a number between ``0`` and ``9999``. + :param duration: Duration of the sound in milliseconds, a number between ``0`` and ``9999``. + :param vol_start: Start volume value, a number between ``0`` and ``255``. + :param vol_end: End volume value, a number between ``0`` and ``255``. + :param waveform: Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise). + :param fx: Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``. + :param shape: The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``. + """ def copy(self) -> SoundEffect: - """Maak een kopie van dit ``SoundEffect``. (kopiëer) + """Create a copy of this ``SoundEffect``. -Example: ``sound_2 = sound_1.copy()`` + Example: ``sound_2 = sound_1.copy()`` -:return: A copy of the SoundEffect.""" + :return: A copy of the SoundEffect. + """ class AudioFrame: - """Een ``AudioFrame`` object is een lijst van 32 samples elk een niet-ondertekende byte -(geheel getal tussen 0 en 255). + """An ``AudioFrame`` object is a list of 32 samples each of which is a unsigned byte + (whole number between 0 and 255). -It takes just over 4 ms to play a single frame. + It takes just over 4 ms to play a single frame. -Example:: + Example:: - frame = AudioFrame() - for i in range(len(frame)): - frame[i] = 252 - i * 8""" + frame = AudioFrame() + for i in range(len(frame)): + frame[i] = 252 - i * 8 + """ def copyfrom(self, other: AudioFrame) -> None: - """Overschrijf de gegevens in deze ``AudioFrame`` met de gegevens van een andere ``AudioFrame`` instantie. (kopieer van) - -Example: ``my_frame.copyfrom(source_frame)`` - -:param other: (overige) ``AudioFrame`` exemplaar van waar de gegevens worden gekopieerd.""" - - def __len__(self) -> int: - ... + """Overwrite the data in this ``AudioFrame`` with the data from another ``AudioFrame`` instance. - def __setitem__(self, key: int, value: int) -> None: - ... + Example: ``my_frame.copyfrom(source_frame)`` - def __getitem__(self, key: int) -> int: - ... \ No newline at end of file + :param other: ``AudioFrame`` instance from which to copy the data. + """ + def __len__(self) -> int: ... + def __setitem__(self, key: int, value: int) -> None: ... + def __getitem__(self, key: int) -> int: ... diff --git a/lang/nl/typeshed/stdlib/microbit/compass.pyi b/lang/nl/typeshed/stdlib/microbit/compass.pyi index 06c6d48..c74a47b 100644 --- a/lang/nl/typeshed/stdlib/microbit/compass.pyi +++ b/lang/nl/typeshed/stdlib/microbit/compass.pyi @@ -1,70 +1,78 @@ -"""Gebruik het ingebouwde kompas. (kompas)""" +"""Use the built-in compass. +""" def calibrate() -> None: - """Start het kalibratieproces. (Kalibreren) + """Starts the calibration process. -Example: ``compass.calibrate()`` + Example: ``compass.calibrate()`` -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.""" + 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: - """Controleer of het kompas is gekalibreerd. (gekalibreerd) + """Check is the compass is calibrated. -Example: ``compass.is_calibrated()`` + Example: ``compass.is_calibrated()`` -:return: ``True`` if the compass has been successfully calibrated, ``False`` otherwise.""" + :return: ``True`` if the compass has been successfully calibrated, ``False`` otherwise. + """ ... def clear_calibration() -> None: - """Kalibratie ongedaan maken, waardoor het kompas weer losgemaakt wordt. (kalibratie wissen) + """Undoes the calibration, making the compass uncalibrated again. -Example: ``compass.clear_calibration()``""" + Example: ``compass.clear_calibration()`` + """ ... def get_x() -> int: - """Krijg de magnetische veldsterkte op de ``x`` as. (krijg x) + """Get the magnetic field strength on the ``x`` axis. -Example: ``compass.get_x()`` + Example: ``compass.get_x()`` -Call ``calibrate`` first or the results will be inaccurate. + Call ``calibrate`` first or the results will be inaccurate. -:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" + :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. + """ ... def get_y() -> int: - """Krijg de magnetische veldsterkte op de ``y`` as. (krijg y) + """Get the magnetic field strength on the ``y`` axis. -Example: ``compass.get_y()`` + Example: ``compass.get_y()`` -Call ``calibrate`` first or the results will be inaccurate. + Call ``calibrate`` first or the results will be inaccurate. -:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" + :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. + """ ... def get_z() -> int: - """Krijg de magnetische veldsterkte op de ``z`` as. (krijg z) + """Get the magnetic field strength on the ``z`` axis. -Example: ``compass.get_z()`` + Example: ``compass.get_z()`` -Call ``calibrate`` first or the results will be inaccurate. + Call ``calibrate`` first or the results will be inaccurate. -:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" + :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. + """ ... def heading() -> int: - """Haal de kompaskop op. (kop) + """Get the compass heading. -Example: ``compass.heading()`` + Example: ``compass.heading()`` -:return: An integer in the range from 0 to 360, representing the angle in degrees, clockwise, with north as 0.""" + :return: An integer in the range from 0 to 360, representing the angle in degrees, clockwise, with north as 0. + """ ... def get_field_strength() -> int: - """Krijg de magnitude van het magnetische veld rond het apparaat. (krijg veldsterkte) + """Get the magnitude of the magnetic field around the device. -Example: ``compass.get_field_strength()`` + Example: ``compass.get_field_strength()`` -:return: An integer indication of the magnitude of the magnetic field in nano tesla.""" - ... \ No newline at end of file + :return: An integer indication of the magnitude of the magnetic field in nano tesla.""" + ... diff --git a/lang/nl/typeshed/stdlib/microbit/display.pyi b/lang/nl/typeshed/stdlib/microbit/display.pyi index 0447e07..aa4013e 100644 --- a/lang/nl/typeshed/stdlib/microbit/display.pyi +++ b/lang/nl/typeshed/stdlib/microbit/display.pyi @@ -1,92 +1,115 @@ -"""Tekst, afbeeldingen en animaties weergeven op het 5×5 LED-weergave.""" +"""Show text, images and animations on the 5×5 LED display. +""" + from ..microbit import Image from typing import Union, overload, Iterable def get_pixel(x: int, y: int) -> int: - """Krijg de helderheid van de LED in kolom ``x`` en rij ``y``. (verkrijg pixel) + """Get the brightness of the LED at column ``x`` and row ``y``. -Example: ``display.get_pixel(0, 0)`` + Example: ``display.get_pixel(0, 0)`` -:param x: (х) De weergavekolom (0..4) -:param y: De weergave rij (0.4) -:return: A number between 0 (off) and 9 (bright)""" + :param x: The display column (0..4) + :param y: The display row (0..4) + :return: A number between 0 (off) and 9 (bright) + """ ... def set_pixel(x: int, y: int, value: int) -> None: - """Stel de helderheid van de LED in op kolom ``x`` en rij ``y``. (pixel instellen) + """Set the brightness of the LED at column ``x`` and row ``y``. -Example: ``display.set_pixel(0, 0, 9)`` + Example: ``display.set_pixel(0, 0, 9)`` -:param x: (х) De weergavekolom (0..4) -:param y: De weergave rij (0.4) -:param value: (waarde) De helderheid tussen 0 (uit) en 9 (helderst)""" + :param x: The display column (0..4) + :param y: The display row (0..4) + :param value: The brightness between 0 (off) and 9 (bright) + """ ... def clear() -> None: - """Stel de helderheid van alle LED's in op 0 (uit). (wissen) + """Set the brightness of all LEDs to 0 (off). -Example: ``display.clear()``""" + Example: ``display.clear()`` + """ ... -def show(image: Union[str, float, int, Image, Iterable[Image]], delay: int=400, wait: bool=True, loop: bool=False, clear: bool=False) -> None: - """Toont afbeeldingen, letters of cijfers op het LED-scherm. (toon) +def show( + image: Union[str, float, int, Image, Iterable[Image]], + delay: int = 400, + wait: bool = True, + loop: bool = False, + clear: bool = False, +) -> None: + """Shows images, letters or digits on the LED display. -Example: ``display.show(Image.HEART)`` + Example: ``display.show(Image.HEART)`` -When ``image`` is an image or a list of images then each image is displayed in turn. -If ``image`` is a string or number, each letter or digit is displayed in turn. + When ``image`` is an image or a list of images then each image is displayed in turn. + If ``image`` is a string or number, each letter or digit is displayed in turn. -:param image: (afbeelding) Een string, nummer, afbeelding of lijst van weer te geven afbeeldingen. -:param delay: (vertraging) Elke letter, cijfer of afbeelding wordt weergegeven met ``delay`` milliseconden tussen hen. -:param wait: (wacht) Als ``wait`` ``True``is, blokkeert deze functie totdat de animatie is voltooid, anders gebeurt de animatie op de achtergrond. -:param loop: Als ``loop`` ``True``is, zal de animatie voor altijd herhalen. -:param clear: (wissen) Als ``clear`` ``True``is, wordt het scherm gewist nadat de reeks is voltooid. + :param image: A string, number, image or list of images to show. + :param delay: Each letter, digit or image is shown with ``delay`` milliseconds between them. + :param wait: If ``wait`` is ``True``, this function will block until the animation is finished, otherwise the animation will happen in the background. + :param loop: If ``loop`` is ``True``, the animation will repeat forever. + :param clear: If ``clear`` is ``True``, the display will be cleared after the sequence has finished. -The ``wait``, ``loop`` and ``clear`` arguments must be specified using their keyword.""" + The ``wait``, ``loop`` and ``clear`` arguments must be specified using their keyword. + """ ... -def scroll(text: Union[str, float, int], delay: int=150, wait: bool=True, loop: bool=False, monospace: bool=False) -> None: - """Scrolt een nummer of tekst op het LED display (scrollen) - -Example: ``display.scroll('micro:bit')`` - -:param text: (tekst) De tekenreeks om te scrollen. Als ``text`` een geheel getal of float is, wordt het eerst geconverteerd naar een tekenreeks met behulp van ``str()``. -:param delay: (vertraging) De parameter ``delay`` bepaalt hoe snel de tekst scrolt. -:param wait: (wacht) Als ``wait`` ``True``is, blokkeert deze functie totdat de animatie is voltooid, anders gebeurt de animatie op de achtergrond. -:param loop: Als ``loop`` ``True``is, zal de animatie voor altijd herhalen. -:param monospace: Als ``monospace`` ``True`` is, nemen de tekens allemaal 5 pixel kolommen in de breedte in beslag, anders staat er precies 1 lege pixelkolom tussen elk teken terwijl ze scrollen. - -The ``wait``, ``loop`` and ``monospace`` arguments must be specified -using their keyword.""" +def scroll( + text: Union[str, float, int], + delay: int = 150, + wait: bool = True, + loop: bool = False, + monospace: bool = False, +) -> None: + """Scrolls a number or text on the LED display. + + Example: ``display.scroll('micro:bit')`` + + :param text: The string to scroll. If ``text`` is an integer or float it is first converted to a string using ``str()``. + :param delay: The ``delay`` parameter controls how fast the text is scrolling. + :param wait: If ``wait`` is ``True``, this function will block until the animation is finished, otherwise the animation will happen in the background. + :param loop: If ``loop`` is ``True``, the animation will repeat forever. + :param monospace: 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. + + The ``wait``, ``loop`` and ``monospace`` arguments must be specified + using their keyword. + """ ... def on() -> None: - """Schakel het LED display in. (aan) + """Turn on the LED display. -Example: ``display.on()``""" + Example: ``display.on()`` + """ ... def off() -> None: - """Het uitschakelen van het LED display (uitschakelen van het scherm geeft je de mogelijkheid om de GPIO-pinnen opnieuw te gebruiken voor andere doeleinden). (uit) + """Turn off the LED display (disabling the display allows you to re-use the GPIO pins for other purposes). -Example: ``display.off()``""" + Example: ``display.off()`` + """ ... def is_on() -> bool: - """Controleer of de LED-weergave is ingeschakeld. (staat aan) + """Check whether the LED display is enabled. -Example: ``display.is_on()`` + Example: ``display.is_on()`` -:return: ``True`` if the display is on, otherwise returns ``False``.""" + :return: ``True`` if the display is on, otherwise returns ``False``. + """ ... def read_light_level() -> int: - """Lees het licht niveau. (lees licht niveau) + """Read the light level. -Example: ``display.read_light_level()`` + Example: ``display.read_light_level()`` -Uses the display's LEDs in reverse-bias mode to sense the amount of light -falling on the display. + Uses the display's LEDs in reverse-bias mode to sense the amount of light + falling on the display. -:return: An integer between 0 and 255 representing the light level, with larger meaning more light.""" - ... \ No newline at end of file + :return: An integer between 0 and 255 representing the light level, with larger meaning more light. + """ + ... diff --git a/lang/nl/typeshed/stdlib/microbit/i2c.pyi b/lang/nl/typeshed/stdlib/microbit/i2c.pyi index b3654a5..df26efa 100644 --- a/lang/nl/typeshed/stdlib/microbit/i2c.pyi +++ b/lang/nl/typeshed/stdlib/microbit/i2c.pyi @@ -1,49 +1,57 @@ -"""Communiceer met apparaten met behulp van het I²C bus protocol.""" +"""Communicate with devices using the I²C bus protocol. +""" + from _typeshed import ReadableBuffer from ..microbit import MicroBitDigitalPin, pin19, pin20 from typing import List -def init(freq: int=100000, sda: MicroBitDigitalPin=pin20, scl: MicroBitDigitalPin=pin19) -> None: - """Initialiseer een randapparaat opnieuw. (initialiseren) +def init( + freq: int = 100000, sda: MicroBitDigitalPin = pin20, scl: MicroBitDigitalPin = pin19 +) -> None: + """Re-initialize a peripheral. -Example: ``i2c.init()`` + Example: ``i2c.init()`` -:param freq: (frequentie) klok frequentie -:param sda: ``sda`` pin (standaard 20) -:param scl: ``scl`` pin (standaard 19) + :param freq: clock frequency + :param sda: ``sda`` pin (default 20) + :param scl: ``scl`` pin (default 19) -On a micro:bit V1 board, changing the I²C pins from defaults will make -the accelerometer and compass stop working, as they are connected -internally to those pins. This warning does not apply to the **V2** -revision of the micro:bit as this has `separate I²C lines `_ -for the motion sensors and the edge connector.""" + On a micro:bit V1 board, changing the I²C pins from defaults will make + the accelerometer and compass stop working, as they are connected + internally to those pins. This warning does not apply to the **V2** + revision of the micro:bit as this has `separate I²C lines `_ + for the motion sensors and the edge connector. + """ ... def scan() -> List[int]: - """Scan de bus op apparaten. (scannen) + """Scan the bus for devices. -Example: ``i2c.scan()`` + Example: ``i2c.scan()`` -:return: A list of 7-bit addresses corresponding to those devices that responded to the scan.""" + :return: A list of 7-bit addresses corresponding to those devices that responded to the scan. + """ ... -def read(addr: int, n: int, repeat: bool=False) -> bytes: - """Lees bytes van een apparaat. (lezen) +def read(addr: int, n: int, repeat: bool = False) -> bytes: + """Read bytes from a device. -Example: ``i2c.read(0x50, 64)`` + Example: ``i2c.read(0x50, 64)`` -:param addr: Het 7-bit adres van het apparaat -:param n: Het aantal te lezen bytes -:param repeat: (herhaal) Als ``True``, zal er geen stop bit worden verzonden -:return: The bytes read""" + :param addr: The 7-bit address of the device + :param n: The number of bytes to read + :param repeat: If ``True``, no stop bit will be sent + :return: The bytes read + """ ... -def write(addr: int, buf: ReadableBuffer, repeat: bool=False) -> None: - """Schrijven van bytes naar een apparaat. (schrijven) +def write(addr: int, buf: ReadableBuffer, repeat: bool = False) -> None: + """Write bytes to a device. -Example: ``i2c.write(0x50, bytes([1, 2, 3]))`` + Example: ``i2c.write(0x50, bytes([1, 2, 3]))`` -:param addr: Het 7-bit adres van het apparaat -:param buf: Een buffer met de te schrijven bytes -:param repeat: (herhaal) Als ``True``, zal er geen stop bit worden verzonden""" - ... \ No newline at end of file + :param addr: The 7-bit address of the device + :param buf: A buffer containing the bytes to write + :param repeat: If ``True``, no stop bit will be sent + """ + ... diff --git a/lang/nl/typeshed/stdlib/microbit/microphone.pyi b/lang/nl/typeshed/stdlib/microbit/microphone.pyi index df484aa..68e8f3a 100644 --- a/lang/nl/typeshed/stdlib/microbit/microphone.pyi +++ b/lang/nl/typeshed/stdlib/microbit/microphone.pyi @@ -1,62 +1,70 @@ -"""Reageer op geluid met de ingebouwde microfoon (V2 alleen). (microfoon)""" +"""Respond to sound using the built-in microphone (V2 only). +""" + from typing import Optional, Tuple from ..microbit import SoundEvent def current_event() -> Optional[SoundEvent]: - """Krijg de laatst opgenomen geluidsgebeurtenis (huidige gebeurtenis) + """Get the last recorded sound event -Example: ``microphone.current_event()`` + Example: ``microphone.current_event()`` -:return: The event, ``SoundEvent('loud')`` or ``SoundEvent('quiet')``.""" + :return: The event, ``SoundEvent('loud')`` or ``SoundEvent('quiet')``. + """ ... def was_event(event: SoundEvent) -> bool: - """Controleer of een geluid tenminste één keer is gehoord sinds het laatste gesprek. + """Check if a sound was heard at least once since the last call. -Example: ``microphone.was_event(SoundEvent.LOUD)`` + Example: ``microphone.was_event(SoundEvent.LOUD)`` -This call clears the sound history before returning. + This call clears the sound history before returning. -:param event: (gebeurtenis) Het te controleren evenement, zoals ``SoundEvent.LOUD`` of ``SoundEvent.QUIET`` -:return: ``True`` if sound was heard at least once since the last call, otherwise ``False``.""" + :param event: The event to check for, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET`` + :return: ``True`` if sound was heard at least once since the last call, otherwise ``False``. + """ ... def is_event(event: SoundEvent) -> bool: - """Controleer de meest recente geluidsgebeurtenis gedetecteerd. + """Check the most recent sound event detected. -Example: ``microphone.is_event(SoundEvent.LOUD)`` + Example: ``microphone.is_event(SoundEvent.LOUD)`` -This call does not clear the sound event history. + This call does not clear the sound event history. -:param event: (gebeurtenis) Het te controleren evenement, zoals ``SoundEvent.LOUD`` of ``SoundEvent.QUIET`` -:return: ``True`` if sound was the most recent heard, ``False`` otherwise.""" + :param event: The event to check for, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET`` + :return: ``True`` if sound was the most recent heard, ``False`` otherwise. + """ ... def get_events() -> Tuple[SoundEvent, ...]: - """Krijg de geluidsgeschiedenis als tuple. + """Get the sound event history as a tuple. -Example: ``microphone.get_events()`` + Example: ``microphone.get_events()`` -This call clears the sound history before returning. + This call clears the sound history before returning. -:return: A tuple of the event history with the most recent event last.""" + :return: A tuple of the event history with the most recent event last. + """ ... def set_threshold(event: SoundEvent, value: int) -> None: - """Stel de drempel in voor een geluidsgebeurtenis. (stel drempelwaarde in) + """Set the threshold for a sound event. -Example: ``microphone.set_threshold(SoundEvent.LOUD, 250)`` + Example: ``microphone.set_threshold(SoundEvent.LOUD, 250)`` -A high threshold means the event will only trigger if the sound is very loud (>= 250 in the example). + A high threshold means the event will only trigger if the sound is very loud (>= 250 in the example). -:param event: (gebeurtenis) Een geluidsgebeurtenis, zoals ``SoundEvent.LOUD`` of ``SoundEvent.QUIET``. -:param value: (waarde) Het drempelniveau in het bereik 0-255.""" + :param event: A sound event, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET``. + :param value: The threshold level in the range 0-255. + """ ... def sound_level() -> int: - """Krijg het Geluidsdrukniveau. (geluidsniveau) + """Get the sound pressure level. -Example: ``microphone.sound_level()`` + Example: ``microphone.sound_level()`` -:return: A representation of the sound pressure level in the range 0 to 255.""" - ... \ No newline at end of file + :return: A representation of the sound pressure level in the range 0 to 255. + """ + ... diff --git a/lang/nl/typeshed/stdlib/microbit/speaker.pyi b/lang/nl/typeshed/stdlib/microbit/speaker.pyi index a1c9cee..5a74a4d 100644 --- a/lang/nl/typeshed/stdlib/microbit/speaker.pyi +++ b/lang/nl/typeshed/stdlib/microbit/speaker.pyi @@ -1,15 +1,18 @@ -"""Beheer de ingebouwde luidspreker (alleen V2). (luidspreker)""" +"""Control the built-in speaker (V2 only). +""" def off() -> None: - """Luidspreker uitschakelen. (uit) + """Turn the speaker off. -Example: ``speaker.off()`` + Example: ``speaker.off()`` -This does not disable sound output to an edge connector pin.""" + This does not disable sound output to an edge connector pin. + """ ... def on() -> None: - """Luidspreker inschakelen (aan) + """Turn the speaker on. -Example: ``speaker.on()``""" - ... \ No newline at end of file + Example: ``speaker.on()`` + """ + ... diff --git a/lang/nl/typeshed/stdlib/microbit/spi.pyi b/lang/nl/typeshed/stdlib/microbit/spi.pyi index 064ddbf..09c4046 100644 --- a/lang/nl/typeshed/stdlib/microbit/spi.pyi +++ b/lang/nl/typeshed/stdlib/microbit/spi.pyi @@ -1,47 +1,60 @@ -"""Communiceer met apparaten met behulp van de seriële perifere interface (SPI) bus.""" +"""Communicate with devices using the serial peripheral interface (SPI) bus. +""" + from _typeshed import ReadableBuffer, WriteableBuffer from ..microbit import pin13, pin14, pin15, MicroBitDigitalPin -def init(baudrate: int=1000000, bits: int=8, mode: int=0, sclk: MicroBitDigitalPin=pin13, mosi: MicroBitDigitalPin=pin15, miso: MicroBitDigitalPin=pin14) -> None: - """Initialiseer SPI communicatie. (initialiseren) - -Example: ``spi.init()`` - -For correct communication, the parameters have to be the same on both communicating devices. - -:param baudrate: De snelheid van de communicatie. -:param bits: De breedte in bits van elke overdracht. Momenteel wordt alleen ``bits=8`` ondersteund. Dit kan echter veranderen in de toekomst. -:param mode: (modus) Bepaalt de combinatie van klokpolariteit en fase - `zie online tabel `_. -:param sclk: sclk pin (standaard 13) -:param mosi: mosi pin (standaard 15) -:param miso: miso pin (standaard 14)""" +def init( + baudrate: int = 1000000, + bits: int = 8, + mode: int = 0, + sclk: MicroBitDigitalPin = pin13, + mosi: MicroBitDigitalPin = pin15, + miso: MicroBitDigitalPin = pin14, +) -> None: + """Initialize SPI communication. + + Example: ``spi.init()`` + + For correct communication, the parameters have to be the same on both communicating devices. + + :param baudrate: The speed of communication. + :param bits: The width in bits of each transfer. Currently only ``bits=8`` is supported. However, this may change in the future. + :param mode: Determines the combination of clock polarity and phase - `see online table `_. + :param sclk: sclk pin (default 13) + :param mosi: mosi pin (default 15) + :param miso: miso pin (default 14) + """ ... -def read(nbytes: int, out: int=0) -> bytes: - """Lees bytes. (lezen) +def read(nbytes: int, out: int = 0) -> bytes: + """Read at most ``nbytes`` while continuously writing the single byte given by ``out``. -Example: ``spi.read(64)`` + Example: ``spi.read(64)`` -:param nbytes: Maximum aantal te lezen bytes. -:param out: (uit) The byte value to write (default 0). -:return: The bytes read.""" + :param nbytes: Maximum number of bytes to read. + :param out: The byte value to write (default 0). + :return: The bytes read. + """ ... def write(buffer: ReadableBuffer) -> None: - """Schrijf bytes naar de bus. (schrijven) + """Write bytes to the bus. -Example: ``spi.write(bytes([1, 2, 3]))`` + Example: ``spi.write(bytes([1, 2, 3]))`` -:param buffer: Een buffer om gegevens van te lezen.""" + :param buffer: A buffer to read data from. + """ ... def write_readinto(out: WriteableBuffer, in_: ReadableBuffer) -> None: - """Schrijf de ``out`` buffer naar de bus en lees elke reactie in de ``in_`` buffer. (schrijf readinto) + """Write the ``out`` buffer to the bus and read any response into the ``in_`` buffer. -Example: ``spi.write_readinto(out_buffer, in_buffer)`` + Example: ``spi.write_readinto(out_buffer, in_buffer)`` -The length of the buffers should be the same. The buffers can be the same object. + The length of the buffers should be the same. The buffers can be the same object. -:param out: (uit) De buffer om een reactie naar te schrijven. -:param in_: De buffer om gegevens van te lezen.""" - ... \ No newline at end of file + :param out: The buffer to write any response to. + :param in_: The buffer to read data from. + """ + ... diff --git a/lang/nl/typeshed/stdlib/microbit/uart.pyi b/lang/nl/typeshed/stdlib/microbit/uart.pyi index 0f4f26d..2ab650f 100644 --- a/lang/nl/typeshed/stdlib/microbit/uart.pyi +++ b/lang/nl/typeshed/stdlib/microbit/uart.pyi @@ -1,79 +1,96 @@ -"""Communiceer met een apparaat via een seriële interface.""" +"""Communicate with a device using a serial interface. +""" + from _typeshed import WriteableBuffer from ..microbit import MicroBitDigitalPin from typing import Optional, Union -ODD: int -"""Oneven pariteit (oneven)""" -EVEN: int -"""Even pariteit""" - -def init(baudrate: int=9600, bits: int=8, parity: Optional[int]=None, stop: int=1, tx: Optional[MicroBitDigitalPin]=None, rx: Optional[MicroBitDigitalPin]=None) -> None: - """Initialiseer seriële communicatie. (initialiseren) - -Example: ``uart.init(115200, tx=pin0, rx=pin1)`` -:param baudrate: De snelheid van de communicatie. -:param bits: De grootte van de bytes die worden verzonden. micro:bit ondersteunt slechts 8. -:param parity: (pariteit) Hoe de pariteit is aangevinkt, ``None``, ``uart.ODD`` of ``uart.EVEN``. -:param stop: Het aantal stop bits, moet 1 zijn voor micro:bit. -:param tx: Verzend pin. -:param rx: Ontvangende pin. - -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. +ODD: int +"""Odd parity""" -For more details see `the online documentation `_.""" +EVEN: int +"""Even parity""" + +def init( + baudrate: int = 9600, + bits: int = 8, + parity: Optional[int] = None, + stop: int = 1, + tx: Optional[MicroBitDigitalPin] = None, + rx: Optional[MicroBitDigitalPin] = None, +) -> None: + """Initialize serial communication. + + Example: ``uart.init(115200, tx=pin0, rx=pin1)`` + + :param baudrate: The speed of communication. + :param bits: The size of bytes being transmitted. micro:bit only supports 8. + :param parity: How parity is checked, ``None``, ``uart.ODD`` or ``uart.EVEN``. + :param stop: The number of stop bits, has to be 1 for micro:bit. + :param tx: Transmitting pin. + :param rx: Receiving pin. + + 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. + + For more details see `the online documentation `_. + """ ... def any() -> bool: - """Controleer of er nog gegevens staan te wachten. (elke) + """Check if any data is waiting. -Example: ``uart.any()`` + Example: ``uart.any()`` -:return: ``True`` if any data is waiting, else ``False``.""" + :return: ``True`` if any data is waiting, else ``False``. + """ ... -def read(nbytes: Optional[int]=None) -> Optional[bytes]: - """Lees bytes. (lezen) +def read(nbytes: Optional[int] = None) -> Optional[bytes]: + """Read bytes. -Example: ``uart.read()`` + Example: ``uart.read()`` -:param nbytes: Als ``nbytes`` is gespecificeerd, lees dan maximaal zoveel bytes, anders lees zo veel mogelijk bytes -:return: A bytes object or ``None`` on timeout""" + :param nbytes: If ``nbytes`` is specified then read at most that many bytes, otherwise read as many bytes as possible + :return: A bytes object or ``None`` on timeout + """ ... -def readinto(buf: WriteableBuffer, nbytes: Optional[int]=None) -> Optional[int]: - """Lees bytes in de ``buf``. (inlezen) +def readinto(buf: WriteableBuffer, nbytes: Optional[int] = None) -> Optional[int]: + """Read bytes into the ``buf``. -Example: ``uart.readinto(input_buffer)`` + Example: ``uart.readinto(input_buffer)`` -:param buf: De buffer om naar te schrijven. -:param nbytes: Als ``nbytes`` is gespecificeerd, lees dan hooguit zoveel bytes, anders lees ``len(buf)`` bytes. -:return: number of bytes read and stored into ``buf`` or ``None`` on timeout.""" + :param buf: The buffer to write to. + :param nbytes: If ``nbytes`` is specified then read at most that many bytes, otherwise read ``len(buf)`` bytes. + :return: number of bytes read and stored into ``buf`` or ``None`` on timeout. + """ ... def readline() -> Optional[bytes]: - """Lees een regel, eindigend in een nieuw karakter regel. (leesregel) + """Read a line, ending in a newline character. -Example: ``uart.readline()`` + Example: ``uart.readline()`` -:return: The line read or ``None`` on timeout. The newline character is included in the returned bytes.""" + :return: The line read or ``None`` on timeout. The newline character is included in the returned bytes. + """ ... def write(buf: Union[bytes, str]) -> Optional[int]: - """Schrijf bytes naar de bus. (schrijven) + """Write a buffer to the bus. -Example: ``uart.write('hello world')`` + Example: ``uart.write('hello world')`` -:param buf: Een bytes object of een tekenreeks. -:return: The number of bytes written, or ``None`` on timeout. + :param buf: A bytes object or a string. + :return: The number of bytes written, or ``None`` on timeout. -Examples:: + Examples:: - uart.write('hello world') - uart.write(b'hello world') - uart.write(bytes([1, 2, 3]))""" - ... \ No newline at end of file + uart.write('hello world') + uart.write(b'hello world') + uart.write(bytes([1, 2, 3])) + """ + ... diff --git a/lang/nl/typeshed/stdlib/micropython.pyi b/lang/nl/typeshed/stdlib/micropython.pyi index 7dda37b..7a6079f 100644 --- a/lang/nl/typeshed/stdlib/micropython.pyi +++ b/lang/nl/typeshed/stdlib/micropython.pyi @@ -1,132 +1,144 @@ -"""MicroPython intern.""" +"""MicroPython internals.""" + from typing import Any, TypeVar, overload -_T = TypeVar('_T') + +_T = TypeVar("_T") def const(expr: _T) -> _T: - """Gebruikt om te verklaren dat de expressie een constante is zodat de compiler -deze kan optimaliseren. + """Used to declare that the expression is a constant so that the compiler can + optimise it. -The use of this function should be as follows:: + The use of this function should be as follows:: - from micropython import const - CONST_X = const(123) - CONST_Y = const(2 * CONST_X + 1) + from micropython import const + CONST_X = const(123) + CONST_Y = const(2 * CONST_X + 1) -Constants declared this way are still accessible as global variables from -outside the module they are declared in. On the other hand, if a constant -begins with an underscore then it is hidden, it is not available as a -global variable, and does not take up any memory during execution. + Constants declared this way are still accessible as global variables from + outside the module they are declared in. On the other hand, if a constant + begins with an underscore then it is hidden, it is not available as a + global variable, and does not take up any memory during execution. -:param expr: Een constante expressie.""" + :param expr: A constant expression. + """ ... @overload def opt_level() -> int: - """Krijg het huidige optimalisatieniveau voor de compilatie van scripts. (Kies niveau) + """Get the current optimisation level for the compilation of scripts. -Example: ``micropython.opt_level()`` + Example: ``micropython.opt_level()`` -The optimisation level controls the following compilation features: + The optimisation level controls the following compilation features: -- Assertions: at level 0 assertion statements are enabled and compiled - into the bytecode; at levels 1 and higher assertions are not compiled. + - Assertions: at level 0 assertion statements are enabled and compiled + into the bytecode; at levels 1 and higher assertions are not compiled. -- Built-in ``__debug__`` variable: at level 0 this variable expands to - True; at levels 1 and higher it expands to False. + - Built-in ``__debug__`` variable: at level 0 this variable expands to + True; at levels 1 and higher it expands to False. -- Source-code line numbers: at levels 0, 1 and 2 source-code line number - are stored along with the bytecode so that exceptions can report the - line number they occurred at; at levels 3 and higher line numbers are - not stored. + - Source-code line numbers: at levels 0, 1 and 2 source-code line number + are stored along with the bytecode so that exceptions can report the + line number they occurred at; at levels 3 and higher line numbers are + not stored. -:return: An integer representing the current level.""" + :return: An integer representing the current level. + """ ... @overload def opt_level(level: int) -> None: - """Stelt het optimalisatie niveau in voor de latere compilatie van scripts. (opt niveau) + """Sets the optimisation level for subsequent compilation of scripts. -Example: ``micropython.opt_level(1)`` + Example: ``micropython.opt_level(1)`` -The optimisation level controls the following compilation features: + The optimisation level controls the following compilation features: -- Assertions: at level 0 assertion statements are enabled and compiled - into the bytecode; at levels 1 and higher assertions are not compiled. + - Assertions: at level 0 assertion statements are enabled and compiled + into the bytecode; at levels 1 and higher assertions are not compiled. -- Built-in ``__debug__`` variable: at level 0 this variable expands to - True; at levels 1 and higher it expands to False. + - Built-in ``__debug__`` variable: at level 0 this variable expands to + True; at levels 1 and higher it expands to False. -- Source-code line numbers: at levels 0, 1 and 2 source-code line number - are stored along with the bytecode so that exceptions can report the - line number they occurred at; at levels 3 and higher line numbers are - not stored. + - Source-code line numbers: at levels 0, 1 and 2 source-code line number + are stored along with the bytecode so that exceptions can report the + line number they occurred at; at levels 3 and higher line numbers are + not stored. -The default optimisation level is usually level 0. + The default optimisation level is usually level 0. -:param level: (niveau) Een integer optimaliserings niveau.""" + :param level: An integer optimisation level. + """ ... -def mem_info(verbose: Any=None) -> None: - """Druk informatie af over het momenteel gebruikte geheugen. +def mem_info(verbose: Any = None) -> None: + """Print information about currently used memory. -Example: ``micropython.mem_info()`` + Example: ``micropython.mem_info()`` -:param verbose: Als het argument van ``verbose`` wordt opgegeven, wordt extra informatie afgedrukt.""" + :param verbose: If the ``verbose`` argument is given then extra information is printed. + """ ... -def qstr_info(verbose: Any=None) -> None: - """Druk informatie af over momenteel gebruikte interne tekenreeksen. +def qstr_info(verbose: Any = None) -> None: + """Print information about currently interned strings. -Example: ``micropython.qstr_info()`` + Example: ``micropython.qstr_info()`` -:param verbose: Als het argument van ``verbose`` wordt opgegeven, wordt extra informatie afgedrukt. + :param verbose: If the ``verbose`` argument is given then extra information is printed. -The information that is printed is implementation dependent, but currently -includes the number of interned strings and the amount of RAM they use. In -verbose mode it prints out the names of all RAM-interned strings.""" + The information that is printed is implementation dependent, but currently + includes the number of interned strings and the amount of RAM they use. In + verbose mode it prints out the names of all RAM-interned strings. + """ ... def stack_use() -> int: - """Retourneert een integer getal dat huidige hoeveelheid stack vertegenwoordigt die wordt gebruikt. (stapel gebruik) + """Return an integer representing the current amount of stack that is being + used. -Example: ``micropython.stack_use()`` + Example: ``micropython.stack_use()`` -The absolute value of this is not particularly useful, rather it -should be used to compute differences in stack usage at different points. + The absolute value of this is not particularly useful, rather it + should be used to compute differences in stack usage at different points. -:return: An integer representing current stack use.""" + :return: An integer representing current stack use. + """ ... def heap_lock() -> None: - """Lock de heap. (heap slot) + """Lock the heap. -Example: ``micropython.heap_lock()`` + Example: ``micropython.heap_lock()`` -When locked no memory allocation can occur and a ``MemoryError`` will be -raised if any heap allocation is attempted.""" + When locked no memory allocation can occur and a ``MemoryError`` will be + raised if any heap allocation is attempted. + """ ... def heap_unlock() -> None: """Unlock the heap. -Example: ``micropython.heap_unlock()`` + Example: ``micropython.heap_unlock()`` -When locked no memory allocation can occur and a ``MemoryError`` will be -raised if any heap allocation is attempted.""" + When locked no memory allocation can occur and a ``MemoryError`` will be + raised if any heap allocation is attempted. + """ ... def kbd_intr(chr: int) -> None: - """Stel het karakter in dat een ``KeyboardInterrupt`` -uitzondering maakt. + """Set the character that will raise a ``KeyboardInterrupt`` exception. -Example: ``micropython.kbd_intr(-1)`` + Example: ``micropython.kbd_intr(-1)`` -:param chr: Karakter code om de onderbreking of -1 om opname van Ctrl-C uit te schakelen. + :param chr: Character code to raise the interrupt or -1 to disable capture of Ctrl-C. -By default this is set to 3 during script execution, corresponding to Ctrl-C. -Passing -1 to this function will disable capture of Ctrl-C, and passing 3 -will restore it. + By default this is set to 3 during script execution, corresponding to Ctrl-C. + Passing -1 to this function will disable capture of Ctrl-C, and passing 3 + will restore it. -This function can be used to prevent the capturing of Ctrl-C on the -incoming stream of characters that is usually used for the REPL, in case -that stream is used for other purposes.""" - ... \ No newline at end of file + This function can be used to prevent the capturing of Ctrl-C on the + incoming stream of characters that is usually used for the REPL, in case + that stream is used for other purposes. + """ + ... diff --git a/lang/nl/typeshed/stdlib/music.pyi b/lang/nl/typeshed/stdlib/music.pyi index 5c3c7fc..5f4778b 100644 --- a/lang/nl/typeshed/stdlib/music.pyi +++ b/lang/nl/typeshed/stdlib/music.pyi @@ -1,128 +1,167 @@ -"""Maak en speel melodieën. (muziek)""" +"""Create and play melodies. +""" from typing import Optional, Tuple, Union, List + from .microbit import MicroBitDigitalPin, pin0 + DADADADUM: Tuple[str, ...] -"""Melodie: de opening naar Beethoven's 5e Symfonie in C minor.""" +"""Melody: the opening to Beethoven’s 5th Symphony in C minor.""" + ENTERTAINER: Tuple[str, ...] -"""Melody: het openingsfragment van Scott Joplin’s Ragtime classic “The Entertainer”.""" +"""Melody: the opening fragment of Scott Joplin’s Ragtime classic “The Entertainer”.""" + PRELUDE: Tuple[str, ...] -"""Melodie: de opening van de eerste prelude in C Major van J.S.Bach's 48 Preludes en Fugues.""" +"""Melody: the opening of the first Prelude in C Major of J.S.Bach’s 48 Preludes and Fugues.""" + ODE: Tuple[str, ...] -"""Melodie: het thema "Ode aan Joy" van Beethoven zijn negende Symfonie in D-klein.""" +"""Melody: the “Ode to Joy” theme from Beethoven’s 9th Symphony in D minor.""" + NYAN: Tuple[str, ...] -"""Melodie: het Nyan Cat thema (http://www.nyan.cat/). +"""Melody: the Nyan Cat theme (http://www.nyan.cat/). The composer is unknown. This is fair use for educational porpoises (as they say in New York).""" + RINGTONE: Tuple[str, ...] -"""Melodie: iets dat klinkt als een beltoon van een mobiele telefoon. (beltoon) +"""Melody: something that sounds like a mobile phone ringtone. To be used to indicate an incoming message. """ + FUNK: Tuple[str, ...] -"""Melodie: een grappige bas lijn voor geheime agenten en criminele meesterbreinen.""" +"""Melody: a funky bass line for secret agents and criminal masterminds.""" + BLUES: Tuple[str, ...] -"""Melodie: een boogie-woogie 12-bar blues wandel bas. (Blues)""" +"""Melody: a boogie-woogie 12-bar blues walking bass.""" + BIRTHDAY: Tuple[str, ...] -"""Melodie: “Happy Birthday to You…” (verjaardag) +"""Melody: “Happy Birthday to You…” For copyright status see: http://www.bbc.co.uk/news/world-us-canada-34332853 """ + WEDDING: Tuple[str, ...] -"""Melodie: het bruidskoor van de opera van Wagner “Lohengrin”. (bruiloft)""" +"""Melody: the bridal chorus from Wagner’s opera “Lohengrin”.""" + FUNERAL: Tuple[str, ...] -"""Melody: de “begrafenismars” die ook bekend staat als Frédéric Chopin’s Piano Sonata No. 2 in B♭ minor, Op. 35. (begrafenis)""" +"""Melody: the “funeral march” otherwise known as Frédéric Chopin’s Piano Sonata No. 2 in B♭ minor, Op. 35.""" + PUNCHLINE: Tuple[str, ...] -"""Melodie: een grappig fragment dat aangeeft dat er een grap is gemaakt. (clou)""" +"""Melody: a fun fragment that signifies a joke has been made.""" + PYTHON: Tuple[str, ...] -"""Melodie: John Philip Sousa's mars "Liberty Bell", ook bekend als het thema voor "Monty Python's Flying Circus" (waarnaar de programmeertaal Python is vernoemd).""" +"""Melody: John Philip Sousa’s march “Liberty Bell” aka, the theme for “Monty Python’s Flying Circus” (after which the Python programming language is named).""" + BADDY: Tuple[str, ...] -"""Melodie: stomme filmtijdperk de binnenkomst van een boef. (boef)""" +"""Melody: silent movie era entrance of a baddy.""" + CHASE: Tuple[str, ...] -"""Melodie: stille film tijdperk achtervolgings-scène. (achtervolgen)""" +"""Melody: silent movie era chase scene.""" + BA_DING: Tuple[str, ...] -"""Melodie: een kort signaal om aan te geven dat er iets is gebeurd.""" +"""Melody: a short signal to indicate something has happened.""" + WAWAWAWAA: Tuple[str, ...] -"""Melody: een zeer trieste trombone.""" +"""Melody: a very sad trombone.""" + JUMP_UP: Tuple[str, ...] -"""Melody: voor gebruik in een spel om opwaartse beweging aan te geven. (spring omhoog)""" +"""Melody: for use in a game, indicating upward movement.""" + JUMP_DOWN: Tuple[str, ...] -"""Melody: voor gebruik in een spel, om neerwaartse beweging aan te geven. (spring omlaag)""" +"""Melody: for use in a game, indicating downward movement.""" + POWER_UP: Tuple[str, ...] -"""Melodie: een fanfare die aantoont dat een prestatie ontgrendeld is. (opstarten)""" +"""Melody: a fanfare to indicate an achievement unlocked.""" + POWER_DOWN: Tuple[str, ...] -"""Melody: een droevige fanfare om aan te geven dat een prestatie verloren is gegaan. (afsluiten)""" +"""Melody: a sad fanfare to indicate an achievement lost.""" -def set_tempo(ticks: int=4, bpm: int=120) -> None: - """Stelt het geschatte tempo in voor het afspelen. (kies tempo) +def set_tempo(ticks: int = 4, bpm: int = 120) -> None: + """Sets the approximate tempo for playback. -Example: ``music.set_tempo(bpm=120)`` + Example: ``music.set_tempo(bpm=120)`` -:param ticks: (tikken) Het aantal tikken in een beat. -:param bpm: Een geheel getal dat het aantal beats per minuut bepaalt. + :param ticks: The number of ticks constituting a beat. + :param bpm: An integer determining how many beats per minute. -Suggested default values allow the following useful behaviour: + Suggested default values allow the following useful behaviour: -- music.set_tempo() – reset the tempo to default of ticks = 4, bpm = 120 -- music.set_tempo(ticks=8) – change the “definition” of a beat -- music.set_tempo(bpm=180) – just change the tempo + - music.set_tempo() – reset the tempo to default of ticks = 4, bpm = 120 + - music.set_tempo(ticks=8) – change the “definition” of a beat + - music.set_tempo(bpm=180) – just change the tempo -To work out the length of a tick in milliseconds is very simple arithmetic: -60000/bpm/ticks_per_beat. For the default values that’s -60000/120/4 = 125 milliseconds or 1 beat = 500 milliseconds.""" + To work out the length of a tick in milliseconds is very simple arithmetic: + 60000/bpm/ticks_per_beat. For the default values that’s + 60000/120/4 = 125 milliseconds or 1 beat = 500 milliseconds. + """ ... def get_tempo() -> Tuple[int, int]: - """Haalt het huidige tempo op als een heel geheel getal: ``(ticks, bpm)``. (krijg tempo) + """Gets the current tempo as a tuple of integers: ``(ticks, bpm)``. -Example: ``ticks, beats = music.get_tempo()`` + Example: ``ticks, beats = music.get_tempo()`` -:return: The temp as a tuple with two integer values, the ticks then the beats per minute.""" + :return: The temp as a tuple with two integer values, the ticks then the beats per minute. + """ ... -def play(music: Union[str, List[str], Tuple[str, ...]], pin: Optional[MicroBitDigitalPin]=pin0, wait: bool=True, loop: bool=False) -> None: - """Speelt muziek af. (afspelen) +def play( + music: Union[str, List[str], Tuple[str, ...]], + pin: Optional[MicroBitDigitalPin] = pin0, + wait: bool = True, + loop: bool = False, +) -> None: + """Plays music. -Example: ``music.play(music.NYAN)`` + Example: ``music.play(music.NYAN)`` -:param music: (muziek) muziek opgegeven in `a special notation `_ -:param pin: de uitvoer pin voor gebruik met een externe luidspreker (standaard ``pin0``), ``None`` voor geen geluid. -:param wait: (wacht) Als ``wait`` is ingesteld op ``True``wordt deze functie geblokkeerd. -:param loop: Als ``loop`` is ingesteld op ``True``herhaalt de melodie tot ``stop`` wordt opgeroepen of wordt de blokkerende oproep word onderbroken. + :param music: music specified in `a special notation `_ + :param pin: the output pin for use with an external speaker (default ``pin0``), ``None`` for no sound. + :param wait: If ``wait`` is set to ``True``, this function is blocking. + :param loop: If ``loop`` is set to ``True``, the tune repeats until ``stop`` is called or the blocking call is interrupted. -Many built-in melodies are defined in this module.""" + Many built-in melodies are defined in this module. + """ ... -def pitch(frequency: int, duration: int=-1, pin: Optional[MicroBitDigitalPin]=pin0, wait: bool=True) -> None: - """Speel een noot. (toonhoogte) +def pitch( + frequency: int, + duration: int = -1, + pin: Optional[MicroBitDigitalPin] = pin0, + wait: bool = True, +) -> None: + """Play a note. -Example: ``music.pitch(185, 1000)`` + Example: ``music.pitch(185, 1000)`` -:param frequency: (frequentie) Een integere frequentie -:param duration: (Duur) Een milliseconde duur. Als negatief dan gaat het geluid door tot de volgende oproep of een oproep tot ``stop``. -:param pin: Optionele uitvoer pin (standaard ``pin0``). -:param wait: (wacht) Als ``wait`` is ingesteld op ``True``wordt deze functie geblokkeerd. + :param frequency: An integer frequency + :param duration: A millisecond duration. If negative then sound is continuous until the next call or a call to ``stop``. + :param pin: Optional output pin (default ``pin0``). + :param wait: If ``wait`` is set to ``True``, this function is blocking. -For example, if the frequency is set to 440 and the length to -1000 then we hear a standard concert A for one second. + For example, if the frequency is set to 440 and the length to + 1000 then we hear a standard concert A for one second. -You can only play one pitch on one pin at any one time.""" + You can only play one pitch on one pin at any one time. + """ ... -def stop(pin: Optional[MicroBitDigitalPin]=pin0) -> None: - """Stopt alle muziek op de ingebouwde luidspreker en elke pin die geluid uitzendt. +def stop(pin: Optional[MicroBitDigitalPin] = pin0) -> None: + """Stops all music playback on the built-in speaker and any pin outputting sound. -Example: ``music.stop()`` + Example: ``music.stop()`` -:param pin: Een optioneel argument kan worden opgegeven om een pin op te geven, bijvoorbeeld ``music.stop(pin1)``.""" + :param pin: An optional argument can be provided to specify a pin, e.g. ``music.stop(pin1)``. + """ def reset() -> None: - """Reset ticks, bpm, duur en octaven naar hun standaardwaarden. + """Resets ticks, bpm, duration and octave to their default values. -Example: ``music.reset()`` + Example: ``music.reset()`` -Values: -- ``ticks = 4`` -- ``bpm = 120`` -- ``duration = 4`` -- ``octave = 4``""" - ... \ No newline at end of file + Values: + - ``ticks = 4`` + - ``bpm = 120`` + - ``duration = 4`` + - ``octave = 4`` + """ + ... diff --git a/lang/nl/typeshed/stdlib/neopixel.pyi b/lang/nl/typeshed/stdlib/neopixel.pyi index 93183ed..2d5a749 100644 --- a/lang/nl/typeshed/stdlib/neopixel.pyi +++ b/lang/nl/typeshed/stdlib/neopixel.pyi @@ -1,81 +1,82 @@ -"""Individueel adresseerbare RGB en RGBW LED-strips.""" +"""Individually addressable RGB and RGBW LED strips. +""" from .microbit import MicroBitDigitalPin from typing import Tuple class NeoPixel: + def __init__(self, pin: MicroBitDigitalPin, n: int, bpp: int = 3) -> None: + """Initialise a new strip of neopixel LEDs controlled via a pin. - def __init__(self, pin: MicroBitDigitalPin, n: int, bpp: int=3) -> None: - """Initialiseer een nieuwe strip van neopixel LED's beheerd via een pin. (initialiseren) + Example: ``np = neopixel.NeoPixel(pin0, 8)`` -Example: ``np = neopixel.NeoPixel(pin0, 8)`` + To support RGBW neopixels, a third argument can be passed to + ``NeoPixel`` to indicate the number of bytes per pixel (``bpp``). + For RGBW, this is is 4 rather than the default of 3 for RGB and GRB. -To support RGBW neopixels, a third argument can be passed to -``NeoPixel`` to indicate the number of bytes per pixel (``bpp``). -For RGBW, this is is 4 rather than the default of 3 for RGB and GRB. + Each pixel is addressed by a position (starting from 0). Neopixels are + given RGB (red, green, blue) / RGBW (red, green, blue, white) values + between 0-255 as a tuple. For example, in RGB, ``(255,255,255)`` is + white. In RGBW, ``(255,255,255,0)`` or ``(0,0,0,255)`` is white. -Each pixel is addressed by a position (starting from 0). Neopixels are -given RGB (red, green, blue) / RGBW (red, green, blue, white) values -between 0-255 as a tuple. For example, in RGB, ``(255,255,255)`` is -white. In RGBW, ``(255,255,255,0)`` or ``(0,0,0,255)`` is white. + See `the online docs `_ for warnings and other advice. -See `the online docs `_ for warnings and other advice. - -:param pin: De pin regelt de neopixelstrook. -:param n: Het aantal neopixels in de strip. -:param bpp: Bytes per pixel. Voor ondersteuning van RGBW neopixels geeft je 4 aan in plaats van de standaardwaarde van 3 voor RGB en GRB.""" + :param pin: The pin controlling the neopixel strip. + :param n: The number of neopixels in the strip. + :param bpp: Bytes per pixel. For RGBW neopixel support, pass 4 rather than the default of 3 for RGB and GRB. + """ ... - def clear(self) -> None: - """Verwijder alle pixels. (wissen) + """Clear all the pixels. -Example: ``np.clear()``""" + Example: ``np.clear()`` + """ ... - def show(self) -> None: - """Toon de pixels. (toon) + """Show the pixels. -Example: ``np.show()`` + Example: ``np.show()`` -Must be called for any updates to become visible.""" + Must be called for any updates to become visible. + """ ... - def write(self) -> None: - """Toon de pixels (alleen micro:bit V2). (schrijven) + """Show the pixels (micro:bit V2 only). -Example: ``np.write()`` + Example: ``np.write()`` -Must be called for any updates to become visible. + Must be called for any updates to become visible. -Equivalent to ``show``.""" + Equivalent to ``show``. + """ ... - def fill(self, colour: Tuple[int, ...]) -> None: - """Kleur alle pixels een bepaalde RGB/RGBW waarde (alleen micro:bit V2). (opvullen) + """Colour all pixels a given RGB/RGBW value (micro:bit V2 only). -Example: ``np.fill((0, 0, 255))`` + Example: ``np.fill((0, 0, 255))`` -:param colour: (kleur) Een tuple van dezelfde lengte als het aantal bytes per pixel (bpp). + :param colour: A tuple of the same length as the number of bytes per pixel (bpp). -Use in conjunction with ``show()`` to update the neopixels.""" + Use in conjunction with ``show()`` to update the neopixels. + """ ... - def __setitem__(self, key: int, value: Tuple[int, ...]) -> None: - """Stel een pixelkleur in. + """Set a pixel colour. -Example: ``np[0] = (255, 0, 0)`` - -:param key: (sleutel) Het pixelnummer. -:param value: (waarde) De kleur.""" + Example: ``np[0] = (255, 0, 0)`` + :param key: The pixel number. + :param value: The colour. + """ def __getitem__(self, key: int) -> Tuple[int, ...]: - """Krijg een pixelkleur. - -Example: ``r, g, b = np[0]`` + """Get a pixel colour. -:param key: (sleutel) Het pixelnummer. -:return: The colour tuple.""" + Example: ``r, g, b = np[0]`` + :param key: The pixel number. + :return: The colour tuple. + """ def __len__(self) -> int: - """Haal de lengte op van deze pixelstrip. + """Get length of this pixel strip. -Example: ``len(np)``""" \ No newline at end of file + Example: ``len(np)`` + """ diff --git a/lang/nl/typeshed/stdlib/os.pyi b/lang/nl/typeshed/stdlib/os.pyi index bfa6adf..2f2db77 100644 --- a/lang/nl/typeshed/stdlib/os.pyi +++ b/lang/nl/typeshed/stdlib/os.pyi @@ -1,63 +1,73 @@ -"""Toegang tot het bestandssysteem.""" +"""Access the file system. +""" + from typing import Tuple from typing import List def listdir() -> List[str]: - """Bestanden weergeven. + """List files. -Example: ``os.listdir()`` + Example: ``os.listdir()`` -:return: A list of the names of all the files contained within the local -persistent on-device file system.""" + :return: A list of the names of all the files contained within the local + persistent on-device file system. + """ ... def remove(filename: str) -> None: - """Verwijder (verwijder) een bestand. (verwijder) + """Remove (delete) a file. -Example: ``os.remove('data.txt')`` + Example: ``os.remove('data.txt')`` -:param filename: (bestands naam) Het bestand is verwijderd + :param filename: The file to delete. -If the file does not exist an ``OSError`` exception will occur.""" + If the file does not exist an ``OSError`` exception will occur. + """ ... def size(filename: str) -> int: - """Geeft de grootte van een bestand weer. (grootte) + """Returns the size of a file. -Example: ``os.size('data.txt')`` + Example: ``os.size('data.txt')`` -:param filename: (bestands naam) Het bestand -:return: The size in bytes. + :param filename: The file + :return: The size in bytes. -If the file does not exist an ``OSError`` exception will occur.""" + If the file does not exist an ``OSError`` exception will occur. + """ class uname_result(Tuple[str, str, str, str, str]): - """Resultaat van ``os.uname()`` (uname resultaat)""" + """Result of ``os.uname()``""" sysname: str - """Besturingssysteem naam""" + """Operating system name.""" + nodename: str - """Naam van machine op het netwerk (implementation-defined).""" + """Name of machine on network (implementation-defined).""" + release: str - """Besturingssysteem release. (vrijgeven)""" + """Operating system release.""" + version: str - """Besturingssysteem versie. (versie)""" + """Operating system version.""" + machine: str - """Identificatie hardware""" + """Hardware identifier.""" def uname() -> uname_result: - """Geeft informatie terug die het huidige besturingssysteem identificeert. + """Returns information identifying the current operating system. -Example: ``os.uname()`` + Example: ``os.uname()`` -The return value is an object with five attributes: + The return value is an object with five attributes: -- ``sysname`` - operating system name -- ``nodename`` - name of machine on network (implementation-defined) -- ``release`` - operating system release -- ``version`` - operating system version -- ``machine`` - hardware identifier + - ``sysname`` - operating system name + - ``nodename`` - name of machine on network (implementation-defined) + - ``release`` - operating system release + - ``version`` - operating system version + - ``machine`` - hardware identifier -There is no underlying operating system in MicroPython. As a result the -information returned by the ``uname`` function is mostly useful for -versioning details.""" - ... \ No newline at end of file + There is no underlying operating system in MicroPython. As a result the + information returned by the ``uname`` function is mostly useful for + versioning details. + """ + ... diff --git a/lang/nl/typeshed/stdlib/radio.pyi b/lang/nl/typeshed/stdlib/radio.pyi index 656cb19..8dd0267 100644 --- a/lang/nl/typeshed/stdlib/radio.pyi +++ b/lang/nl/typeshed/stdlib/radio.pyi @@ -1,130 +1,152 @@ -"""Communiceer tussen micro:bits met de ingebouwde radio.""" +"""Communicate between micro:bits with the built-in radio. +""" + from _typeshed import WriteableBuffer from typing import Optional, Tuple + RATE_1MBIT: int -"""Constante gebruikt om een doorvoer van 1 MBit per seconde aan te geven.""" +"""Constant used to indicate a throughput of 1 MBit a second.""" + RATE_2MBIT: int -"""Constante gebruikt om een doorvoer van 2 MBit per seconde aan te geven.""" +"""Constant used to indicate a throughput of 2 MBit a second.""" def on() -> None: - """Zet de radio aan. (aan) + """Turns the radio on. -Example: ``radio.on()`` + Example: ``radio.on()`` -This needs to be explicitly called since the radio draws power and takes -up memory that you may otherwise need.""" + This needs to be explicitly called since the radio draws power and takes + up memory that you may otherwise need. + """ ... def off() -> None: - """Schakelt de radio uit, bespaar stroom en geheugen. (uit) + """Turns off the radio, saving power and memory. -Example: ``radio.off()``""" + Example: ``radio.off()`` + """ ... -def config(length: int=32, queue: int=3, channel: int=7, power: int=6, address: int=1969383796, group: int=0, data_rate: int=RATE_1MBIT) -> None: - """Configureert de radio. (configuratie) - -Example: ``radio.config(group=42)`` - -The default configuration is suitable for most use. - -:param length: (lengte) (default=32) definieert de maximale lengte, in bytes, van een bericht dat via de radio wordt verzonden. -Het kan maximaal 251 bytes lang zijn (254 - 3 bytes voor S0, LENGTH en S1 preamble). -:param queue: (wachtrij) (standaard=3) geeft het aantal berichten aan dat in de wachtrij van het inkomende bericht kan worden opgeslagen. -Als er geen ruimte meer is in de wachtrij voor binnenkomende berichten, dan valt het inkomende bericht weg. -:param channel: (kanaal) (default=7) een integer waarde van 0 tot 83 (inclusief) die een willekeurig "kanaal" definieert waaraan de radio wordt afgestemd. -Berichten worden via dit kanaal verzonden en alleen via dit kanaal worden berichten in de wachtrij van het inkomende berichten geplaatst. Elke stap is 1 MHz breed, gebaseerd op 2400MHz. -:param power: (vermogen) (default=6) is een integer waarde van 0 tot 7 (inclusief) om de sterkte van het signaal aan te geven dat wordt gebruikt bij het uitzenden van een bericht. -Hoe hoger de waarde, des te sterker het signaal, maar hoe meer stroom het apparaat verbruikt. De nummering vertaalt naar posities in de volgende lijst van dBm (decibel milliwatt) waarden: -30, -20, -16, -12, -8, -4, 0, 4. -:param address: (adres) (default=0x75626974) een willekeurige naam, uitgedrukt als een 32-bits adres, wordt gebruikt om inkomende pakketten op hardware-niveau te filteren, waarbij alleen de pakketten worden bewaard die overeenkomen met het adres dat je zelf instelt. -De standaard gebruiker door andere micro:bit gerelateerde platforms is de standaard instelling die hier wordt gebruikt. -:param group: (groep) (standaard=0) een 8-bit waarde (0-255) gebruikt met de ``address`` bij het filteren van berichten. -Conceptueel, "adres" is als een huis/kantooradres en "groep" is als de persoon op dat adres waarnaar je je bericht wilt sturen. -:param data_rate: (Gegevens snelheid) (default=``radio.RATE_1MBIT``) geeft aan hoe snel de doorvoer van gegevens plaatsvindt. -Kan een van de volgende constanten zijn gedefinieerd in de ``radio`` module: ``RATE_250KBIT``, ``RATE_1MBIT`` of ``RATE_2MBIT``. - -If ``config`` is not called then the defaults described above are assumed.""" +def config( + length: int = 32, + queue: int = 3, + channel: int = 7, + power: int = 6, + address: int = 0x75626974, + group: int = 0, + data_rate: int = RATE_1MBIT, +) -> None: + """Configures the radio. + + Example: ``radio.config(group=42)`` + + The default configuration is suitable for most use. + + :param length: (default=32) defines the maximum length, in bytes, of a message sent via the radio. + It can be up to 251 bytes long (254 - 3 bytes for S0, LENGTH and S1 preamble). + :param queue: (default=3) specifies the number of messages that can be stored on the incoming message queue. + If there are no spaces left on the queue for incoming messages, then the incoming message is dropped. + :param channel: (default=7) an integer value from 0 to 83 (inclusive) that defines an arbitrary "channel" to which the radio is tuned. + Messages will be sent via this channel and only messages received via this channel will be put onto the incoming message queue. Each step is 1MHz wide, based at 2400MHz. + :param power: (default=6) is an integer value from 0 to 7 (inclusive) to indicate the strength of signal used when broadcasting a message. + The higher the value the stronger the signal, but the more power is consumed by the device. The numbering translates to positions in the following list of dBm (decibel milliwatt) values: -30, -20, -16, -12, -8, -4, 0, 4. + :param address: (default=0x75626974) an arbitrary name, expressed as a 32-bit address, that's used to filter incoming packets at the hardware level, keeping only those that match the address you set. + The default used by other micro:bit related platforms is the default setting used here. + :param group: (default=0) an 8-bit value (0-255) used with the ``address`` when filtering messages. + Conceptually, "address" is like a house/office address and "group" is like the person at that address to which you want to send your message. + :param data_rate: (default=``radio.RATE_1MBIT``) indicates the speed at which data throughput takes place. + Can be one of the following constants defined in the ``radio`` module: ``RATE_250KBIT``, ``RATE_1MBIT`` or ``RATE_2MBIT``. + + If ``config`` is not called then the defaults described above are assumed. + """ ... def reset() -> None: - """Reset alle instellingen naar hun standaardwaarde. + """Reset the settings to their default values. -Example: ``radio.reset()`` + Example: ``radio.reset()`` -The defaults as as per the ``config`` function above.""" + The defaults as as per the ``config`` function above. + """ ... def send_bytes(message: bytes) -> None: - """Stuurt een bericht met bytes. (verstuur bytes) + """Sends a message containing bytes. -Example: ``radio.send_bytes(b'hello')`` + Example: ``radio.send_bytes(b'hello')`` -:param message: (bericht) De te verzenden bytes.""" + :param message: The bytes to send. + """ ... def receive_bytes() -> Optional[bytes]: - """Ontvang het volgende inkomende bericht in de wachtrij van het bericht. (ontvang bytes) + """Receive the next incoming message on the message queue. -Example: ``radio.receive_bytes()`` + Example: ``radio.receive_bytes()`` -:return: The message bytes if any, otherwise ``None``.""" + :return: The message bytes if any, otherwise ``None``. + """ ... def receive_bytes_into(buffer: WriteableBuffer) -> Optional[int]: - """Kopieer het volgende inkomende bericht in de wachtrij van het bericht naar een buffer. (ontvang bytes in) + """Copy the next incoming message on the message queue into a buffer. -Example: ``radio.receive_bytes_info(buffer)`` + Example: ``radio.receive_bytes_info(buffer)`` -:param buffer: De doel buffer. Het bericht wordt ingekort als het groter is dan de buffer. -:return: ``None`` if there are no pending messages, otherwise it returns the length of the message (which might be more than the length of the buffer).""" + :param buffer: The target buffer. The message is truncated if larger than the buffer. + :return: ``None`` if there are no pending messages, otherwise it returns the length of the message (which might be more than the length of the buffer). + """ ... def send(message: str) -> None: - """Stuurt een berichtenreeks. (verzenden) + """Sends a message string. -Example: ``radio.send('hello')`` + Example: ``radio.send('hello')`` -This is the equivalent of ``radio.send_bytes(bytes(message, 'utf8'))`` but with ``b'\x01\x00\x01'`` -prepended to the front (to make it compatible with other platforms that target the micro:bit). + This is the equivalent of ``radio.send_bytes(bytes(message, 'utf8'))`` but with ``b'\x01\x00\x01'`` + prepended to the front (to make it compatible with other platforms that target the micro:bit). -:param message: (bericht) De te verzenden tekenreeks.""" + :param message: The string to send. + """ ... def receive() -> Optional[str]: - """Werkt op precies dezelfde manier als ``receive_bytes`` , maar retourneert wat er verzonden is. (ontvang) + """Works in exactly the same way as ``receive_bytes`` but returns whatever was sent. -Example: ``radio.receive()`` + Example: ``radio.receive()`` -Equivalent to ``str(receive_bytes(), 'utf8')`` but with a check that the the first -three bytes are ``b'\x01\x00\x01'`` (to make it compatible with other platforms that -may target the micro:bit). + Equivalent to ``str(receive_bytes(), 'utf8')`` but with a check that the the first + three bytes are ``b'\x01\x00\x01'`` (to make it compatible with other platforms that + may target the micro:bit). -:return: The message with the prepended bytes stripped and converted to a string. + :return: The message with the prepended bytes stripped and converted to a string. -A ``ValueError`` exception is raised if conversion to string fails.""" + A ``ValueError`` exception is raised if conversion to string fails. + """ ... def receive_full() -> Optional[Tuple[bytes, int, int]]: - """Geeft als resultaat een dup met drie waarden die het volgende inkomende bericht in de wachtrij van het bericht weergeven. (Ontvang vol) + """Returns a tuple containing three values representing the next incoming message on the message queue. -Example: ``radio.receive_full()`` + Example: ``radio.receive_full()`` -If there are no pending messages then ``None`` is returned. + If there are no pending messages then ``None`` is returned. -The three values in the tuple represent: + The three values in the tuple represent: -- the next incoming message on the message queue as bytes. -- the RSSI (signal strength): a value between 0 (strongest) and -255 (weakest) as measured in dBm. -- a microsecond timestamp: the value returned by ``time.ticks_us()`` when the message was received. + - the next incoming message on the message queue as bytes. + - the RSSI (signal strength): a value between 0 (strongest) and -255 (weakest) as measured in dBm. + - a microsecond timestamp: the value returned by ``time.ticks_us()`` when the message was received. -For example:: + For example:: - details = radio.receive_full() - if details: - msg, rssi, timestamp = details + details = radio.receive_full() + if details: + msg, rssi, timestamp = details -This function is useful for providing information needed for triangulation -and/or trilateration with other micro:bit devices. + This function is useful for providing information needed for triangulation + and/or trilateration with other micro:bit devices. -:return: ``None`` if there is no message, otherwise a tuple of length three with the bytes, strength and timestamp values.""" - ... \ No newline at end of file + :return: ``None`` if there is no message, otherwise a tuple of length three with the bytes, strength and timestamp values. + """ + ... diff --git a/lang/nl/typeshed/stdlib/random.pyi b/lang/nl/typeshed/stdlib/random.pyi index 32acd0e..a2c2ef3 100644 --- a/lang/nl/typeshed/stdlib/random.pyi +++ b/lang/nl/typeshed/stdlib/random.pyi @@ -1,81 +1,93 @@ -"""Willekeurige getallen genereren. (willekeurig)""" +"""Generate random numbers. +""" from typing import TypeVar, Sequence, Union, overload def getrandbits(n: int) -> int: - """Genereer een geheel getal met ``n`` willekeurige bits. + """Generate an integer with ``n`` random bits. -Example: ``random.getrandbits(1)`` + Example: ``random.getrandbits(1)`` -:param n: Een waarde tussen 1-30 (inclusief).""" + :param n: A value between 1-30 (inclusive). + """ ... def seed(n: int) -> None: - """Initialiseer de willekeurige getalgenerator. + """Initialize the random number generator. -Example: ``random.seed(0)`` + Example: ``random.seed(0)`` -:param n: De integer seed + :param n: The integer seed -This will give you reproducibly deterministic randomness from a given starting -state (``n``).""" + This will give you reproducibly deterministic randomness from a given starting + state (``n``). + """ ... def randint(a: int, b: int) -> int: - """Kies een willekeurig geheel getal tussen ``a`` en ``b`` inclusief. + """Choose a random integer between ``a`` and ``b`` inclusive. -Example: ``random.randint(0, 9)`` + Example: ``random.randint(0, 9)`` -:param a: Beginwaarde voor het bereik (inclusief) -:param b: Eindwaarde voor het bereik (inclusief) + :param a: Start value for the range (inclusive) + :param b: End value for the range (inclusive) -Alias for ``randrange(a, b + 1)``.""" + Alias for ``randrange(a, b + 1)``. + """ ... @overload def randrange(stop: int) -> int: - """Kies een willekeurig geselecteerd geheel getal tussen nul en tot (maar niet -inclusief) ``stop``. + """Choose a randomly selected integer between zero and up to (but not + including) ``stop``. -Example: ``random.randrange(10)`` + Example: ``random.randrange(10)`` -:param stop: Eindwaarde voor het bereik (exclusief)""" + :param stop: End value for the range (exclusive) + """ ... @overload -def randrange(start: int, stop: int, step: int=1) -> int: - """Kies een willekeurig geselecteerd element uit ``range(start, stop, step)``. +def randrange(start: int, stop: int, step: int = 1) -> int: + """ + Choose a randomly selected element from ``range(start, stop, step)``. -Example: ``random.randrange(0, 10)`` + Example: ``random.randrange(0, 10)`` -:param start: Het begin van het bereik (inclusief) -:param stop: Einde van het bereik (exclusief) -:param step: (stap) De stap.""" + :param start: The start of the range (inclusive) + :param stop: The end of the range (exclusive) + :param step: The step. + """ ... -_T = TypeVar('_T') + +_T = TypeVar("_T") def choice(seq: Sequence[_T]) -> _T: - """Kies een willekeurig element uit de niet-lege reeks ``seq``. (keuze) + """Choose a random element from the non-empty sequence ``seq``. -Example: ``random.choice([Image.HAPPY, Image.SAD])`` + Example: ``random.choice([Image.HAPPY, Image.SAD])`` -:param seq: Een volgorde. + :param seq: A sequence. -If ``seq`` is empty, raises ``IndexError``.""" + If ``seq`` is empty, raises ``IndexError``. + """ ... def random() -> float: - """Genereer een willekeurig zwevend puntnummer in het bereik [0.0, 1.0). (willekeurig) + """Generate a random floating point number in the range [0.0, 1.0). -Example: ``random.random()`` + Example: ``random.random()`` -:return: The random floating point number""" + :return: The random floating point number + """ ... def uniform(a: float, b: float) -> float: - """Geeft een willekeurig zwevend punt nummer tussen ``a`` en ``b`` inclusief. + """ + Return a random floating point number between ``a`` and ``b`` inclusive. -Example: ``random.uniform(0, 9)`` + Example: ``random.uniform(0, 9)`` -:param a: Beginwaarde voor het bereik (inclusief) -:param b: Eindwaarde voor het bereik (inclusief)""" - ... \ No newline at end of file + :param a: Start value for the range (inclusive) + :param b: End value for the range (inclusive) + """ + ... diff --git a/lang/nl/typeshed/stdlib/speech.pyi b/lang/nl/typeshed/stdlib/speech.pyi index 2075501..349d188 100644 --- a/lang/nl/typeshed/stdlib/speech.pyi +++ b/lang/nl/typeshed/stdlib/speech.pyi @@ -1,76 +1,106 @@ -"""Laat de micro:bit praten, zingen en andere spraak maken, zoals geluid. (spraak)""" +"""Make the micro:bit talk, sing and make other speech like sounds. +""" + from typing import Optional from .microbit import MicroBitDigitalPin, pin0 def translate(words: str) -> str: - """Vertaal Engelse woorden naar fonemen. (vertalen) + """Translate English words to phonemes. -Example: ``speech.translate('hello world')`` + Example: ``speech.translate('hello world')`` -:param words: (woorden) Een tekenreeks Engelse woorden. -:return: A string containing a best guess at the appropriate phonemes to pronounce. -The output is generated from this `text to phoneme translation table `_. + :param words: A string of English words. + :return: A string containing a best guess at the appropriate phonemes to pronounce. + The output is generated from this `text to phoneme translation table `_. -This function should be used to generate a first approximation of phonemes -that can be further hand-edited to improve accuracy, inflection and -emphasis. + This function should be used to generate a first approximation of phonemes + that can be further hand-edited to improve accuracy, inflection and + emphasis. -See `the online documentation `_ for detailed information.""" + See `the online documentation `_ for detailed information. + """ ... -def pronounce(phonemes: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: Optional[MicroBitDigitalPin]=pin0) -> None: - """Uitspraak phonemes. (uitspreken) - -Example: ``speech.pronounce(' /HEHLOW WERLD')`` - -:param phonemes: (fonemen) De reeks fonemen om uit te spreken -:param pitch: (toonhoogte) Een nummer dat de toonhoogte van de stem weergeeft -:param speed: (snelheid) Een nummer dat de snelheid van de stem vertegenwoordigt -:param mouth: (mond) Een nummer dat de mond van de stem weergeeft -:param throat: (keel) Een nummer dat de keel van de stem weergeeft -:param pin: Een optioneel argument om de uitvoer pin op te geven, kan worden gebruikt om de standaard van ``pin0``te overschrijven. Als we geen geluid willen afspelen, kunnen we ``pin=None`` gebruiken. Alleen voor micro:bit V2. - -Override the optional pitch, speed, mouth and throat settings to change the -timbre (quality) of the voice. - -See `the online documentation `_ for detailed information.""" +def pronounce( + phonemes: str, + pitch: int = 64, + speed: int = 72, + mouth: int = 128, + throat: int = 128, + pin: Optional[MicroBitDigitalPin] = pin0, +) -> None: + """Pronounce phonemes. + + Example: ``speech.pronounce(' /HEHLOW WERLD')`` + + :param phonemes: The string of phonemes to pronounce + :param pitch: A number representing the pitch of the voice + :param speed: A number representing the speed of the voice + :param mouth: A number representing the mouth of the voice + :param throat: A number representing the throat of the voice + :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. + If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. + + Override the optional pitch, speed, mouth and throat settings to change the + timbre (quality) of the voice. + + See `the online documentation `_ for detailed information. + """ ... -def say(words: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: MicroBitDigitalPin=pin0) -> None: - """Zeg Engelse woorden. (zeg) - -Example: ``speech.say('hello world')`` - -:param words: (woorden) De tekenreeks van woorden om te zeggen. -:param pitch: (toonhoogte) Een nummer dat de toonhoogte van de stem weergeeft -:param speed: (snelheid) Een nummer dat de snelheid van de stem vertegenwoordigt -:param mouth: (mond) Een nummer dat de mond van de stem weergeeft -:param throat: (keel) Een nummer dat de keel van de stem weergeeft -:param pin: Een optioneel argument om de uitvoer pin op te geven, kan worden gebruikt om de standaard van ``pin0``te overschrijven. Als we geen geluid willen afspelen, kunnen we ``pin=None`` gebruiken. Alleen voor micro:bit V2. - -The result is semi-accurate for English. Override the optional pitch, speed, -mouth and throat settings to change the timbre (quality) of the voice. - -This is a short-hand equivalent of: -``speech.pronounce(speech.translate(words))`` - -See `the online documentation `_ for detailed information.""" +def say( + words: str, + pitch: int = 64, + speed: int = 72, + mouth: int = 128, + throat: int = 128, + pin: MicroBitDigitalPin = pin0, +) -> None: + """Say English words. + + Example: ``speech.say('hello world')`` + + :param words: The string of words to say. + :param pitch: A number representing the pitch of the voice + :param speed: A number representing the speed of the voice + :param mouth: A number representing the mouth of the voice + :param throat: A number representing the throat of the voice + :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. + If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. + + The result is semi-accurate for English. Override the optional pitch, speed, + mouth and throat settings to change the timbre (quality) of the voice. + + This is a short-hand equivalent of: + ``speech.pronounce(speech.translate(words))`` + + See `the online documentation `_ for detailed information. + """ ... -def sing(phonemes: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: MicroBitDigitalPin=pin0) -> None: - """Zing fonemen. (zing) - -Example: ``speech.sing(' /HEHLOW WERLD')`` - -:param phonemes: (fonemen) De tekenreeks van woorden om te zingen. -:param pitch: (toonhoogte) Een nummer dat de toonhoogte van de stem weergeeft -:param speed: (snelheid) Een nummer dat de snelheid van de stem vertegenwoordigt -:param mouth: (mond) Een nummer dat de mond van de stem weergeeft -:param throat: (keel) Een nummer dat de keel van de stem weergeeft -:param pin: Een optioneel argument om de uitvoer pin op te geven, kan worden gebruikt om de standaard van ``pin0``te overschrijven. Als we geen geluid willen afspelen, kunnen we ``pin=None`` gebruiken. Alleen voor micro:bit V2. - -Override the optional pitch, speed, mouth and throat settings to change -the timbre (quality) of the voice. - -See `the online documentation `_ for detailed information.""" - ... \ No newline at end of file +def sing( + phonemes: str, + pitch: int = 64, + speed: int = 72, + mouth: int = 128, + throat: int = 128, + pin: MicroBitDigitalPin = pin0, +) -> None: + """Sing phonemes. + + Example: ``speech.sing(' /HEHLOW WERLD')`` + + :param phonemes: The string of words to sing. + :param pitch: A number representing the pitch of the voice + :param speed: A number representing the speed of the voice + :param mouth: A number representing the mouth of the voice + :param throat: A number representing the throat of the voice + :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. + If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. + + Override the optional pitch, speed, mouth and throat settings to change + the timbre (quality) of the voice. + + See `the online documentation `_ for detailed information. + """ + ... diff --git a/lang/nl/typeshed/stdlib/struct.pyi b/lang/nl/typeshed/stdlib/struct.pyi index f88dc4a..53b3e0b 100644 --- a/lang/nl/typeshed/stdlib/struct.pyi +++ b/lang/nl/typeshed/stdlib/struct.pyi @@ -1,56 +1,65 @@ -"""Primitieve datatypes inpakken en uitpakken.""" +"""Pack and unpack primitive data types. +""" + from _typeshed import ReadableBuffer, WriteableBuffer from typing import Any, Tuple, Union def calcsize(fmt: str) -> int: - """Haal het aantal bytes op dat nodig is om de gegeven ``fmt`` op te slaan. + """Get the number of bytes needed to store the given ``fmt``. -Example: ``struct.calcsize('hf')`` + Example: ``struct.calcsize('hf')`` -:param fmt: Tekenreeks opmaak. -:return The number of bytes needed to store such a value.""" + :param fmt: A format string. + :return The number of bytes needed to store such a value. + """ ... def pack(fmt: str, v1: Any, *vn: Any) -> bytes: - """Verpak de waarden op basis van een string formaat. (inpakken) + """Pack values according to a format string. -Example: ``struct.pack('hf', 1, 3.1415)`` + Example: ``struct.pack('hf', 1, 3.1415)`` -:param fmt: De formaat tekenreeks. -:param v1: De eerste waarde. -:param *vn: De resterende waarden. -:return A bytes object encoding the values.""" + :param fmt: The format string. + :param v1: The first value. + :param *vn: The remaining values. + :return A bytes object encoding the values. + """ ... -def pack_into(fmt: str, buffer: WriteableBuffer, offset: int, v1: Any, *vn: Any) -> None: - """Verpak de waarden op basis van een string formaat. (inpakken) +def pack_into( + fmt: str, buffer: WriteableBuffer, offset: int, v1: Any, *vn: Any +) -> None: + """Pack values according to a format string. -Example: ``struct.pack_info('hf', buffer, 1, 3.1415)`` + Example: ``struct.pack_info('hf', buffer, 1, 3.1415)`` -:param fmt: De formaat tekenreeks. -:param buffer: De doelbuffer om in te schrijven. -:param offset: (Offset) De compensatie in de buffer. Kan negatief zijn om te tellen aan het einde van de buffer. -:param v1: De eerste waarde. -:param *vn: De resterende waarden.""" + :param fmt: The format string. + :param buffer: The target buffer to write into. + :param offset: The offset into the buffer. May be negative to count from the end of the buffer. + :param v1: The first value. + :param *vn: The remaining values. + """ ... def unpack(fmt: str, data: ReadableBuffer) -> Tuple[Any, ...]: - """Uitpakken van gegevens volgens een opmaakreeks. (uitpakken) + """Unpack data according to a format string. -Example: ``v1, v2 = struct.unpack('hf', buffer)`` + Example: ``v1, v2 = struct.unpack('hf', buffer)`` -:param fmt: De formaat tekenreeks. -:param data: (gegevens) De gegevens. -:return: A tuple of the unpacked values.""" + :param fmt: The format string. + :param data: The data. + :return: A tuple of the unpacked values. + """ ... -def unpack_from(fmt: str, buffer: ReadableBuffer, offset: int=0) -> Tuple: - """Uitpakken van gegevens van een buffer volgens een opmaak. (uitpakken van) +def unpack_from(fmt: str, buffer: ReadableBuffer, offset: int = 0) -> Tuple: + """Unpack data from a buffer according to a format string. -Example: ``v1, v2 = struct.unpack_from('hf', buffer)`` + Example: ``v1, v2 = struct.unpack_from('hf', buffer)`` -:param fmt: De formaat tekenreeks. -:param buffer: De bronbuffer om uit te lezen. -:param offset: (Offset) De compensatie in de buffer. Kan negatief zijn om te tellen aan het einde van de buffer. -:return: A tuple of the unpacked values.""" - ... \ No newline at end of file + :param fmt: The format string. + :param buffer: The source buffer to read from. + :param offset: The offset into the buffer. May be negative to count from the end of the buffer. + :return: A tuple of the unpacked values. + """ + ... diff --git a/lang/nl/typeshed/stdlib/sys.pyi b/lang/nl/typeshed/stdlib/sys.pyi index 90c34d5..320bac9 100644 --- a/lang/nl/typeshed/stdlib/sys.pyi +++ b/lang/nl/typeshed/stdlib/sys.pyi @@ -1,36 +1,43 @@ -"""Systeem specifieke functies""" +"""System specific functions""" + from typing import Any, Dict, List, NoReturn, TextIO, Tuple -def exit(retval: object=...) -> NoReturn: - """Beëindig het huidige programma met een bepaalde exit code. (afsluiten) +def exit(retval: object = ...) -> NoReturn: + """Terminate current program with a given exit code. -Example: ``sys.exit(1)`` + Example: ``sys.exit(1)`` -This function raises a ``SystemExit`` exception. If an argument is given, its -value given as an argument to ``SystemExit``. + This function raises a ``SystemExit`` exception. If an argument is given, its + value given as an argument to ``SystemExit``. -:param retval: De exit code of bericht.""" + :param retval: The exit code or message. + """ ... def print_exception(exc: Exception) -> None: - """Print een exception met traceback. (exceptie afdrukken) + """ + Print an exception with a traceback. + + Example: ``sys.print_exception(e)`` -Example: ``sys.print_exception(e)`` + :param exc: The exception to print -:param exc: De af te drukken uitzondering + This is simplified version of a function which appears in the + ``traceback`` module in CPython. + """ -This is simplified version of a function which appears in the -``traceback`` module in CPython.""" argv: List[str] -"""Een veranderlijke lijst met argumenten waarmee het huidige programma is gestart.""" +"""A mutable list of arguments the current program was started with.""" + byteorder: str -"""De byte volgorde van het systeem (``"little"`` of ``"big"``). (byte volgorde)""" +"""The byte order of the system (``"little"`` or ``"big"``).""" class _implementation: name: str version: Tuple[int, int, int] + implementation: _implementation -"""Object met informatie over de huidige Python implementatie. (implementatie) +"""Object with information about the current Python implementation. For MicroPython, it has following attributes: @@ -44,10 +51,13 @@ minimal ports). CPython mandates more attributes for this object, but the actual useful bare minimum is implemented in MicroPython. """ + maxsize: int """ -Maximale waarde die een native integer type kan aanhouden op het huidige platform, of de maximale waarde die kan worden vertegenwoordigd door MicroPython integer type, als het kleiner is dan platform max waarde (dat is het geval voor MicroPython poorten zonder -lange int ondersteuning). +Maximum value which a native integer type can hold on the current platform, +or maximum value representable by MicroPython integer type, if it's smaller +than platform max value (that is the case for MicroPython ports without +long int support). This attribute is useful for detecting "bitness" of a platform (32-bit vs 64-bit, etc.). It's recommended to not compare this attribute to some @@ -67,14 +77,17 @@ value directly, but instead count number of bits in it:: # (e.g. 31) due to peculiarities described above, so use "> 16", # "> 32", "> 64" style of comparisons. """ + modules: Dict[str, Any] -"""Woordenboek van geladen modules. +"""Dictionary of loaded modules. On some ports, it may not include builtin modules.""" + path: List[str] -"""Een aanpasbare lijst van mappen om te zoeken naar geïmporteerde modules. (pad)""" +"""A mutable list of directories to search for imported modules.""" + platform: str -"""Het platform waarop MicroPython actief is. +"""The platform that MicroPython is running on. For OS/RTOS ports, this is usually an identifier of the OS, e.g. ``"linux"``. For baremetal ports it is an identifier of a board, e.g. ``"pyboard"`` for @@ -84,11 +97,13 @@ distinguish one board from another. If you need to check whether your program runs on MicroPython (vs other Python implementation), use ``sys.implementation`` instead. """ + version: str -"""Python taalversie waar deze implementatie mee overeenstemt als tekenreeks. (versie)""" +"""Python language version that this implementation conforms to, as a string.""" + version_info: Tuple[int, int, int] -"""Python taalversie waaraan deze implementatie voldoet, als een tupel van ints. (versie informatie) +"""Python language version that this implementation conforms to, as a tuple of ints. Only the first three version numbers (major, minor, micro) are supported and they can be referenced only by index, not by name. -""" \ No newline at end of file +""" diff --git a/lang/nl/typeshed/stdlib/time.pyi b/lang/nl/typeshed/stdlib/time.pyi index 7c26199..598c483 100644 --- a/lang/nl/typeshed/stdlib/time.pyi +++ b/lang/nl/typeshed/stdlib/time.pyi @@ -1,112 +1,132 @@ -"""Meet tijd en voeg vertragingen toe aan programma's. (tijd)""" +"""Measure time and add delays to programs. +""" + from typing import Union def sleep(seconds: Union[int, float]) -> None: - """Vertraag een aantal seconden. (slapen) + """ + Delay a number of seconds. -Example: ``time.sleep(1)`` + Example: ``time.sleep(1)`` -:param seconds: (seconden) Het aantal seconden om voor te slapen. -Gebruik een floating-point nummer om te slapen voor een fractioneel aantal seconden.""" + :param seconds: The number of seconds to sleep for. + Use a floating-point number to sleep for a fractional number of seconds. + """ ... def sleep_ms(ms: int) -> None: - """Vertraging voor een bepaald aantal milliseconden. (slaap ms) + """ + Delay for given number of milliseconds. -Example: ``time.sleep_ms(1_000_000)`` + Example: ``time.sleep_ms(1_000_000)`` -:param ms: Het aantal milliseconden vertraging (>= 0).""" + :param ms: The number of milliseconds delay (>= 0). + """ ... def sleep_us(us: int) -> None: - """Vertraging voor een bepaald aantal microseconden. (slaap us) + """ + Delay for given number of microseconds. -Example: ``time.sleep_us(1000)`` + Example: ``time.sleep_us(1000)`` -:param us: Het aantal microseconden vertraging (>= 0).""" + :param us: The number of microseconds delay (>= 0). + """ ... def ticks_ms() -> int: - """Krijg een toenemende milliseconde teller met een willekeurig referentiepunt, dat omwikkeld na een waarde. + """ + Get an increasing, millisecond counter with an arbitrary reference point, + that wraps around after some value. -Example: ``time.ticks_ms()`` + Example: ``time.ticks_ms()`` -:return: The counter value in milliseconds.""" + :return: The counter value in milliseconds. + """ ... def ticks_us() -> int: - """Krijg een toenemende milliseconde teller met een willekeurig referentiepunt, dat omwikkeld na een waarde. + """ + Get an increasing, microsecond counter with an arbitrary reference point, + that wraps around after some value. -Example: ``time.ticks_us()`` + Example: ``time.ticks_us()`` -:return: The counter value in microseconds.""" + :return: The counter value in microseconds. + """ ... def ticks_add(ticks: int, delta: int) -> int: - """Waarde van de offset ticks door een bepaald getal, die ofwel positief ofwel -negatief kan zijn. (ticks toevoegen) + """ + Offset ticks value by a given number, which can be either positive or + negative. -Example: ``time.ticks_add(time.ticks_ms(), 200)`` + Example: ``time.ticks_add(time.ticks_ms(), 200)`` -Given a ticks value, this function allows to calculate ticks -value delta ticks before or after it, following modular-arithmetic -definition of tick values. + Given a ticks value, this function allows to calculate ticks + value delta ticks before or after it, following modular-arithmetic + definition of tick values. -:param ticks: (tikken) Een ticks waarde -:param delta: Een integer verschuiving + :param ticks: A ticks value + :param delta: An integer offset -Example:: + Example:: - # Find out what ticks value there was 100ms ago - print(ticks_add(time.ticks_ms(), -100)) + # Find out what ticks value there was 100ms ago + print(ticks_add(time.ticks_ms(), -100)) - # Calculate deadline for operation and test for it - deadline = ticks_add(time.ticks_ms(), 200) - while ticks_diff(deadline, time.ticks_ms()) > 0: - do_a_little_of_something() + # Calculate deadline for operation and test for it + deadline = ticks_add(time.ticks_ms(), 200) + while ticks_diff(deadline, time.ticks_ms()) > 0: + do_a_little_of_something() - # Find out TICKS_MAX used by this port - print(ticks_add(0, -1))""" + # Find out TICKS_MAX used by this port + print(ticks_add(0, -1)) + """ ... def ticks_diff(ticks1: int, ticks2: int) -> int: - """Meet het verschil in ticks tussen waarden die worden geretourneerd door ``time.ticks_ms()`` of ``ticks_us()``, als een ondertekende waarde die rond kan lopen. - -Example: ``time.ticks_diff(scheduled_time, now)`` - -:param ticks1: De waarde om van af te trekken -:param ticks2: De waarde om af te trekken - -The argument order is the same as for subtraction operator, -``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. - -``ticks_diff()`` is designed to accommodate various usage -patterns, among them: - -Polling with timeout. In this case, the order of events is known, and you -will deal only with positive results of :func:`time.ticks_diff()`:: - - # Wait for GPIO pin to be asserted, but at most 500us - start = time.ticks_us() - while pin.value() == 0: - if time.ticks_diff(time.ticks_us(), start) > 500: - raise TimeoutError - - -Scheduling events. In this case, :func:`time.ticks_diff()` result may be -negative if an event is overdue:: - - # This code snippet is not optimized - now = time.ticks_ms() - scheduled_time = task.scheduled_time() - if ticks_diff(scheduled_time, now) > 0: - print("Too early, let's nap") - sleep_ms(ticks_diff(scheduled_time, now)) - task.run() - elif ticks_diff(scheduled_time, now) == 0: - print("Right at time!") - task.run() - elif ticks_diff(scheduled_time, now) < 0: - print("Oops, running late, tell task to run faster!") - task.run(run_faster=True)""" - ... \ No newline at end of file + """ + Measure ticks difference between values returned from + ``time.ticks_ms()`` or ``ticks_us()``, as a signed value + which may wrap around. + + Example: ``time.ticks_diff(scheduled_time, now)`` + + :param ticks1: The value to subtract from + :param ticks2: The value to subtract + + The argument order is the same as for subtraction operator, + ``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. + + ``ticks_diff()`` is designed to accommodate various usage + patterns, among them: + + Polling with timeout. In this case, the order of events is known, and you + will deal only with positive results of :func:`time.ticks_diff()`:: + + # Wait for GPIO pin to be asserted, but at most 500us + start = time.ticks_us() + while pin.value() == 0: + if time.ticks_diff(time.ticks_us(), start) > 500: + raise TimeoutError + + + Scheduling events. In this case, :func:`time.ticks_diff()` result may be + negative if an event is overdue:: + + # This code snippet is not optimized + now = time.ticks_ms() + scheduled_time = task.scheduled_time() + if ticks_diff(scheduled_time, now) > 0: + print("Too early, let's nap") + sleep_ms(ticks_diff(scheduled_time, now)) + task.run() + elif ticks_diff(scheduled_time, now) == 0: + print("Right at time!") + task.run() + elif ticks_diff(scheduled_time, now) < 0: + print("Oops, running late, tell task to run faster!") + task.run(run_faster=True) + """ + ... diff --git a/lang/pl/typeshed/stdlib/gc.pyi b/lang/pl/typeshed/stdlib/gc.pyi index 5e50259..1370abf 100644 --- a/lang/pl/typeshed/stdlib/gc.pyi +++ b/lang/pl/typeshed/stdlib/gc.pyi @@ -1,68 +1,73 @@ -"""Steruj zbieraniem sieci""" +"""Control the garbage collector""" + from typing import overload def enable() -> None: - """Włącz automatyczne zbieranie śmieci.""" + """Enable automatic garbage collection.""" ... def disable() -> None: - """Wyłącz automatyczne zbieranie śmieci. + """Disable automatic garbage collection. -Heap memory can still be allocated, -and garbage collection can still be initiated manually using ``gc.collect``.""" + Heap memory can still be allocated, + and garbage collection can still be initiated manually using ``gc.collect``.""" def collect() -> None: - """Uruchom zbieranie śmieci.""" + """Run a garbage collection.""" ... def mem_alloc() -> int: - """Znajdź liczbę przydzielonych bajtów sterty pamięci RAM. + """Get the number of bytes of heap RAM that are allocated. -:return: The number of bytes allocated. + :return: The number of bytes allocated. -This function is MicroPython extension.""" + This function is MicroPython extension. + """ ... def mem_free() -> int: - """Znajdź liczbę bajtów dostępnej sterty pamięci RAM lub -1, jeśli ta liczba nie jest znana. + """Get the number of bytes of available heap RAM, or -1 if this amount is not known. -:return: The number of bytes free. + :return: The number of bytes free. -This function is MicroPython extension.""" + This function is MicroPython extension. + """ ... @overload def threshold() -> int: - """Zapytanie o dodatkowy próg przydziału GC. + """Query the additional GC allocation threshold. -:return: The GC allocation threshold. + :return: The GC allocation threshold. -This function is a MicroPython extension. CPython has a similar -function - ``set_threshold()``, but due to different GC -implementations, its signature and semantics are different.""" + This function is a MicroPython extension. CPython has a similar + function - ``set_threshold()``, but due to different GC + implementations, its signature and semantics are different. + """ ... @overload def threshold(amount: int) -> None: - """Ustaw próg dodatkowego przydziału GC. - -Normally, a collection is triggered only when a new allocation -cannot be satisfied, i.e. on an out-of-memory (OOM) condition. -If this function is called, in addition to OOM, a collection -will be triggered each time after ``amount`` bytes have been -allocated (in total, since the previous time such an amount of bytes -have been allocated). ``amount`` is usually specified as less than the -full heap size, with the intention to trigger a collection earlier than when the -heap becomes exhausted, and in the hope that an early collection will prevent -excessive memory fragmentation. This is a heuristic measure, the effect -of which will vary from application to application, as well as -the optimal value of the ``amount`` parameter. - -A value of -1 means a disabled allocation threshold. - -This function is a MicroPython extension. CPython has a similar -function - ``set_threshold()``, but due to different GC -implementations, its signature and semantics are different. - -:param amount: Liczba bajtów, po których powinno zostać uruchomione zbieranie śmieci.""" - ... \ No newline at end of file + """Set the additional GC allocation threshold. + + Normally, a collection is triggered only when a new allocation + cannot be satisfied, i.e. on an out-of-memory (OOM) condition. + If this function is called, in addition to OOM, a collection + will be triggered each time after ``amount`` bytes have been + allocated (in total, since the previous time such an amount of bytes + have been allocated). ``amount`` is usually specified as less than the + full heap size, with the intention to trigger a collection earlier than when the + heap becomes exhausted, and in the hope that an early collection will prevent + excessive memory fragmentation. This is a heuristic measure, the effect + of which will vary from application to application, as well as + the optimal value of the ``amount`` parameter. + + A value of -1 means a disabled allocation threshold. + + This function is a MicroPython extension. CPython has a similar + function - ``set_threshold()``, but due to different GC + implementations, its signature and semantics are different. + + :param amount: The number of bytes after which a garbage collection should be triggered. + """ + ... diff --git a/lang/pl/typeshed/stdlib/log.pyi b/lang/pl/typeshed/stdlib/log.pyi index 4aa875f..c9870fa 100644 --- a/lang/pl/typeshed/stdlib/log.pyi +++ b/lang/pl/typeshed/stdlib/log.pyi @@ -1,89 +1,104 @@ -"""Zaloguj dane do swojego micro:bita V2.""" +"""Log data to your micro:bit V2.""" + from typing import Literal, Mapping, Optional, Union, overload + MILLISECONDS = 1 -"""Format znacznika czasu w milisekundach.""" +"""Milliseconds timestamp format.""" + SECONDS = 10 -"""Format znacznika czasu w sekundach.""" +"""Seconds timestamp format.""" + MINUTES = 600 -"""Format znacznika czasu w minutach.""" +"""Minutes timestamp format.""" + HOURS = 36000 -"""Format znacznika czasu w godzinach.""" +"""Hours timestamp format.""" + DAYS = 864000 -"""Format znacznika czasu w dniach.""" +"""Days timestamp format.""" -def set_labels(*labels: str, timestamp: Optional[Literal[1, 10, 36000, 864000]]=SECONDS) -> None: - """Ustaw nagłówek pliku dziennika. +def set_labels( + *labels: str, timestamp: Optional[Literal[1, 10, 36000, 864000]] = SECONDS +) -> None: + """Set up the log file header. -Example: ``log.set_labels('X', 'Y', 'Z', timestamp=log.MINUTES)`` + Example: ``log.set_labels('X', 'Y', 'Z', timestamp=log.MINUTES)`` -Ideally this function should be called a single time, before any data is -logged, to configure the data table header once. + Ideally this function should be called a single time, before any data is + logged, to configure the data table header once. -If a log file already exists when the program starts, or if this function -is called multiple times, it will check the labels already defined in the -log file. If this function call contains any new labels not already -present, it will generate a new header row with the additional columns. + If a log file already exists when the program starts, or if this function + is called multiple times, it will check the labels already defined in the + log file. If this function call contains any new labels not already + present, it will generate a new header row with the additional columns. -By default the first column contains a timestamp for each row. The time -unit can be selected via the timestamp argument. + By default the first column contains a timestamp for each row. The time + unit can be selected via the timestamp argument. -:param *labels: Dowolna liczba argumentów pozycyjnych, każdy odpowiadający wpisowi w nagłówku dziennika. -:param timestamp: Wybierz jednostkę znacznika czasu, która będzie automatycznie dodana jako pierwsza kolumna w każdym wierszu. Wartości znacznika czasu mogą być jedną z ``log.MILLISECONDS``, ``log.SECONDS``, ``log.MINUTES``, ``log.HOURS``, ``log.DAYS`` lub ``None``, aby wyłączyć znacznik czasu. Wartością domyślną jest ``log.SECONDS``.""" + :param *labels: Any number of positional arguments, each corresponding to an entry in the log header. + :param timestamp: Select the timestamp unit that will be automatically added as the first column in every row. Timestamp values can be one of ``log.MILLISECONDS``, ``log.SECONDS``, ``log.MINUTES``, ``log.HOURS``, ``log.DAYS`` or ``None`` to disable the timestamp. The default value is ``log.SECONDS``. + """ ... @overload -def add(data_dictionary: Optional[Mapping[str, Union[str, int, float]]]) -> None: - """Dodaj wiersz danych do dziennika poprzez podanie słownika nagłówków i wartości. +def add( + data_dictionary: Optional[Mapping[str, Union[str, int, float]]], +) -> None: + """Add a data row to the log by passing a dictionary of headers and values. -Example: ``log.add({ 'temp': temperature() })`` + Example: ``log.add({ 'temp': temperature() })`` -Each call to this function adds a row to the log. + Each call to this function adds a row to the log. -New labels not previously specified via the set_labels function, or by a -previous call to this function, will trigger a new header entry to be added -to the log with the extra labels. + New labels not previously specified via the set_labels function, or by a + previous call to this function, will trigger a new header entry to be added + to the log with the extra labels. -Labels previously specified and not present in a call to this function will -be skipped with an empty value in the log row. + Labels previously specified and not present in a call to this function will + be skipped with an empty value in the log row. -:param data_dictionary: Dane do logowania jako słownik z kluczem dla każdego nagłówka.""" + :param data_dictionary: The data to log as a dictionary with a key for each header. + """ ... @overload def add(**kwargs: Union[str, int, float]) -> None: - """Dodaj wiersz danych do dziennika używając argumentów słów kluczowych. (dodaj) + """Add a data row to the log using keyword arguments. -Example: ``log.add(temp=temperature())`` + Example: ``log.add(temp=temperature())`` -Each call to this function adds a row to the log. + Each call to this function adds a row to the log. -New labels not previously specified via the set_labels function, or by a -previous call to this function, will trigger a new header entry to be added -to the log with the extra labels. + New labels not previously specified via the set_labels function, or by a + previous call to this function, will trigger a new header entry to be added + to the log with the extra labels. -Labels previously specified and not present in a call to this function will -be skipped with an empty value in the log row.""" + Labels previously specified and not present in a call to this function will + be skipped with an empty value in the log row. + """ ... def delete(full=False): - """Usuwa zawartość wpisu, w tym nagłówki. + """Deletes the contents of the log, including headers. -Example: ``log.delete()`` + Example: ``log.delete()`` -To add the log headers again the ``set_labels`` function should to be called after this function. + To add the log headers again the ``set_labels`` function should to be called after this function. -There are two erase modes; “full” completely removes the data from the physical storage, -and “fast” invalidates the data without removing it. + There are two erase modes; “full” completely removes the data from the physical storage, + and “fast” invalidates the data without removing it. -:param full: ``True`` wybiera usunięcie "pełne" i ``False`` wybiera metodę "szybkiego" usunięcia.""" + :param full: ``True`` selects a “full” erase and ``False`` selects the “fast” erase method. + """ ... def set_mirroring(serial: bool): - """Skonfiguruj lustrzane odbicie logowania danych do wyjścia szeregowego. + """Configure mirroring of the data logging activity to the serial output. -Example: ``log.set_mirroring(True)`` + Example: ``log.set_mirroring(True)`` -Serial mirroring is disabled by default. When enabled, it will print to serial each row logged into the log file. + Serial mirroring is disabled by default. When enabled, it will print to serial each row logged into the log file. -:param serial: ``True`` umożliwia odbicie lustrzane danych na szeregowe wyjście.""" - ... \ No newline at end of file + :param serial: ``True`` enables mirroring data to the serial output. + """ + ... diff --git a/lang/pl/typeshed/stdlib/machine.pyi b/lang/pl/typeshed/stdlib/machine.pyi index 70046a9..2e82f5b 100644 --- a/lang/pl/typeshed/stdlib/machine.pyi +++ b/lang/pl/typeshed/stdlib/machine.pyi @@ -1,84 +1,97 @@ -"""Narzędzia niskiego poziomu.""" +"""Low-level utilities. +""" from typing import Any from .microbit import MicroBitDigitalPin def unique_id() -> bytes: - """Pobierz ciąg bajtów z unikatowym identyfikatorem płytki. + """Get a byte string with a unique identifier of a board. -Example: ``machine.unique_id()`` + Example: ``machine.unique_id()`` -:return: An identifier that varies from one board instance to another.""" + :return: An identifier that varies from one board instance to another. + """ ... def reset() -> None: - """Zresetuj urządzenie w sposób podobny do naciśnięcia zewnętrznego przycisku RESET. + """Reset the device in a manner similar to pushing the external RESET button. -Example: ``machine.reset()``""" + Example: ``machine.reset()`` + """ ... def freq() -> int: - """Uzyskaj częstotliwość procesora w hercach + """Get the CPU frequency in hertz. -Example: ``machine.freq()`` + Example: ``machine.freq()`` -:return: The CPU frequency.""" + :return: The CPU frequency. + """ ... def disable_irq() -> Any: - """Wyłącz żądania przerwań. + """Disable interrupt requests. -Example: ``interrupt_state = machine.disable_irq()`` + Example: ``interrupt_state = machine.disable_irq()`` -:return: the previous IRQ state which should be considered an opaque value + :return: the previous IRQ state which should be considered an opaque value -The return value should be passed to the ``enable_irq`` function to restore -interrupts to their original state.""" + The return value should be passed to the ``enable_irq`` function to restore + interrupts to their original state. + """ ... def enable_irq(state: Any) -> None: - """Ponownie włącz żądania przerwań. + """Re-enable interrupt requests. -Example: ``machine.enable_irq(interrupt_state)`` + Example: ``machine.enable_irq(interrupt_state)`` -:param state: Wartość, która została zwrócona z ostatniego wywołania funkcji ``disable_irq``.""" + :param state: The value that was returned from the most recent call to the ``disable_irq`` function. + """ ... -def time_pulse_us(pin: MicroBitDigitalPin, pulse_level: int, timeout_us: int=1000000) -> int: - """Czas pulsowania na pinie. +def time_pulse_us( + pin: MicroBitDigitalPin, pulse_level: int, timeout_us: int = 1000000 +) -> int: + """Time a pulse on a pin. -Example: ``time_pulse_us(pin0, 1)`` + Example: ``time_pulse_us(pin0, 1)`` -If the current input value of the pin is different to ``pulse_level``, the -function first waits until the pin input becomes equal to -``pulse_level``, then times the duration that the pin is equal to -``pulse_level``. If the pin is already equal to ``pulse_level`` then timing -starts straight away. + If the current input value of the pin is different to ``pulse_level``, the + function first waits until the pin input becomes equal to + ``pulse_level``, then times the duration that the pin is equal to + ``pulse_level``. If the pin is already equal to ``pulse_level`` then timing + starts straight away. -:param pin: Pin do użycia -:param pulse_level: 0 do czasu niskiego pulsu lub 1 do czasu wysokiego pulsu -:param timeout_us: Mikrosekundowy limit czasu -:return: The duration of the pulse in microseconds, or -1 for a timeout waiting for the level to match ``pulse_level``, or -2 on timeout waiting for the pulse to end""" + :param pin: The pin to use + :param pulse_level: 0 to time a low pulse or 1 to time a high pulse + :param timeout_us: A microsecond timeout + :return: The duration of the pulse in microseconds, or -1 for a timeout waiting for the level to match ``pulse_level``, or -2 on timeout waiting for the pulse to end + """ ... class mem: - """Klasa dla widoków pamięci ``mem8``, ``mem16`` i ``mem32``.""" + """The class for the ``mem8``, ``mem16`` and ``mem32`` memory views.""" def __getitem__(self, address: int) -> int: - """Uzyskaj dostęp do wartości z pamięci. + """Access a value from memory. -:param address: Adres pamięci. -:return: The value at that address as an integer.""" + :param address: The memory address. + :return: The value at that address as an integer. + """ ... - def __setitem__(self, address: int, value: int) -> None: - """Ustaw wartość dla podanego adresu. + """Set a value at the given address. -:param address: Adres pamięci. -:param value: Wartość całkowita do ustawiania.""" + :param address: The memory address. + :param value: The integer value to set. + """ ... + mem8: mem -"""8-bitowy widok pamięci.""" +"""8-bit (byte) view of memory.""" + mem16: mem -"""16-bitowy widok pamięci.""" +"""16-bit view of memory.""" + mem32: mem -"""32-bitowy widok pamięci.""" \ No newline at end of file +"""32-bit view of memory.""" diff --git a/lang/pl/typeshed/stdlib/math.pyi b/lang/pl/typeshed/stdlib/math.pyi index e61fbe3..f82d4de 100644 --- a/lang/pl/typeshed/stdlib/math.pyi +++ b/lang/pl/typeshed/stdlib/math.pyi @@ -1,246 +1,273 @@ -"""Funkcje matematyczne.""" +"""Mathematical functions. +""" + from typing import Tuple def acos(x: float) -> float: - """Obliczyć odwrotność cosinusa. + """Calculate the inverse cosine. -Example: ``math.acos(1)`` + Example: ``math.acos(1)`` -:param x: Liczba -:return: The inverse cosine of ``x``""" + :param x: A number + :return: The inverse cosine of ``x`` + """ ... def asin(x: float) -> float: - """Obliczyć odwrotność sinusa. + """Calculate the inverse sine. -Example: ``math.asin(0)`` + Example: ``math.asin(0)`` -:param x: Liczba -:return: The inverse sine of ``x``""" + :param x: A number + :return: The inverse sine of ``x`` + """ ... def atan(x: float) -> float: - """Oblicz odwrotność tangensa. + """Calculate the inverse tangent. -Example: ``math.atan(0)`` + Example: ``math.atan(0)`` -:param x: Liczba -:return: The inverse tangent of ``x``""" + :param x: A number + :return: The inverse tangent of ``x`` + """ ... def atan2(y: float, x: float) -> float: - """Oblicz wartość główną odwrotności tangensa ``y/x``. + """Calculate the principal value of the inverse tangent of ``y/x``. -Example: ``math.atan2(0, -1)`` + Example: ``math.atan2(0, -1)`` -:param y: Liczba -:param x: Liczba -:return: The principal value of the inverse tangent of ``y/x``""" + :param y: A number + :param x: A number + :return: The principal value of the inverse tangent of ``y/x`` + """ ... def ceil(x: float) -> float: - """Zaokrąglij liczbę w kierunku dodatniej nieskończoności. + """Round a number towards positive infinity. -Example: ``math.ceil(0.1)`` + Example: ``math.ceil(0.1)`` -:param x: Liczba -:return: ``x`` rounded towards positive infinity.""" + :param x: A number + :return: ``x`` rounded towards positive infinity. + """ ... def copysign(x: float, y: float) -> float: - """Oblicz ``x`` ze znakiem ``y``. + """Calculate ``x`` with the sign of ``y``. -Example: ``math.copysign(1, -1)`` + Example: ``math.copysign(1, -1)`` -:param x: Liczba -:param y: Źródło znaku dla wartości zwracanej -:return: ``x`` with the sign of ``y``""" + :param x: A number + :param y: The source of the sign for the return value + :return: ``x`` with the sign of ``y`` + """ ... def cos(x: float) -> float: - """Oblicz cosinus ``x``. + """Calculate the cosine of ``x``. -Example: ``math.cos(0)`` + Example: ``math.cos(0)`` -:param x: Liczba -:return: The cosine of ``x``""" + :param x: A number + :return: The cosine of ``x`` + """ ... def degrees(x: float) -> float: - """Konwertuj radiany na stopnie. + """Convert radians to degrees. -Example: ``math.degrees(2 * math.pi)`` + Example: ``math.degrees(2 * math.pi)`` -:param x: Wartość w radianach -:return: The value converted to degrees""" + :param x: A value in radians + :return: The value converted to degrees""" ... def exp(x: float) -> float: - """Oblicz potęgę ``x``. + """Calculate the exponential of ``x``. -Example: ``math.exp(1)`` + Example: ``math.exp(1)`` -:param x: Liczba -:return: The exponential of ``x``.""" + :param x: A number + :return: The exponential of ``x``. + """ ... def fabs(x: float) -> float: - """Zwróć wartość bezwzględną ``x``. + """Return the absolute value of ``x``. -Example: ``math.fabs(-0.1)`` + Example: ``math.fabs(-0.1)`` -:param x: Liczba -:return: The absolute value of ``x``""" + :param x: A number + :return: The absolute value of ``x`` + """ ... def floor(x: float) -> int: - """Zaokrąglij liczbę w kierunku ujemnej nieskończoności. + """Round a number towards negative infinity. -Example: ``math.floor(0.9)`` + Example: ``math.floor(0.9)`` -:param x: Liczba -:return: ``x`` rounded towards negative infinity.""" + :param x: A number + :return: ``x`` rounded towards negative infinity. + """ ... def fmod(x: float, y: float) -> float: - """Oblicz resztę z ``x/y``. + """Calculate the remainder of ``x/y``. -Example: ``math.fmod(10, 3)`` + Example: ``math.fmod(10, 3)`` -:param x: Licznik -:param y: Mianownik""" + :param x: The numerator + :param y: The denominator + """ ... def frexp(x: float) -> Tuple[float, int]: - """Rozkłada liczbę zmiennopozycyjną na mantysę i wykładnik. + """Decomposes a floating-point number into its mantissa and exponent. -Example: ``mantissa, exponent = math.frexp(2)`` + Example: ``mantissa, exponent = math.frexp(2)`` -The returned value is the tuple ``(m, e)`` such that ``x == m * 2**e`` -exactly. If ``x == 0`` then the function returns ``(0.0, 0)``, otherwise -the relation ``0.5 <= abs(m) < 1`` holds. + The returned value is the tuple ``(m, e)`` such that ``x == m * 2**e`` + exactly. If ``x == 0`` then the function returns ``(0.0, 0)``, otherwise + the relation ``0.5 <= abs(m) < 1`` holds. -:param x: Liczba zmiennopozycyjna -:return: A tuple of length two containing its mantissa then exponent""" + :param x: A floating-point number + :return: A tuple of length two containing its mantissa then exponent + """ ... def isfinite(x: float) -> bool: - """Sprawdź, czy wartość jest skończona. + """Check if a value is finite. -Example: ``math.isfinite(float('inf'))`` + Example: ``math.isfinite(float('inf'))`` -:param x: Liczba. -:return: ``True`` if ``x`` is finite, ``False`` otherwise.""" + :param x: A number. + :return: ``True`` if ``x`` is finite, ``False`` otherwise. + """ ... def isinf(x: float) -> bool: - """Sprawdź, czy wartość jest nieskończona. + """Check if a value is infinite. -Example: ``math.isinf(float('-inf'))`` + Example: ``math.isinf(float('-inf'))`` -:param x: Liczba. -:return: ``True`` if ``x`` is infinite, ``False`` otherwise.""" + :param x: A number. + :return: ``True`` if ``x`` is infinite, ``False`` otherwise. + """ ... def isnan(x: float) -> bool: - """Sprawdź, czy wartość nie jest liczbą (NaN). + """Check if a value is not-a-number (NaN). -Example: ``math.isnan(float('nan'))`` + Example: ``math.isnan(float('nan'))`` -:param x: Liczba -:return: ``True`` if ``x`` is not-a-number (NaN), ``False`` otherwise.""" + :param x: A number + :return: ``True`` if ``x`` is not-a-number (NaN), ``False`` otherwise.""" ... def ldexp(x: float, exp: int) -> float: - """Oblicz ``x * (2**exp)``. + """Calculate ``x * (2**exp)``. -Example: ``math.ldexp(0.5, 2)`` + Example: ``math.ldexp(0.5, 2)`` -:param x: Liczba -:param exp: Wykładnik całkowity -:return: ``x * (2**exp)``""" + :param x: A number + :param exp: Integer exponent + :return: ``x * (2**exp)`` + """ ... -def log(x: float, base: float=e) -> float: - """Oblicz logarytm z ``x`` przy podanej podstawie (domyślnie loggorytm naturalny). +def log(x: float, base: float = e) -> float: + """Calculate the logarithm of ``x`` to the given base (defaults to natural logorithm). -Example: ``math.log(math.e)`` + Example: ``math.log(math.e)`` -With one argument, return the natural logarithm of x (to base e). + With one argument, return the natural logarithm of x (to base e). -With two arguments, return the logarithm of x to the given base, calculated as ``log(x)/log(base)``. + With two arguments, return the logarithm of x to the given base, calculated as ``log(x)/log(base)``. -:param x: Liczba -:param base: Podstawa do użycia -:return: The natural logarithm of ``x``""" + :param x: A number + :param base: The base to use + :return: The natural logarithm of ``x`` + """ ... def modf(x: float) -> Tuple[float, float]: - """Oblicz część ułamkową i całkowitą z ``x``. + """Calculate the fractional and integral parts of ``x``. -Example: ``fractional, integral = math.modf(1.5)`` + Example: ``fractional, integral = math.modf(1.5)`` -:param x: Liczba -:return: A tuple of two floats representing the fractional then integral parts of ``x``. + :param x: A number + :return: A tuple of two floats representing the fractional then integral parts of ``x``. -Both the fractional and integral values have the same sign as ``x``.""" + Both the fractional and integral values have the same sign as ``x``. + """ ... def pow(x: float, y: float) -> float: - """Zwraca ``x`` do potęgi ``y``. + """Returns ``x`` to the power of ``y``. -Example: ``math.pow(4, 0.5)`` + Example: ``math.pow(4, 0.5)`` -:param x: Liczba -:param y: Wykładnik -:return: ``x`` to the power of ``y``""" + :param x: A number + :param y: The exponent + :return: ``x`` to the power of ``y`` + """ ... def radians(x: float) -> float: - """Konwertuj stopnie na radiany. + """Convert a degrees to radians. -Example: ``math.radians(360)`` + Example: ``math.radians(360)`` -:param x: Wartość w stopniach -:return: The value converted to radians""" + :param x: A value in degrees + :return: The value converted to radians + """ ... def sin(x: float) -> float: - """Oblicz sinus ``x``. + """Calculate the sine of ``x``. -Example: ``math.sin(math.pi/2)`` + Example: ``math.sin(math.pi/2)`` -:param x: Liczba -:return: The sine of ``x``""" + :param x: A number + :return: The sine of ``x`` + """ ... def sqrt(x: float) -> float: - """Oblicz pierwiastek kwadratowy z ``x``. + """Calculate the square root of ``x``. -Example: ``math.sqrt(4)`` + Example: ``math.sqrt(4)`` -:param x: Liczba -:return: The square root of ``x``""" + :param x: A number + :return: The square root of ``x`` + """ ... def tan(x: float) -> float: - """Oblicz tangens z ``x``. + """Calculate the tangent of ``x``. -Example: ``math.tan(0)`` + Example: ``math.tan(0)`` -:param x: Liczba -:return: The tangent of ``x``.""" + :param x: A number + :return: The tangent of ``x``. + """ ... def trunc(x: float) -> int: - """Zaokrąglij liczbę w kierunku 0. + """Round a number towards 0. -Example: ``math.trunc(-0.9)`` + Example: ``math.trunc(-0.9)`` -:param x: Liczba -:return: ``x`` rounded towards zero.""" + :param x: A number + :return: ``x`` rounded towards zero. + """ ... + e: float -"""Podstawa logarytmu naturalnego""" +"""Base of the natural logarithm""" + pi: float -"""Stosunek obwodu okręgu do jego średnicy""" \ No newline at end of file +"""The ratio of a circle's circumference to its diameter""" diff --git a/lang/pl/typeshed/stdlib/microbit/__init__.pyi b/lang/pl/typeshed/stdlib/microbit/__init__.pyi index a40d3d6..f12158f 100644 --- a/lang/pl/typeshed/stdlib/microbit/__init__.pyi +++ b/lang/pl/typeshed/stdlib/microbit/__init__.pyi @@ -1,6 +1,11 @@ -"""Piny, obrazy, dźwięki, temperatura i głośność.""" +"""Pins, images, sounds, temperature and volume. +""" + from typing import Any, Callable, List, Optional, Tuple, Union, overload + from _typeshed import ReadableBuffer + +# V2 only from . import accelerometer as accelerometer from . import audio as audio from . import compass as compass @@ -11,701 +16,831 @@ from . import speaker as speaker from . import spi as spi from . import uart as uart -def run_every(callback: Optional[Callable[[], None]]=None, days: int=0, h: int=0, min: int=0, s: int=0, ms: int=0) -> Callable[[Callable[[], None]], Callable[[], None]]: - """Zaplanuj uruchomienie funkcji w przedziale określonym przez argumenty czasu **tylko V2**. +def run_every( + callback: Optional[Callable[[], None]] = None, + days: int = 0, + h: int = 0, + min: int = 0, + s: int = 0, + ms: int = 0, +) -> Callable[[Callable[[], None]], Callable[[], None]]: + """Schedule to run a function at the interval specified by the time arguments **V2 only**. -Example: ``run_every(my_logging, min=5)`` + Example: ``run_every(my_logging, min=5)`` -``run_every`` can be used in two ways: + ``run_every`` can be used in two ways: -As a Decorator - placed on top of the function to schedule. For example:: + As a Decorator - placed on top of the function to schedule. For example:: - @run_every(h=1, min=20, s=30, ms=50) - def my_function(): - # Do something here + @run_every(h=1, min=20, s=30, ms=50) + def my_function(): + # Do something here -As a Function - passing the callback as a positional argument. For example:: + As a Function - passing the callback as a positional argument. For example:: - def my_function(): - # Do something here - run_every(my_function, s=30) + def my_function(): + # Do something here + run_every(my_function, s=30) -Each argument corresponds to a different time unit and they are additive. -So ``run_every(min=1, s=30)`` schedules the callback every minute and a half. + Each argument corresponds to a different time unit and they are additive. + So ``run_every(min=1, s=30)`` schedules the callback every minute and a half. -When an exception is thrown inside the callback function it deschedules the -function. To avoid this you can catch exceptions with ``try/except``. + When an exception is thrown inside the callback function it deschedules the + function. To avoid this you can catch exceptions with ``try/except``. -:param callback: Funkcja wywoływana w podanym przedziale. Pomiń, jeśli używasz jako dekorator. -:param days: Ustawia oznaczenie dnia dla harmonogramu. -:param h: Ustawia znak godziny dla harmonogramu. -:param min: Ustawia znak minuty dla harmonogramu. -:param s: Ustawia znak sekundy dla harmonogramu. -:param ms: Ustawia znak milisekundy dla harmonogramu.""" + :param callback: Function to call at the provided interval. Omit when using as a decorator. + :param days: Sets the day mark for the scheduling. + :param h: Sets the hour mark for the scheduling. + :param min: Sets the minute mark for the scheduling. + :param s: Sets the second mark for the scheduling. + :param ms: Sets the millisecond mark for the scheduling. + """ def panic(n: int) -> None: - """Wejdź w tryb paniki. + """Enter a panic mode. -Example: ``panic(127)`` + Example: ``panic(127)`` -:param n: Dowolna liczba całkowita <= 255 dla wskazania statusu. + :param n: An arbitrary integer <= 255 to indicate a status. -Requires restart.""" + Requires restart. + """ def reset() -> None: - """Uruchom ponownie płytkę.""" + """Restart the board.""" + @overload def scale(value: float, from_: Tuple[float, float], to: Tuple[int, int]) -> int: - """Konwertuje wartość z zakresu do zakresu liczb całkowitych. + """Converts a value from a range to an integer range. -Example: ``volume = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255))`` + Example: ``volume = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255))`` -For example, to convert an accelerometer X value to a speaker volume. + For example, to convert an accelerometer X value to a speaker volume. -If one of the numbers in the ``to`` parameter is a floating point -(i.e a decimal number like ``10.0``), this function will return a -floating point number. + If one of the numbers in the ``to`` parameter is a floating point + (i.e a decimal number like ``10.0``), this function will return a + floating point number. - temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0)) + temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0)) -:param value: Liczba do konwersji. -:param from_: Krotka do zdefiniowania zakresu dla konwersji z. -:param to: Krotka do zdefiniowania zakresu dla konwersji do. -:return: The ``value`` converted to the ``to`` range.""" + :param value: A number to convert. + :param from_: A tuple to define the range to convert from. + :param to: A tuple to define the range to convert to. + :return: The ``value`` converted to the ``to`` range. + """ @overload def scale(value: float, from_: Tuple[float, float], to: Tuple[float, float]) -> float: - """Konwertuje wartość z zakresu do zakresu o zmiennopozycyjnego. + """Converts a value from a range to a floating point range. -Example: ``temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0))`` + Example: ``temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0))`` -For example, to convert temperature from a Celsius scale to Fahrenheit. + For example, to convert temperature from a Celsius scale to Fahrenheit. -If one of the numbers in the ``to`` parameter is a floating point -(i.e a decimal number like ``10.0``), this function will return a -floating point number. -If they are both integers (i.e ``10``), it will return an integer:: + If one of the numbers in the ``to`` parameter is a floating point + (i.e a decimal number like ``10.0``), this function will return a + floating point number. + If they are both integers (i.e ``10``), it will return an integer:: - returns_int = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255)) + returns_int = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255)) -:param value: Liczba do konwersji. -:param from_: Krotka do zdefiniowania zakresu dla konwersji z. -:param to: Krotka do zdefiniowania zakresu, na jaki konwertować. -:return: The ``value`` converted to the ``to`` range.""" + :param value: A number to convert. + :param from_: A tuple to define the range to convert from. + :param to: A tuple to define the range to convert to. + :return: The ``value`` converted to the ``to`` range. + """ def sleep(n: float) -> None: - """Poczekaj ``n`` milisekund. + """Wait for ``n`` milliseconds. -Example: ``sleep(1000)`` + Example: ``sleep(1000)`` -:param n: Liczba milisekund oczekiwania + :param n: The number of milliseconds to wait -One second is 1000 milliseconds, so:: + One second is 1000 milliseconds, so:: - microbit.sleep(1000) + microbit.sleep(1000) -will pause the execution for one second.""" + will pause the execution for one second. + """ def running_time() -> int: - """Uzyskaj czas pracy płytki. + """Get the running time of the board. -:return: The number of milliseconds since the board was switched on or restarted.""" + :return: The number of milliseconds since the board was switched on or restarted. + """ def temperature() -> int: - """Uzyskaj temperaturę micro:bita w stopniach Celsjusza.""" + """Get the temperature of the micro:bit in degrees Celsius.""" def set_volume(v: int) -> None: - """Ustawia głośność. + """Sets the volume. -Example: ``set_volume(127)`` + Example: ``set_volume(127)`` -:param v: wartość między 0 (niska) a 255 (wysoka). + :param v: a value between 0 (low) and 255 (high). -Out of range values will be clamped to 0 or 255. + Out of range values will be clamped to 0 or 255. -**V2** only.""" + **V2** only. + """ ... class Button: - """Klasa dla przycisków ``button_a`` i ``button_b``.""" + """The class for the buttons ``button_a`` and ``button_b``.""" def is_pressed(self) -> bool: - """Sprawdź, czy przycisk jest naciśnięty. + """Check if the button is pressed. -:return: ``True`` if the specified button ``button`` is pressed, and ``False`` otherwise.""" + :return: ``True`` if the specified button ``button`` is pressed, and ``False`` otherwise. + """ ... - def was_pressed(self) -> bool: - """Sprawdź, czy przycisk został naciśnięty od momentu uruchomienia urządzenia lub kiedy ta metoda została wywołana. + """Check if the button was pressed since the device started or the last time this method was called. -Calling this method will clear the press state so -that the button must be pressed again before this method will return -``True`` again. + Calling this method will clear the press state so + that the button must be pressed again before this method will return + ``True`` again. -:return: ``True`` if the specified button ``button`` was pressed, and ``False`` otherwise""" + :return: ``True`` if the specified button ``button`` was pressed, and ``False`` otherwise + """ ... - def get_presses(self) -> int: - """Pobierz sumę naciśnięć przycisków i zresetuje tę sumę -do zera przed powrotem. + """Get the running total of button presses, and resets this total + to zero before returning. -:return: The number of presses since the device started or the last time this method was called""" + :return: The number of presses since the device started or the last time this method was called + """ ... + button_a: Button -"""Lewy przycisk ``Button`` obiekt.""" +"""The left button ``Button`` object.""" + button_b: Button -"""Prawy przycisk ``Button`` obiekt.""" +"""The right button ``Button`` object.""" class MicroBitDigitalPin: - """Cyfrowy pin. + """A digital pin. + + Some pins support analog and touch features using the ``MicroBitAnalogDigitalPin`` and ``MicroBitTouchPin`` subclasses. + """ -Some pins support analog and touch features using the ``MicroBitAnalogDigitalPin`` and ``MicroBitTouchPin`` subclasses.""" NO_PULL: int PULL_UP: int PULL_DOWN: int - def read_digital(self) -> int: - """Uzyskaj cyfrową wartość pinu. + """Get the digital value of the pin. -Example: ``value = pin0.read_digital()`` + Example: ``value = pin0.read_digital()`` -:return: 1 if the pin is high, and 0 if it's low.""" + :return: 1 if the pin is high, and 0 if it's low. + """ ... - def write_digital(self, value: int) -> None: - """Ustaw cyfrową wartość pinu. + """Set the digital value of the pin. -Example: ``pin0.write_digital(1)`` + Example: ``pin0.write_digital(1)`` -:param value: 1, aby ustawić wysoką wartość pinu lub 0, aby ustawić niską wartość pinu""" + :param value: 1 to set the pin high or 0 to set the pin low""" ... - def set_pull(self, value: int) -> None: - """Ustaw stan ciągnięcia na jedną z trzech możliwych wartości: ``PULL_UP``, ``PULL_DOWN`` lub ``NO_PULL``. + """Set the pull state to one of three possible values: ``PULL_UP``, ``PULL_DOWN`` or ``NO_PULL``. -Example: ``pin0.set_pull(pin0.PULL_UP)`` + Example: ``pin0.set_pull(pin0.PULL_UP)`` -:param value: Stan ciągnięcia z odpowiedniego pinu, np. ``pin0.PULL_UP``.""" + :param value: The pull state from the relevant pin, e.g. ``pin0.PULL_UP``. + """ ... - def get_pull(self) -> int: - """Uzyskaj stan cignięcia na pinie. + """Get the pull state on a pin. -Example: ``pin0.get_pull()`` + Example: ``pin0.get_pull()`` -:return: ``NO_PULL``, ``PULL_DOWN``, or ``PULL_UP`` + :return: ``NO_PULL``, ``PULL_DOWN``, or ``PULL_UP`` -These are set using the ``set_pull()`` method or automatically configured -when a pin mode requires it.""" + These are set using the ``set_pull()`` method or automatically configured + when a pin mode requires it. + """ ... - def get_mode(self) -> str: - """Zwraca tryb pinu. + """Returns the pin mode. -Example: ``pin0.get_mode()`` + Example: ``pin0.get_mode()`` -When a pin is used for a specific function, like -writing a digital value, or reading an analog value, the pin mode -changes. + When a pin is used for a specific function, like + writing a digital value, or reading an analog value, the pin mode + changes. -:return: ``"unused"``, ``"analog"``, ``"read_digital"``, ``"write_digital"``, ``"display"``, ``"button"``, ``"music"``, ``"audio"``, ``"touch"``, ``"i2c"``, or ``"spi"``""" + :return: ``"unused"``, ``"analog"``, ``"read_digital"``, ``"write_digital"``, ``"display"``, ``"button"``, ``"music"``, ``"audio"``, ``"touch"``, ``"i2c"``, or ``"spi"`` + """ ... - def write_analog(self, value: int) -> None: - """Wysyłaj sygnał PWM na pin, z cyklem pracy proporcjonalnym do ``value``. - -Example: ``pin0.write_analog(254)`` + """Output a PWM signal on the pin, with the duty cycle proportional to ``value``. -:param value: Liczba całkowita lub liczba zmiennopozycyjna między 0 (0% cyklu pracy) a 1023 (100% cyklu pracy).""" + Example: ``pin0.write_analog(254)`` + :param value: An integer or a floating point number between 0 (0% duty cycle) and 1023 (100% duty). + """ def set_analog_period(self, period: int) -> None: - """Ustaw okres wyjścia sygnału PWM na ``period`` w milisekundach. + """Set the period of the PWM signal being output to ``period`` in milliseconds. -Example: ``pin0.set_analog_period(10)`` - -:param period: Okres w milisekundach z minimalną poprawną wartością 1 ms.""" + Example: ``pin0.set_analog_period(10)`` + :param period: The period in milliseconds with a minimum valid value of 1ms. + """ def set_analog_period_microseconds(self, period: int) -> None: - """Ustaw okres wyjścia sygnału PWM na ``period`` w mikrosekundach. (ustaw mikrosekundy okresu analogowego) + """Set the period of the PWM signal being output to ``period`` in microseconds. -Example: ``pin0.set_analog_period_microseconds(512)`` + Example: ``pin0.set_analog_period_microseconds(512)`` -:param period: Okres w mikrosekundach z minimalną poprawną wartością 256µs.""" + :param period: The period in microseconds with a minimum valid value of 256µs. + """ class MicroBitAnalogDigitalPin(MicroBitDigitalPin): - """Pin z funkcjami analogowymi i cyfrowymi.""" + """A pin with analog and digital features.""" def read_analog(self) -> int: - """Odczytaj napięcie przyłożone do pinu. + """Read the voltage applied to the pin. -Example: ``pin0.read_analog()`` + Example: ``pin0.read_analog()`` -:return: An integer between 0 (meaning 0V) and 1023 (meaning 3.3V).""" + :return: An integer between 0 (meaning 0V) and 1023 (meaning 3.3V). + """ class MicroBitTouchPin(MicroBitAnalogDigitalPin): - """Pin z funkcjami analogowymi, cyfrowymi i dotykowymi.""" + """A pin with analog, digital and touch features.""" + CAPACITIVE: int RESISTIVE: int - def is_touched(self) -> bool: - """Sprawdź, czy pin został dotknięty. + """Check if the pin is being touched. -Example: ``pin0.is_touched()`` + Example: ``pin0.is_touched()`` -The default touch mode for the pins on the edge connector is ``resistive``. -The default for the logo pin **V2** is ``capacitive``. + The default touch mode for the pins on the edge connector is ``resistive``. + The default for the logo pin **V2** is ``capacitive``. -**Resistive touch** -This test is done by measuring how much resistance there is between the -pin and ground. A low resistance gives a reading of ``True``. To get -a reliable reading using a finger you may need to touch the ground pin -with another part of your body, for example your other hand. + **Resistive touch** + This test is done by measuring how much resistance there is between the + pin and ground. A low resistance gives a reading of ``True``. To get + a reliable reading using a finger you may need to touch the ground pin + with another part of your body, for example your other hand. -**Capacitive touch** -This test is done by interacting with the electric field of a capacitor -using a finger as a conductor. `Capacitive touch -`_ -does not require you to make a ground connection as part of a circuit. + **Capacitive touch** + This test is done by interacting with the electric field of a capacitor + using a finger as a conductor. `Capacitive touch + `_ + does not require you to make a ground connection as part of a circuit. -:return: ``True`` if the pin is being touched with a finger, otherwise return ``False``.""" + :return: ``True`` if the pin is being touched with a finger, otherwise return ``False``. + """ ... - def set_touch_mode(self, value: int) -> None: - """Ustaw tryb dotykowy dla pinu. + """Set the touch mode for the pin. -Example: ``pin0.set_touch_mode(pin0.CAPACITIVE)`` + Example: ``pin0.set_touch_mode(pin0.CAPACITIVE)`` -The default touch mode for the pins on the edge connector is -``resistive``. The default for the logo pin **V2** is ``capacitive``. + The default touch mode for the pins on the edge connector is + ``resistive``. The default for the logo pin **V2** is ``capacitive``. -:param value: ``CAPACITIVE`` lub ``RESISTIVE`` z odpowiedniego pinu.""" + :param value: ``CAPACITIVE`` or ``RESISTIVE`` from the relevant pin. + """ ... + pin0: MicroBitTouchPin -"""Pin z funkcjami cyfrową, analogową i dotykową.""" +"""Pin with digital, analog and touch features.""" + pin1: MicroBitTouchPin -"""Pin z funkcjami cyfrową, analogową i dotykową.""" +"""Pin with digital, analog and touch features.""" + pin2: MicroBitTouchPin -"""Pin z funkcjami cyfrową, analogową i dotykową.""" +"""Pin with digital, analog and touch features.""" + pin3: MicroBitAnalogDigitalPin -"""Pin z funkcjami cyfrowymi i analogowymi.""" +"""Pin with digital and analog features.""" + pin4: MicroBitAnalogDigitalPin -"""Pin z funkcjami cyfrowymi i analogowymi.""" +"""Pin with digital and analog features.""" + pin5: MicroBitDigitalPin -"""Pin z funkcjami cyfrowymi.""" +"""Pin with digital features.""" + pin6: MicroBitDigitalPin -"""Pin z funkcjami cyfrowymi.""" +"""Pin with digital features.""" + pin7: MicroBitDigitalPin -"""Pin z funkcjami cyfrowymi.""" +"""Pin with digital features.""" + pin8: MicroBitDigitalPin -"""Pin z funkcjami cyfrowymi.""" +"""Pin with digital features.""" + pin9: MicroBitDigitalPin -"""Pin z funkcjami cyfrowymi.""" +"""Pin with digital features.""" + pin10: MicroBitAnalogDigitalPin -"""Pin z funkcjami cyfrowymi i analogowymi.""" +"""Pin with digital and analog features.""" + pin11: MicroBitDigitalPin -"""Pin z funkcjami cyfrowymi.""" +"""Pin with digital features.""" + pin12: MicroBitDigitalPin -"""Pin z funkcjami cyfrowymi.""" +"""Pin with digital features.""" + pin13: MicroBitDigitalPin -"""Pin z funkcjami cyfrowymi.""" +"""Pin with digital features.""" + pin14: MicroBitDigitalPin -"""Pin z funkcjami cyfrowymi.""" +"""Pin with digital features.""" + pin15: MicroBitDigitalPin -"""Pin z funkcjami cyfrowymi.""" +"""Pin with digital features.""" + pin16: MicroBitDigitalPin -"""Pin z funkcjami cyfrowymi.""" +"""Pin with digital features.""" + pin19: MicroBitDigitalPin -"""Pin z funkcjami cyfrowymi.""" +"""Pin with digital features.""" + pin20: MicroBitDigitalPin -"""Pin z funkcjami cyfrowymi.""" +"""Pin with digital features.""" + pin_logo: MicroBitTouchPin -"""Wrażliwy na dotyk pin z logo z przodu micro:bita, który domyślnie jest ustawiony na pojemnościowy tryb dotykowy.""" +"""A touch sensitive logo pin on the front of the micro:bit, which by default is set to capacitive touch mode.""" + pin_speaker: MicroBitAnalogDigitalPin -"""Pin adresujący głośnik micro:bita. +"""A pin to address the micro:bit speaker. This API is intended only for use in Pulse-Width Modulation pin operations e.g. pin_speaker.write_analog(128). """ class Image: - """Obraz wyświetlany na wyświetlaczu LED micro:bita. + """An image to show on the micro:bit LED display. -Given an image object it's possible to display it via the ``display`` API:: + Given an image object it's possible to display it via the ``display`` API:: + + display.show(Image.HAPPY) + """ - display.show(Image.HAPPY)""" HEART: Image - """Obraz serca.""" + """Heart image.""" + HEART_SMALL: Image - """Obraz małego serca.""" + """Small heart image.""" + HAPPY: Image - """Obraz szczęśliwej twarzy.""" + """Happy face image.""" + SMILE: Image - """Obraz uśmiechniętej twarzy.""" + """Smiling mouth image.""" + SAD: Image - """Obraz smutnej twarzy.""" + """Sad face image.""" + CONFUSED: Image - """Obraz zmieszanej twarzy.""" + """Confused face image.""" + ANGRY: Image - """Obraz złej twarzy.""" + """Angry face image.""" + ASLEEP: Image - """Obraz śpiącej twarzy.""" + """Sleeping face image.""" + SURPRISED: Image - """Obraz zaskoczonej twarzy.""" + """Surprised face image.""" + SILLY: Image - """Obraz głupiej twarzy.""" + """Silly face image.""" + FABULOUS: Image - """Obraz twarzy w okularach przeciwsłonecznych.""" + """Sunglasses face image.""" + MEH: Image - """Obraz niewzruszonej twarzy.""" + """Unimpressed face image.""" + YES: Image - """Haczyk na TAK.""" + """Tick image.""" + NO: Image - """Krzyżyk na NIE.""" + """Cross image.""" + CLOCK12: Image - """Obraz z linią wskazującą na godzinę 12.""" + """Image with line pointing to 12 o'clock.""" + CLOCK11: Image - """Obraz z linią wskazującą na godzinę 11.""" + """Image with line pointing to 11 o'clock.""" + CLOCK10: Image - """Obraz z linią wskazującą na godzinę 10.""" + """Image with line pointing to 10 o'clock.""" + CLOCK9: Image - """Obraz z linią wskazującą na godzinę 9.""" + """Image with line pointing to 9 o'clock.""" + CLOCK8: Image - """Obraz z linią wskazującą na godzinę 8.""" + """Image with line pointing to 8 o'clock.""" + CLOCK7: Image - """Obraz z linią wskazującą na godzinę 7.""" + """Image with line pointing to 7 o'clock.""" + CLOCK6: Image - """Obraz z linią wskazującą na godzinę 6.""" + """Image with line pointing to 6 o'clock.""" + CLOCK5: Image - """Obraz z linią wskazującą na godzinę 5.""" + """Image with line pointing to 5 o'clock.""" + CLOCK4: Image - """Obraz z linią wskazującą na godzinę 4.""" + """Image with line pointing to 4 o'clock.""" + CLOCK3: Image - """Obraz z linią wskazującą na godzinę 3.""" + """Image with line pointing to 3 o'clock.""" + CLOCK2: Image - """Obraz z linią wskazującą na godzinę 2.""" + """Image with line pointing to 2 o'clock.""" + CLOCK1: Image - """Obraz z linią wskazującą na godzinę 1.""" + """Image with line pointing to 1 o'clock.""" + ARROW_N: Image - """Obraz strzałki wskazującej północ.""" + """Image of arrow pointing north.""" + ARROW_NE: Image - """Obraz strzałki wskazującej północny wschód.""" + """Image of arrow pointing north east.""" + ARROW_E: Image - """Obraz strzałki wskazującej wschód.""" + """Image of arrow pointing east.""" + ARROW_SE: Image - """Obraz strzałki wskazującej południowy wschód.""" + """Image of arrow pointing south east.""" + ARROW_S: Image - """Obraz strzałki wskazującej południe.""" + """Image of arrow pointing south.""" + ARROW_SW: Image - """Obraz strzałki wskazującej południowy zachód.""" + """Image of arrow pointing south west.""" + ARROW_W: Image - """Obraz strzałki wskazującej zachód.""" + """Image of arrow pointing west.""" + ARROW_NW: Image - """Obraz strzałki wskazującej północny zachód.""" + """Image of arrow pointing north west.""" + TRIANGLE: Image - """Obraz trójkąta skierowanego do góry.""" + """Image of a triangle pointing up.""" + TRIANGLE_LEFT: Image - """Obraz trójkąta w lewym rogu.""" + """Image of a triangle in the left corner.""" + CHESSBOARD: Image - """Diody LED świecą naprzemiennie w układzie szachownicy.""" + """Alternate LEDs lit in a chessboard pattern.""" + DIAMOND: Image - """Obraz diamentu.""" + """Diamond image.""" + DIAMOND_SMALL: Image - """Obraz małego diamentu.""" + """Small diamond image.""" + SQUARE: Image - """Obraz kwadratu.""" + """Square image.""" + SQUARE_SMALL: Image - """Obraz małego kwadratu.""" + """Small square image.""" + RABBIT: Image - """Obraz królika.""" + """Rabbit image.""" + COW: Image - """Obraz krowy.""" + """Cow image.""" + MUSIC_CROTCHET: Image - """Obraz ćwierćnuty.""" + """Crotchet note image.""" + MUSIC_QUAVER: Image - """Obraz nuty ósemki.""" + """Quaver note image.""" + MUSIC_QUAVERS: Image - """Obraz pary nut ósemek.""" + """Pair of quavers note image.""" + PITCHFORK: Image - """Obraz kamertonu.""" + """Pitchfork image.""" + XMAS: Image - """Obraz choinki.""" + """Christmas tree image.""" + PACMAN: Image - """Obrazek postaci arcade Pac-Man""" + """Pac-Man arcade character image.""" + TARGET: Image - """Obraz celu.""" + """Target image.""" + TSHIRT: Image - """Obraz t-shirt.""" + """T-shirt image.""" + ROLLERSKATE: Image - """Obraz Rollerskate.""" + """Rollerskate image.""" + DUCK: Image - """Obraz kaczki.""" + """Duck image.""" + HOUSE: Image - """Obraz domu.""" + """House image.""" + TORTOISE: Image - """Obraz żółwia.""" + """Tortoise image.""" + BUTTERFLY: Image - """Obraz motyla.""" + """Butterfly image.""" + STICKFIGURE: Image - """Obraz przyklejonej figury.""" + """Stick figure image.""" + GHOST: Image - """Obraz ducha.""" + """Ghost image.""" + SWORD: Image - """Obraz miecza.""" + """Sword image.""" + GIRAFFE: Image - """Obraz żyrafy.""" + """Giraffe image.""" + SKULL: Image - """Obraz czaszki.""" + """Skull image.""" + UMBRELLA: Image - """Obraz parasola.""" + """Umbrella image.""" + SNAKE: Image - """Obraz węża.""" + """Snake image.""" + SCISSORS: Image - """Obraz nożyczek.""" + """Scissors image.""" + ALL_CLOCKS: List[Image] - """Lista zawierająca wszystkie obrazy CLOCK_ po kolei.""" - ALL_ARROWS: List[Image] - """Lista zawierająca wszystkie obrazy ARROW_ po kolei.""" + """A list containing all the CLOCK_ images in sequence.""" + ALL_ARROWS: List[Image] + """A list containing all the ARROW_ images in sequence.""" @overload def __init__(self, string: str) -> None: - """Utwórz obraz z łańcucha opisującego, które diody LED są zapalone. + """Create an image from a string describing which LEDs are lit. -``string`` has to consist of digits 0-9 arranged into lines, -describing the image, for example:: + ``string`` has to consist of digits 0-9 arranged into lines, + describing the image, for example:: - image = Image("90009:" - "09090:" - "00900:" - "09090:" - "90009") + 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 newlines (\\n) insead of the colons. + 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 newlines (\\n) insead of the colons. -:param string: Łańcuch opisujący obraz.""" + :param string: The string describing the image. + """ ... - @overload - def __init__(self, width: int=5, height: int=5, buffer: ReadableBuffer=None) -> None: - """Utwórz pusty obraz z ``width`` kolumnami i ``height`` wierszami. + def __init__( + self, width: int = 5, height: int = 5, buffer: ReadableBuffer = None + ) -> None: + """Create an empty image with ``width`` columns and ``height`` rows. -:param width: Opcjonalna szerokość obrazu -:param height: Opcjonalna wysokość obrazu -:param buffer: Opcjonalna tablica lub bajty ``width``×``height`` liczb całkowitych w zakresie 0-9 do zainicjowania obrazu + :param width: Optional width of the image + :param height: Optional height of the image + :param buffer: Optional array or bytes of ``width``×``height`` integers in range 0-9 to initialize the image -Examples:: + Examples:: - Image(2, 2, b'\x08\x08\x08\x08') - Image(2, 2, bytearray([9,9,9,9])) + Image(2, 2, b'\x08\x08\x08\x08') + Image(2, 2, bytearray([9,9,9,9])) -These create 2 x 2 pixel images at full brightness.""" + These create 2 x 2 pixel images at full brightness. + """ ... - def width(self) -> int: - """Ustal liczbę kolumn + """Get the number of columns. -:return: The number of columns in the image""" + :return: The number of columns in the image + """ ... - def height(self) -> int: - """Uzyskaj liczbę wierszy + """Get the number of rows. -:return: The number of rows in the image""" + :return: The number of rows in the image + """ ... - def set_pixel(self, x: int, y: int, value: int) -> None: - """Ustaw jasność piksela. + """Set the brightness of a pixel. -Example: ``my_image.set_pixel(0, 0, 9)`` + Example: ``my_image.set_pixel(0, 0, 9)`` -:param x: Numer kolumny -:param y: Numer wiersza -:param value: Jasność jako liczba całkowita między 0 (ciemny) i 9 (jasna) + :param x: The column number + :param y: The row number + :param value: The brightness as an integer 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``.""" + 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: - """uzyskaj jasność piksela. + """Get the brightness of a pixel. -Example: ``my_image.get_pixel(0, 0)`` + Example: ``my_image.get_pixel(0, 0)`` -:param x: Numer kolumny -:param y: Numer wiersza -:return: The brightness as an integer between 0 and 9.""" + :param x: The column number + :param y: The row number + :return: The brightness as an integer between 0 and 9. + """ ... - def shift_left(self, n: int) -> Image: - """Utwórz nowy obraz przesuwając ten obraz w lewo. + """Create a new image by shifting the picture left. -Example: ``Image.HEART_SMALL.shift_left(1)`` + Example: ``Image.HEART_SMALL.shift_left(1)`` -:param n: Liczba kolumn do przesunięcia -:return: The shifted image""" + :param n: The number of columns to shift by + :return: The shifted image + """ ... - def shift_right(self, n: int) -> Image: - """Utwórz nowy obraz, przesuwając ten obraz w prawo. + """Create a new image by shifting the picture right. -Example: ``Image.HEART_SMALL.shift_right(1)`` + Example: ``Image.HEART_SMALL.shift_right(1)`` -:param n: Liczba kolumn do przesunięcia -:return: The shifted image""" + :param n: The number of columns to shift by + :return: The shifted image + """ ... - def shift_up(self, n: int) -> Image: - """Utwórz nowy obraz, przesuwając obraz do góry. + """Create a new image by shifting the picture up. -Example: ``Image.HEART_SMALL.shift_up(1)`` + Example: ``Image.HEART_SMALL.shift_up(1)`` -:param n: Liczba wierszy do przesunięcia o -:return: The shifted image""" + :param n: The number of rows to shift by + :return: The shifted image + """ ... - def shift_down(self, n: int) -> Image: - """Utwórz nowy obraz, przesuwając obraz do dołu. + """Create a new image by shifting the picture down. -Example: ``Image.HEART_SMALL.shift_down(1)`` + Example: ``Image.HEART_SMALL.shift_down(1)`` -:param n: Liczba wierszy do przesunięcia o -:return: The shifted image""" + :param n: The number of rows to shift by + :return: The shifted image + """ ... - def crop(self, x: int, y: int, w: int, h: int) -> Image: - """Utwórz nowy obraz przez przycięcie zdjęcia. + """Create a new image by cropping the picture. -Example: ``Image.HEART.crop(1, 1, 3, 3)`` + Example: ``Image.HEART.crop(1, 1, 3, 3)`` -:param x: Kolumna przesunięcia przycięcia -:param y: Wiersz przesunięcia przycięcia -:param w: Szerokość przycięcia -:param h: Wysokość przycięcia -:return: The new image""" + :param x: The crop offset column + :param y: The crop offset row + :param w: The crop width + :param h: The crop height + :return: The new image + """ ... - def copy(self) -> Image: - """Utwórz dokładną kopię obrazu. + """Create an exact copy of the image. -Example: ``Image.HEART.copy()`` + Example: ``Image.HEART.copy()`` -:return: The new image""" + :return: The new image + """ ... - def invert(self) -> Image: - """Utwórz nowy obraz przez odwrócenie jasności pikseli w obrazie źródłowym. + """Create a new image by inverting the brightness of the pixels in the + source image. -Example: ``Image.SMALL_HEART.invert()`` + Example: ``Image.SMALL_HEART.invert()`` -:return: The new image.""" + :return: The new image. + """ ... - def fill(self, value: int) -> None: - """Ustaw jasność wszystkich pikseli obrazka. + """Set the brightness of all the pixels in the image. -Example: ``my_image.fill(5)`` + Example: ``my_image.fill(5)`` -:param value: Nowa jasność jako liczba między 0 (ciemny) a 9 (jasny). + :param value: The new brightness as a number 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``.""" + 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: - """Skopiuj obszar z innego obrazu na ten obraz. - -Example: ``my_image.blit(Image.HEART, 1, 1, 3, 3, 1, 1)`` - -:param src: Zdjęcie źródłowe -:param x: Początkowe przesunięcie kolumny w obrazie źródłowym -:param y: Początkowe przesunięcie wiersza na obrazie źródłowym -:param w: Liczba kolumn do skopiowania -:param h: Liczba wierszy do skopiowania -:param xdest: Przesunięcie kolumny do modyfikacji na tym obrazie -:param ydest: Przesunięcie wiersza do modyfikacji na tym obrazie - -Pixels outside the source image are treated as having a brightness 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 blit( + self, + src: Image, + x: int, + y: int, + w: int, + h: int, + xdest: int = 0, + ydest: int = 0, + ) -> None: + """Copy an area from another image into this image. + + Example: ``my_image.blit(Image.HEART, 1, 1, 3, 3, 1, 1)`` + + :param src: The source image + :param x: The starting column offset in the source image + :param y: The starting row offset in the source image + :param w: The number of columns to copy + :param h: The number of rows to copy + :param xdest: The column offset to modify in this image + :param ydest: The row offset to modify in this image + + Pixels outside the source image are treated as having a brightness 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: - """Uzyskaj kompaktową reprezentację obrazu w postaci łańcucha.""" + """Get a compact string representation of the image.""" ... - def __str__(self) -> str: - """Uzyskaj czytelną reprezentację obrazu w postaci łańcucha.""" + """Get a readable string representation of the image.""" ... - def __add__(self, other: Image) -> Image: - """Utwórz nowy obraz, dodając wartości jasności z dwóch -obrazów dla każdego piksela. + """Create a new image by adding the brightness values from the two + images for each pixel. -Example: ``Image.HEART + Image.HAPPY`` + Example: ``Image.HEART + Image.HAPPY`` -:param other: Obraz do dodania.""" + :param other: The image to add. + """ ... - def __sub__(self, other: Image) -> Image: - """Utwórz nowy obraz, odejmując wartości jasności -innego obrazu od tego obrazu. + """Create a new image by subtracting the brightness values of the + other image from this image. -Example: ``Image.HEART - Image.HEART_SMALL`` + Example: ``Image.HEART - Image.HEART_SMALL`` -:param other: Obraz do odjęcia.""" + :param other: The image to subtract. + """ ... - def __mul__(self, n: float) -> Image: - """Utwórz nowy obraz, mnożąc jasność każdego piksela przez -``n``. + """Create a new image by multiplying the brightness of each pixel by + ``n``. -Example: ``Image.HEART * 0.5`` + Example: ``Image.HEART * 0.5`` -:param n: Wartość do mnożenia przez.""" + :param n: The value to multiply by. + """ ... - def __truediv__(self, n: float) -> Image: - """Utwórz nowy obraz, dzieląc jasność każdego piksela przez -``n``. + """Create a new image by dividing the brightness of each pixel by + ``n``. -Example: ``Image.HEART / 2`` + Example: ``Image.HEART / 2`` -:param n: Wartość do dzielenia przez.""" + :param n: The value to divide by. + """ ... class SoundEvent: LOUD: SoundEvent - """Przedstawia przejście zdarzeń dźwiękowych z ``quiet`` do ``loud``, jak klaskanie lub krzyczenie.""" + """Represents the transition of sound events, from ``quiet`` to ``loud`` like clapping or shouting.""" + QUIET: SoundEvent - """Przedstawia przejście zdarzeń dźwiękowych z ``loud`` do ``quiet``, jak mówienie lub muzyka w tle.""" + """Represents the transition of sound events, from ``loud`` to ``quiet`` like speaking or background music.""" class Sound: - """Wbudowane dźwięki można wywołać za pomocą ``audio.play(Sound.NAME)``.""" + """The built-in sounds can be called using ``audio.play(Sound.NAME)``.""" + GIGGLE: Sound - """Chichoczący dźwięk.""" + """Giggling sound.""" + HAPPY: Sound - """Szczęśliwy dźwięk.""" + """Happy sound.""" + HELLO: Sound - """Dźwięk powitania.""" + """Greeting sound.""" + MYSTERIOUS: Sound - """Tajemniczy dźwięk.""" + """Mysterious sound.""" + SAD: Sound - """Smutny dźwięk.""" + """Sad sound.""" + SLIDE: Sound - """Przesuwający się dźwięk.""" + """Sliding sound.""" + SOARING: Sound - """Wznoszący się dźwięk.""" + """Soaring sound.""" + SPRING: Sound - """Wiosny dźwięk.""" + """Spring sound.""" + TWINKLE: Sound - """Migoczący dźwięk.""" + """Twinkling sound.""" + YAWN: Sound - """Dźwięk ziewania.""" \ No newline at end of file + """Yawning sound.""" diff --git a/lang/pl/typeshed/stdlib/microbit/accelerometer.pyi b/lang/pl/typeshed/stdlib/microbit/accelerometer.pyi index e47dc08..bac82c0 100644 --- a/lang/pl/typeshed/stdlib/microbit/accelerometer.pyi +++ b/lang/pl/typeshed/stdlib/microbit/accelerometer.pyi @@ -1,103 +1,115 @@ -"""Zmierz przyspieszenie micro:bita i rozpoznawaj gesty.""" +"""Measure the acceleration of the micro:bit and recognise gestures. +""" + from typing import Tuple def get_x() -> int: - """Uzyskaj pomiar przyspieszenia na osi ``x`` w mili-g. + """Get the acceleration measurement in the ``x`` axis in milli-g. -Example: ``accelerometer.get_x()`` + Example: ``accelerometer.get_x()`` -:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" + :return: A positive or negative integer depending on direction in the range +/- 2000mg. + """ ... def get_y() -> int: - """Uzyskaj pomiar przyspieszenia na osi ``y`` w mili-g. + """Get the acceleration measurement in the ``y`` axis in milli-g. -Example: ``accelerometer.get_y()`` + Example: ``accelerometer.get_y()`` -:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" + :return: A positive or negative integer depending on direction in the range +/- 2000mg. + """ ... def get_z() -> int: - """Uzyskaj pomiar przyspieszenia na osi ``z`` w mili-g. + """Get the acceleration measurement in the ``z`` axis in milli-g. -Example: ``accelerometer.get_z()`` + Example: ``accelerometer.get_z()`` -:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" + :return: A positive or negative integer depending on direction in the range +/- 2000mg. + """ ... def get_values() -> Tuple[int, int, int]: - """Uzyskaj pomiary przyspieszenia na wszystkich osiach jednocześnie, jako krotkę. + """Get the acceleration measurements in all axes at once as a tuple. -Example: ``x, y, z = accelerometer.get_values()`` + Example: ``x, y, z = accelerometer.get_values()`` -:return: a three-element tuple of integers ordered as X, Y, Z, each value a positive or negative integer depending on direction in the range +/- 2000mg""" + :return: a three-element tuple of integers ordered as X, Y, Z, each value a positive or negative integer depending on direction in the range +/- 2000mg + """ ... def get_strength() -> int: - """Uzyskaj pomiar przyspieszenia wszystkich osi łącznie jako dodatnią liczbę całkowitą. Jest to suma pitagorejska osi X, Y i Z. + """Get the acceleration measurement of all axes combined, as a positive integer. This is the Pythagorean sum of the X, Y and Z axes. -Example: ``accelerometer.get_strength()`` + Example: ``accelerometer.get_strength()`` -:return: The combined acceleration strength of all the axes, in milli-g.""" + :return: The combined acceleration strength of all the axes, in milli-g. + """ ... def current_gesture() -> str: - """Pobierz nazwę aktualnego gestu. + """Get the name of the current gesture. -Example: ``accelerometer.current_gesture()`` + Example: ``accelerometer.current_gesture()`` -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. + 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. -:return: The current gesture""" + :return: The current gesture + """ ... def is_gesture(name: str) -> bool: - """Sprawdź, czy nazwany gest jest aktualnie aktywny. + """Check if the named gesture is currently active. -Example: ``accelerometer.is_gesture('shake')`` + Example: ``accelerometer.is_gesture('shake')`` -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. + 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. -:param name: Nazwa gestu. -:return: ``True`` if the gesture is active, ``False`` otherwise.""" + :param name: The gesture name. + :return: ``True`` if the gesture is active, ``False`` otherwise. + """ ... def was_gesture(name: str) -> bool: - """Sprawdź, czy nazwany gest był aktywny od ostatniego połączenia. + """Check if the named gesture was active since the last call. -Example: ``accelerometer.was_gesture('shake')`` + Example: ``accelerometer.was_gesture('shake')`` -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. + 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. -:param name: Nazwa gestu. -:return: ``True`` if the gesture was active since the last call, ``False`` otherwise.""" + :param name: The gesture name. + :return: ``True`` if the gesture was active since the last call, ``False`` otherwise. + """ def get_gestures() -> Tuple[str, ...]: - """Zwróć krotkę historii gestów. + """Return a tuple of the gesture history. -Example: ``accelerometer.get_gestures()`` + Example: ``accelerometer.get_gestures()`` -Clears the gesture history before returning. + Clears the gesture history before returning. -Gestures are not updated in the background so there needs to be constant -calls to some accelerometer method to do the gesture detection. Usually -gestures can be detected using a loop with a small :func:`microbit.sleep` delay. + Gestures are not updated in the background so there needs to be constant + calls to some accelerometer method to do the gesture detection. Usually + gestures can be detected using a loop with a small :func:`microbit.sleep` delay. -:return: The history as a tuple, most recent last.""" + :return: The history as a tuple, most recent last. + """ ... def set_range(value: int) -> None: - """Ustaw zakres czułości akcelerometru w g (standardowa grawitacja) na najbliższe wartości obsługiwane przez sprzęt tak, aby zaokrąglał się do ``2``, ``4`` lub ``8`` g. + """Set the accelerometer sensitivity range, in g (standard gravity), to the closest values supported by the hardware, so it rounds to either ``2``, ``4``, or ``8`` g. -Example: ``accelerometer.set_range(8)`` + Example: ``accelerometer.set_range(8)`` -:param value: Nowy zakres dla akcelerometru, liczba całkowita w ``g``.""" \ No newline at end of file + :param value: New range for the accelerometer, an integer in ``g``. + """ diff --git a/lang/pl/typeshed/stdlib/microbit/audio.pyi b/lang/pl/typeshed/stdlib/microbit/audio.pyi index 3a3fe4b..3b1e327 100644 --- a/lang/pl/typeshed/stdlib/microbit/audio.pyi +++ b/lang/pl/typeshed/stdlib/microbit/audio.pyi @@ -1,123 +1,160 @@ -"""Odtwarzaj dźwięki za pomocą micro:bita (importuj ``audio`` dla kompatybilności V1).""" +"""Play sounds using the micro:bit (import ``audio`` for V1 compatibility). +""" + from ..microbit import MicroBitDigitalPin, Sound, pin0 from typing import ClassVar, Iterable, Union -def play(source: Union[Iterable[AudioFrame], Sound, SoundEffect], wait: bool=True, pin: MicroBitDigitalPin=pin0, return_pin: Union[MicroBitDigitalPin, None]=None) -> None: - """Odtwórz wbudowany dźwięk, efekt dźwiękowy lub niestandardowe ramki audio. +def play( + source: Union[Iterable[AudioFrame], Sound, SoundEffect], + wait: bool = True, + pin: MicroBitDigitalPin = pin0, + return_pin: Union[MicroBitDigitalPin, None] = None, +) -> None: + """Play a built-in sound, sound effect or custom audio frames. -Example: ``audio.play(Sound.GIGGLE)`` + Example: ``audio.play(Sound.GIGGLE)`` -:param source: Wbudowany ``Sound``, taki jak ``Sound.GIGGLE``, ``SoundEffect`` lub przykładowe dane jako iteracja obiektów ``AudioFrame``. -:param wait: Jeśli ``wait`` jest ``True``, ta funkcja będzie blokować, aż dźwięk zostanie zakończony. -:param pin: Opcjonalny argument do określenia pinu wyjściowego może być użyty do nadpisania domyślnej wartości ``pin0``. Jeśli nie chcemy, aby żaden dźwięk nie był odtwarzany, możemy użyć ``pin=None``. -:param return_pin: Określa pin łącznika różnicowego, aby podłączyć płytkę do zewnętrznego głośnika zamiast do ziemi. Jest to ignorowane dla **V2**.""" + :param source: A built-in ``Sound`` such as ``Sound.GIGGLE``, a ``SoundEffect`` or sample data as an iterable of ``AudioFrame`` objects. + :param wait: If ``wait`` is ``True``, this function will block until the sound is complete. + :param pin: An optional argument to specify the output pin can be used to override the default of ``pin0``. If we do not want any sound to play we can use ``pin=None``. + :param return_pin: Specifies a differential edge connector pin to connect to an external speaker instead of ground. This is ignored for the **V2** revision. + """ def is_playing() -> bool: - """Sprawdź, czy dźwięk jest odtwarzany. + """Check whether a sound is playing. -Example: ``audio.is_playing()`` + Example: ``audio.is_playing()`` -:return: ``True`` if audio is playing, otherwise ``False``.""" + :return: ``True`` if audio is playing, otherwise ``False``.""" ... def stop() -> None: - """Zatrzymaj odtwarzania audio. + """Stop all audio playback. -Example: ``audio.stop()``""" + Example: ``audio.stop()`` + """ ... class SoundEffect: - """Efekt dźwiękowy, utworzony przez zestaw parametrów skonfigurowanych za pomocą konstruktora lub atrybutów.""" + """A sound effect, composed by a set of parameters configured via the constructor or attributes.""" + WAVEFORM_SINE: ClassVar[int] - """Opcja sinusoidalnej fali używana dla parametru ``waveform``.""" + """Sine wave option used for the ``waveform`` parameter.""" + WAVEFORM_SAWTOOTH: ClassVar[int] - """Opcja fali piłokształtnej używana dla parametru ``waveform``.""" + """Sawtooth wave option used for the ``waveform`` parameter.""" + WAVEFORM_TRIANGLE: ClassVar[int] - """Opcja fali trójkątnej używana dla parametru ``waveform``.""" + """Triangle wave option used for the ``waveform`` parameter.""" + WAVEFORM_SQUARE: ClassVar[int] - """Opcja fali kwadratowj używana dla parametru ``waveform``.""" + """Square wave option used for the ``waveform`` parameter.""" + WAVEFORM_NOISE: ClassVar[int] - """Opcja szumu używana dla parametru ``waveform``.""" + """Noise option used for the ``waveform`` parameter.""" + SHAPE_LINEAR: ClassVar[int] - """Opcja interpolacji liniowej używana dla parametru ``shape``.""" + """Linear interpolation option used for the ``shape`` parameter.""" + SHAPE_CURVE: ClassVar[int] - """Opcja interpolacji krzywej używana dla parametru ``shape``.""" + """Curve interpolation option used for the ``shape`` parameter.""" + SHAPE_LOG: ClassVar[int] - """Opcja interpolacji logarytmicznej używana dla parametru ``shape``.""" + """Logarithmic interpolation option used for the ``shape`` parameter.""" + FX_NONE: ClassVar[int] - """Opcja braku efektu użyta dla parametru ``fx``.""" + """No effect option used for the ``fx`` parameter.""" + FX_TREMOLO: ClassVar[int] - """Opcja efektu Tremelo użyta dla parametru ``fx``.""" + """Tremolo effect option used for the ``fx`` parameter.""" + FX_VIBRATO: ClassVar[int] - """Opcja efektu Vibrato użyta dla parametru ``fx``.""" + """Vibrato effect option used for the ``fx`` parameter.""" + FX_WARBLE: ClassVar[int] - """Opcja efektu Warble użyta dla parametru ``fx``.""" + """Warble effect option used for the ``fx`` parameter.""" + freq_start: int - """Częstotliwość początkowa w hercach (Hz), liczba między ``0`` i ``9999``""" + """Start frequency in Hertz (Hz), a number between ``0`` and ``9999``""" + freq_end: int - """Częstotliwość końcowa w hercach (Hz), liczba między ``0`` i ``9999``""" + """End frequency in Hertz (Hz), a number between ``0`` and ``9999``""" + duration: int - """Czas trwania dźwięku w milisekundach, liczba pomiędzy ``0`` i ``9999``""" - vol_start: int - """Wartość głośności początkowej, liczba między ``0`` i ``255``""" - vol_end: int - """Wartość głośności końcowej, liczba między ``0`` i ``255``""" - waveform: int - """Rodzaj kształtu fali, jedna z tych wartości:``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (losowo generowany szum)""" - fx: int - """Efekt do dodania do dźwięku, jedna z następujących wartości: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE`` lub ``FX_NONE``""" - shape: int - """Rodzaj krzywej interpolacji między częstotliwością początkową i końcową, różne kształty fal mają różne szybkości zmian częstotliwości. Jedna z następujących wartości: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``""" + """Duration of the sound in milliseconds, a number between ``0`` and ``9999``""" - def __init__(self, freq_start: int=500, freq_end: int=2500, duration: int=500, vol_start: int=255, vol_end: int=0, waveform: int=WAVEFORM_SQUARE, fx: int=FX_NONE, shape: int=SHAPE_LOG): - """Utwórz nowy efekt dźwiękowy. + vol_start: int + """Start volume value, a number between ``0`` and ``255``""" -Example: ``my_effect = SoundEffect(duration=1000)`` + vol_end: int + """End volume value, a number between ``0`` and ``255``""" -All the parameters are optional, with default values as shown above, and -they can all be modified via attributes of the same name. For example, we -can first create an effect ``my_effect = SoundEffect(duration=1000)``, -and then change its attributes ``my_effect.duration = 500``. + waveform: int + """Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise)""" -:param freq_start: Częstotliwość początkowa w hercach (Hz), liczba między ``0`` i ``9999``. -:param freq_end: Częstotliwość końcowa w hercach (Hz), liczba między ``0`` i ``9999``. -:param duration: Czas trwania dźwięku w milisekundach, liczba między ``0`` i ``9999``. -:param vol_start: Początkowa wartość głośności, liczba pomiędzy ``0`` i ``255``. -:param vol_end: Końcowa wartość głośności, liczba pomiędzy ``0`` i ``255``. -:param waveform: Rodzaj kształtu fali, jedna z tych wartości: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (losowo generowany szum). -:param fx: Efekt do dodania do dźwięku, jedna z następujących wartości: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE`` lub ``FX_NONE``. -:param shape: Rodzaj krzywej interpolacji między częstotliwością początkową i końcową, różne kształty fal mają różne szybkości zmian częstotliwości. Jedna z następujących wartości: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``.""" + fx: int + """Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``""" + shape: int + """The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``""" + + def __init__( + self, + freq_start: int = 500, + freq_end: int = 2500, + duration: int = 500, + vol_start: int = 255, + vol_end: int = 0, + waveform: int = WAVEFORM_SQUARE, + fx: int = FX_NONE, + shape: int = SHAPE_LOG, + ): + """Create a new sound effect. + + Example: ``my_effect = SoundEffect(duration=1000)`` + + All the parameters are optional, with default values as shown above, and + they can all be modified via attributes of the same name. For example, we + can first create an effect ``my_effect = SoundEffect(duration=1000)``, + and then change its attributes ``my_effect.duration = 500``. + + :param freq_start: Start frequency in Hertz (Hz), a number between ``0`` and ``9999``. + :param freq_end: End frequency in Hertz (Hz), a number between ``0`` and ``9999``. + :param duration: Duration of the sound in milliseconds, a number between ``0`` and ``9999``. + :param vol_start: Start volume value, a number between ``0`` and ``255``. + :param vol_end: End volume value, a number between ``0`` and ``255``. + :param waveform: Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise). + :param fx: Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``. + :param shape: The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``. + """ def copy(self) -> SoundEffect: - """Utwórz kopię ``SoundEffect``. + """Create a copy of this ``SoundEffect``. -Example: ``sound_2 = sound_1.copy()`` + Example: ``sound_2 = sound_1.copy()`` -:return: A copy of the SoundEffect.""" + :return: A copy of the SoundEffect. + """ class AudioFrame: - """Obiekt ``AudioFrame`` jest listą 32 próbek, z których każda jest niepodpisanym bajtem (liczba całkowita między 0 a 255). + """An ``AudioFrame`` object is a list of 32 samples each of which is a unsigned byte + (whole number between 0 and 255). -It takes just over 4 ms to play a single frame. + It takes just over 4 ms to play a single frame. -Example:: + Example:: - frame = AudioFrame() - for i in range(len(frame)): - frame[i] = 252 - i * 8""" + frame = AudioFrame() + for i in range(len(frame)): + frame[i] = 252 - i * 8 + """ def copyfrom(self, other: AudioFrame) -> None: - """Zastąp dane w tym ``AudioFrame`` danymi z innej instancji ``AudioFrame``. - -Example: ``my_frame.copyfrom(source_frame)`` - -:param other: Instancja ``AudioFrame``, z której skopiowane są dane.""" - - def __len__(self) -> int: - ... + """Overwrite the data in this ``AudioFrame`` with the data from another ``AudioFrame`` instance. - def __setitem__(self, key: int, value: int) -> None: - ... + Example: ``my_frame.copyfrom(source_frame)`` - def __getitem__(self, key: int) -> int: - ... \ No newline at end of file + :param other: ``AudioFrame`` instance from which to copy the data. + """ + def __len__(self) -> int: ... + def __setitem__(self, key: int, value: int) -> None: ... + def __getitem__(self, key: int) -> int: ... diff --git a/lang/pl/typeshed/stdlib/microbit/compass.pyi b/lang/pl/typeshed/stdlib/microbit/compass.pyi index cd6c9c7..c74a47b 100644 --- a/lang/pl/typeshed/stdlib/microbit/compass.pyi +++ b/lang/pl/typeshed/stdlib/microbit/compass.pyi @@ -1,70 +1,78 @@ -"""Użyj wbudowanego kompasu.""" +"""Use the built-in compass. +""" def calibrate() -> None: - """Rozpoczyna proces kalibracji. + """Starts the calibration process. -Example: ``compass.calibrate()`` + Example: ``compass.calibrate()`` -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.""" + 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: - """Sprawdź, czy kompas jest skalibrowany. + """Check is the compass is calibrated. -Example: ``compass.is_calibrated()`` + Example: ``compass.is_calibrated()`` -:return: ``True`` if the compass has been successfully calibrated, ``False`` otherwise.""" + :return: ``True`` if the compass has been successfully calibrated, ``False`` otherwise. + """ ... def clear_calibration() -> None: - """Cofnij kalibrację, czyniąc kompas ponownie niekalibrowanym. + """Undoes the calibration, making the compass uncalibrated again. -Example: ``compass.clear_calibration()``""" + Example: ``compass.clear_calibration()`` + """ ... def get_x() -> int: - """Uzyskaj natężenie pola magnetycznego na osi ``x``. + """Get the magnetic field strength on the ``x`` axis. -Example: ``compass.get_x()`` + Example: ``compass.get_x()`` -Call ``calibrate`` first or the results will be inaccurate. + Call ``calibrate`` first or the results will be inaccurate. -:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" + :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. + """ ... def get_y() -> int: - """Uzyskaj natężenie pola magnetycznego na osi ``y``. + """Get the magnetic field strength on the ``y`` axis. -Example: ``compass.get_y()`` + Example: ``compass.get_y()`` -Call ``calibrate`` first or the results will be inaccurate. + Call ``calibrate`` first or the results will be inaccurate. -:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" + :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. + """ ... def get_z() -> int: - """Uzyskaj natężenie pola magnetycznego na osi ``z``. + """Get the magnetic field strength on the ``z`` axis. -Example: ``compass.get_z()`` + Example: ``compass.get_z()`` -Call ``calibrate`` first or the results will be inaccurate. + Call ``calibrate`` first or the results will be inaccurate. -:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" + :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. + """ ... def heading() -> int: - """Pobierz kierunek kompasu. + """Get the compass heading. -Example: ``compass.heading()`` + Example: ``compass.heading()`` -:return: An integer in the range from 0 to 360, representing the angle in degrees, clockwise, with north as 0.""" + :return: An integer in the range from 0 to 360, representing the angle in degrees, clockwise, with north as 0. + """ ... def get_field_strength() -> int: - """Uzyskaj wielkość pola magnetycznego wokół urządzenia. + """Get the magnitude of the magnetic field around the device. -Example: ``compass.get_field_strength()`` + Example: ``compass.get_field_strength()`` -:return: An integer indication of the magnitude of the magnetic field in nano tesla.""" - ... \ No newline at end of file + :return: An integer indication of the magnitude of the magnetic field in nano tesla.""" + ... diff --git a/lang/pl/typeshed/stdlib/microbit/display.pyi b/lang/pl/typeshed/stdlib/microbit/display.pyi index 25ee96c..aa4013e 100644 --- a/lang/pl/typeshed/stdlib/microbit/display.pyi +++ b/lang/pl/typeshed/stdlib/microbit/display.pyi @@ -1,92 +1,115 @@ -"""Pokaż tekst, obrazy i animacje na wyświetlaczu 5x5 LED.""" +"""Show text, images and animations on the 5×5 LED display. +""" + from ..microbit import Image from typing import Union, overload, Iterable def get_pixel(x: int, y: int) -> int: - """Uzyskaj jasność LED w kolumnie ``x`` i w wierszu ``y``. + """Get the brightness of the LED at column ``x`` and row ``y``. -Example: ``display.get_pixel(0, 0)`` + Example: ``display.get_pixel(0, 0)`` -:param x: Wyświetlana kolumna (0..4) -:param y: Wyświetlany wiersz (0..4) -:return: A number between 0 (off) and 9 (bright)""" + :param x: The display column (0..4) + :param y: The display row (0..4) + :return: A number between 0 (off) and 9 (bright) + """ ... def set_pixel(x: int, y: int, value: int) -> None: - """Ustaw jasność LED w kolumnie ``x`` i wierszu ``y``. + """Set the brightness of the LED at column ``x`` and row ``y``. -Example: ``display.set_pixel(0, 0, 9)`` + Example: ``display.set_pixel(0, 0, 9)`` -:param x: Wyświetlana kolumna (0..4) -:param y: Wyświetlany wiersz (0..4) -:param value: Jasność między 0 (wyłączona) i 9 (jasna)""" + :param x: The display column (0..4) + :param y: The display row (0..4) + :param value: The brightness between 0 (off) and 9 (bright) + """ ... def clear() -> None: - """Ustaw jasność wszystkich diod LED na 0 (wyłączone). + """Set the brightness of all LEDs to 0 (off). -Example: ``display.clear()``""" + Example: ``display.clear()`` + """ ... -def show(image: Union[str, float, int, Image, Iterable[Image]], delay: int=400, wait: bool=True, loop: bool=False, clear: bool=False) -> None: - """Pokazuje obrazy, litery lub cyfry na wyświetlaczu LED. +def show( + image: Union[str, float, int, Image, Iterable[Image]], + delay: int = 400, + wait: bool = True, + loop: bool = False, + clear: bool = False, +) -> None: + """Shows images, letters or digits on the LED display. -Example: ``display.show(Image.HEART)`` + Example: ``display.show(Image.HEART)`` -When ``image`` is an image or a list of images then each image is displayed in turn. -If ``image`` is a string or number, each letter or digit is displayed in turn. + When ``image`` is an image or a list of images then each image is displayed in turn. + If ``image`` is a string or number, each letter or digit is displayed in turn. -:param image: Łańcuch, liczba, obraz lub lista obrazów do pokazania. -:param delay: Każda litera, cyfra lub obraz są wyświetlane z ``delay`` milisekundami między sobą. -:param wait: Jeśli ``wait`` jest ``True``, ta funkcja będzie blokować, aż zakończy się animacja, w przeciwnym razie animacja pojawi się w tle. -:param loop: Jeśli ``loop`` jest ``True``, animacja będzie powtarzana w nieskończoność. -:param clear: Jeśli ``clear`` jest ``True``, wyświetlacz zostanie wyczyszczony po zakończeniu sekwencji. + :param image: A string, number, image or list of images to show. + :param delay: Each letter, digit or image is shown with ``delay`` milliseconds between them. + :param wait: If ``wait`` is ``True``, this function will block until the animation is finished, otherwise the animation will happen in the background. + :param loop: If ``loop`` is ``True``, the animation will repeat forever. + :param clear: If ``clear`` is ``True``, the display will be cleared after the sequence has finished. -The ``wait``, ``loop`` and ``clear`` arguments must be specified using their keyword.""" + The ``wait``, ``loop`` and ``clear`` arguments must be specified using their keyword. + """ ... -def scroll(text: Union[str, float, int], delay: int=150, wait: bool=True, loop: bool=False, monospace: bool=False) -> None: - """Przewija liczbę lub tekst na wyświetlaczu LED. - -Example: ``display.scroll('micro:bit')`` - -:param text: Łańcuch do przewinięcia. Jeśli ``text`` jest liczbą całkowitą lub zmiennopozycyjną, najpierw zostanie przekonwertowany na łańcuch za pomocą ``str()``. -:param delay: Parametr ``delay`` kontroluje szybkość przewijania tekstu. -:param wait: Jeśli ``wait`` jest ``True``, ta funkcja będzie blokować, aż zakończy się animacja, w przeciwnym razie animacja pojawi się w tle. -:param loop: Jeśli ``loop`` jest ``True``, animacja będzie powtarzana w nieskończoność. -:param monospace: Jeśli ``monospace`` jest ``True``, wszystkie znaki zajmą co najwyżej 5 kolumn pikseli na szerokość, w przeciwnym razie będzie dokładnie 1 pusta kolumna pikseli pomiędzy każdym znakiem, gdy się przewijają. - -The ``wait``, ``loop`` and ``monospace`` arguments must be specified -using their keyword.""" +def scroll( + text: Union[str, float, int], + delay: int = 150, + wait: bool = True, + loop: bool = False, + monospace: bool = False, +) -> None: + """Scrolls a number or text on the LED display. + + Example: ``display.scroll('micro:bit')`` + + :param text: The string to scroll. If ``text`` is an integer or float it is first converted to a string using ``str()``. + :param delay: The ``delay`` parameter controls how fast the text is scrolling. + :param wait: If ``wait`` is ``True``, this function will block until the animation is finished, otherwise the animation will happen in the background. + :param loop: If ``loop`` is ``True``, the animation will repeat forever. + :param monospace: 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. + + The ``wait``, ``loop`` and ``monospace`` arguments must be specified + using their keyword. + """ ... def on() -> None: - """Włącz wyświetlacz LED. + """Turn on the LED display. -Example: ``display.on()``""" + Example: ``display.on()`` + """ ... def off() -> None: - """Wyłącz wyświetlacz LED (wyłączenie wyświetlania pozwala na ponowne użycie pinów GPIO do innych celów). + """Turn off the LED display (disabling the display allows you to re-use the GPIO pins for other purposes). -Example: ``display.off()``""" + Example: ``display.off()`` + """ ... def is_on() -> bool: - """Sprawdź, czy wyświetlacz LED jest włączony. + """Check whether the LED display is enabled. -Example: ``display.is_on()`` + Example: ``display.is_on()`` -:return: ``True`` if the display is on, otherwise returns ``False``.""" + :return: ``True`` if the display is on, otherwise returns ``False``. + """ ... def read_light_level() -> int: - """Odczytuj poziom światła. + """Read the light level. -Example: ``display.read_light_level()`` + Example: ``display.read_light_level()`` -Uses the display's LEDs in reverse-bias mode to sense the amount of light -falling on the display. + Uses the display's LEDs in reverse-bias mode to sense the amount of light + falling on the display. -:return: An integer between 0 and 255 representing the light level, with larger meaning more light.""" - ... \ No newline at end of file + :return: An integer between 0 and 255 representing the light level, with larger meaning more light. + """ + ... diff --git a/lang/pl/typeshed/stdlib/microbit/i2c.pyi b/lang/pl/typeshed/stdlib/microbit/i2c.pyi index 0adc4a4..df26efa 100644 --- a/lang/pl/typeshed/stdlib/microbit/i2c.pyi +++ b/lang/pl/typeshed/stdlib/microbit/i2c.pyi @@ -1,49 +1,57 @@ -"""Komunikuj się z urządzeniami za pomocą protokołu magistrali I2C.""" +"""Communicate with devices using the I²C bus protocol. +""" + from _typeshed import ReadableBuffer from ..microbit import MicroBitDigitalPin, pin19, pin20 from typing import List -def init(freq: int=100000, sda: MicroBitDigitalPin=pin20, scl: MicroBitDigitalPin=pin19) -> None: - """Ponownie zainicjuj peryferia. +def init( + freq: int = 100000, sda: MicroBitDigitalPin = pin20, scl: MicroBitDigitalPin = pin19 +) -> None: + """Re-initialize a peripheral. -Example: ``i2c.init()`` + Example: ``i2c.init()`` -:param freq: clock frequency -:param sda: ``sda`` pin (domyślnie 20) -:param scl: ``scl`` pin (domyślnie 19) + :param freq: clock frequency + :param sda: ``sda`` pin (default 20) + :param scl: ``scl`` pin (default 19) -On a micro:bit V1 board, changing the I²C pins from defaults will make -the accelerometer and compass stop working, as they are connected -internally to those pins. This warning does not apply to the **V2** -revision of the micro:bit as this has `separate I²C lines `_ -for the motion sensors and the edge connector.""" + On a micro:bit V1 board, changing the I²C pins from defaults will make + the accelerometer and compass stop working, as they are connected + internally to those pins. This warning does not apply to the **V2** + revision of the micro:bit as this has `separate I²C lines `_ + for the motion sensors and the edge connector. + """ ... def scan() -> List[int]: - """Przeskanuj magistralę w poszukiwaniu urządzeń. + """Scan the bus for devices. -Example: ``i2c.scan()`` + Example: ``i2c.scan()`` -:return: A list of 7-bit addresses corresponding to those devices that responded to the scan.""" + :return: A list of 7-bit addresses corresponding to those devices that responded to the scan. + """ ... -def read(addr: int, n: int, repeat: bool=False) -> bytes: - """Odczytaj bajty z urządzenia.. +def read(addr: int, n: int, repeat: bool = False) -> bytes: + """Read bytes from a device. -Example: ``i2c.read(0x50, 64)`` + Example: ``i2c.read(0x50, 64)`` -:param addr: 7-bitowy adres urządzenia -:param n: Liczba bajtów do odczytu -:param repeat: Jeśli ``True``, nie zostaną wysłane żadne bity zatrzymania -:return: The bytes read""" + :param addr: The 7-bit address of the device + :param n: The number of bytes to read + :param repeat: If ``True``, no stop bit will be sent + :return: The bytes read + """ ... -def write(addr: int, buf: ReadableBuffer, repeat: bool=False) -> None: - """Zapisz bajty na urządzenie. +def write(addr: int, buf: ReadableBuffer, repeat: bool = False) -> None: + """Write bytes to a device. -Example: ``i2c.write(0x50, bytes([1, 2, 3]))`` + Example: ``i2c.write(0x50, bytes([1, 2, 3]))`` -:param addr: 7-bitowy adres urządzenia -:param buf: Bufor zawierający bajty do zapisu -:param repeat: Jeśli ``True``, nie zostaną wysłane żadne bity zatrzymania""" - ... \ No newline at end of file + :param addr: The 7-bit address of the device + :param buf: A buffer containing the bytes to write + :param repeat: If ``True``, no stop bit will be sent + """ + ... diff --git a/lang/pl/typeshed/stdlib/microbit/microphone.pyi b/lang/pl/typeshed/stdlib/microbit/microphone.pyi index 368df6f..68e8f3a 100644 --- a/lang/pl/typeshed/stdlib/microbit/microphone.pyi +++ b/lang/pl/typeshed/stdlib/microbit/microphone.pyi @@ -1,62 +1,70 @@ -"""Odpowiedz na dźwięk przy użyciu wbudowanego mikrofonu (tylko V2).""" +"""Respond to sound using the built-in microphone (V2 only). +""" + from typing import Optional, Tuple from ..microbit import SoundEvent def current_event() -> Optional[SoundEvent]: - """Pobierz ostatnie nagrane zdarzenie dźwiękowe + """Get the last recorded sound event -Example: ``microphone.current_event()`` + Example: ``microphone.current_event()`` -:return: The event, ``SoundEvent('loud')`` or ``SoundEvent('quiet')``.""" + :return: The event, ``SoundEvent('loud')`` or ``SoundEvent('quiet')``. + """ ... def was_event(event: SoundEvent) -> bool: - """Sprawdź, czy dźwięk był słyszany co najmniej raz od ostatniego połączenia. + """Check if a sound was heard at least once since the last call. -Example: ``microphone.was_event(SoundEvent.LOUD)`` + Example: ``microphone.was_event(SoundEvent.LOUD)`` -This call clears the sound history before returning. + This call clears the sound history before returning. -:param event: Zdarzenie do sprawdzenia, takie jak ``SoundEvent.LOUD`` lub ``SoundEvent.QUIET`` -:return: ``True`` if sound was heard at least once since the last call, otherwise ``False``.""" + :param event: The event to check for, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET`` + :return: ``True`` if sound was heard at least once since the last call, otherwise ``False``. + """ ... def is_event(event: SoundEvent) -> bool: - """Sprawdź najnowsze wykryte zdarzenie dźwiękowe. + """Check the most recent sound event detected. -Example: ``microphone.is_event(SoundEvent.LOUD)`` + Example: ``microphone.is_event(SoundEvent.LOUD)`` -This call does not clear the sound event history. + This call does not clear the sound event history. -:param event: Zdarzenie do sprawdzenia, takie jak ``SoundEvent.LOUD`` lub ``SoundEvent.QUIET`` -:return: ``True`` if sound was the most recent heard, ``False`` otherwise.""" + :param event: The event to check for, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET`` + :return: ``True`` if sound was the most recent heard, ``False`` otherwise. + """ ... def get_events() -> Tuple[SoundEvent, ...]: - """Pobierz historię zdarzeń dźwiękowych jako krotkę. + """Get the sound event history as a tuple. -Example: ``microphone.get_events()`` + Example: ``microphone.get_events()`` -This call clears the sound history before returning. + This call clears the sound history before returning. -:return: A tuple of the event history with the most recent event last.""" + :return: A tuple of the event history with the most recent event last. + """ ... def set_threshold(event: SoundEvent, value: int) -> None: - """Ustaw próg dla zdarzenia dźwiękowego. + """Set the threshold for a sound event. -Example: ``microphone.set_threshold(SoundEvent.LOUD, 250)`` + Example: ``microphone.set_threshold(SoundEvent.LOUD, 250)`` -A high threshold means the event will only trigger if the sound is very loud (>= 250 in the example). + A high threshold means the event will only trigger if the sound is very loud (>= 250 in the example). -:param event: Zdarzenie dźwiękowe, takie jak ``SoundEvent.LOUD`` lub ``SoundEvent.QUIET``. -:param value: Poziom progu w zakresie 0-255.""" + :param event: A sound event, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET``. + :param value: The threshold level in the range 0-255. + """ ... def sound_level() -> int: - """Uzyskaj poziom ciśnienia akustycznego. + """Get the sound pressure level. -Example: ``microphone.sound_level()`` + Example: ``microphone.sound_level()`` -:return: A representation of the sound pressure level in the range 0 to 255.""" - ... \ No newline at end of file + :return: A representation of the sound pressure level in the range 0 to 255. + """ + ... diff --git a/lang/pl/typeshed/stdlib/microbit/speaker.pyi b/lang/pl/typeshed/stdlib/microbit/speaker.pyi index 9cd1b88..5a74a4d 100644 --- a/lang/pl/typeshed/stdlib/microbit/speaker.pyi +++ b/lang/pl/typeshed/stdlib/microbit/speaker.pyi @@ -1,15 +1,18 @@ -"""Sprawdź wbudowany głośnik (tylko V2).""" +"""Control the built-in speaker (V2 only). +""" def off() -> None: - """Wyłącz głośnik. + """Turn the speaker off. -Example: ``speaker.off()`` + Example: ``speaker.off()`` -This does not disable sound output to an edge connector pin.""" + This does not disable sound output to an edge connector pin. + """ ... def on() -> None: - """Włącz głośnik. + """Turn the speaker on. -Example: ``speaker.on()``""" - ... \ No newline at end of file + Example: ``speaker.on()`` + """ + ... diff --git a/lang/pl/typeshed/stdlib/microbit/spi.pyi b/lang/pl/typeshed/stdlib/microbit/spi.pyi index b6e67aa..09c4046 100644 --- a/lang/pl/typeshed/stdlib/microbit/spi.pyi +++ b/lang/pl/typeshed/stdlib/microbit/spi.pyi @@ -1,47 +1,60 @@ -"""Komunikuj się z urządzeniami za pomocą magistrali szeregowego interfejsu (SPI).""" +"""Communicate with devices using the serial peripheral interface (SPI) bus. +""" + from _typeshed import ReadableBuffer, WriteableBuffer from ..microbit import pin13, pin14, pin15, MicroBitDigitalPin -def init(baudrate: int=1000000, bits: int=8, mode: int=0, sclk: MicroBitDigitalPin=pin13, mosi: MicroBitDigitalPin=pin15, miso: MicroBitDigitalPin=pin14) -> None: - """Zainicjuj komunikację SPI. - -Example: ``spi.init()`` - -For correct communication, the parameters have to be the same on both communicating devices. - -:param baudrate: Szybkość komunikacji. -:param bits: Szerokość w bitach każdego transferu. Obecnie obsługiwanych jest tylko ``bits=8``. Może to jednak ulec zmianie w przyszłości. -:param mode: Określa połączenie polarności zegara i fazy - `zobacz tabelę online `_. -:param sclk: pin sclk (domyślnie 13) -:param mosi: pin mosi (domyślnie 15) -:param miso: pin miso (domyślnie 14)""" +def init( + baudrate: int = 1000000, + bits: int = 8, + mode: int = 0, + sclk: MicroBitDigitalPin = pin13, + mosi: MicroBitDigitalPin = pin15, + miso: MicroBitDigitalPin = pin14, +) -> None: + """Initialize SPI communication. + + Example: ``spi.init()`` + + For correct communication, the parameters have to be the same on both communicating devices. + + :param baudrate: The speed of communication. + :param bits: The width in bits of each transfer. Currently only ``bits=8`` is supported. However, this may change in the future. + :param mode: Determines the combination of clock polarity and phase - `see online table `_. + :param sclk: sclk pin (default 13) + :param mosi: mosi pin (default 15) + :param miso: miso pin (default 14) + """ ... -def read(nbytes: int, out: int=0) -> bytes: - """Czytaj bajty. +def read(nbytes: int, out: int = 0) -> bytes: + """Read at most ``nbytes`` while continuously writing the single byte given by ``out``. -Example: ``spi.read(64)`` + Example: ``spi.read(64)`` -:param nbytes: Maksymalna liczba bajtów do odczytu. -:param out: The byte value to write (default 0). -:return: The bytes read.""" + :param nbytes: Maximum number of bytes to read. + :param out: The byte value to write (default 0). + :return: The bytes read. + """ ... def write(buffer: ReadableBuffer) -> None: - """Zapisz bajty na magistrali. + """Write bytes to the bus. -Example: ``spi.write(bytes([1, 2, 3]))`` + Example: ``spi.write(bytes([1, 2, 3]))`` -:param buffer: Bufor do odczytu danych.""" + :param buffer: A buffer to read data from. + """ ... def write_readinto(out: WriteableBuffer, in_: ReadableBuffer) -> None: - """Zapisz bufor ``out`` do magistrali i wczytaj dowolną odpowiedź do bufora ``in_``. + """Write the ``out`` buffer to the bus and read any response into the ``in_`` buffer. -Example: ``spi.write_readinto(out_buffer, in_buffer)`` + Example: ``spi.write_readinto(out_buffer, in_buffer)`` -The length of the buffers should be the same. The buffers can be the same object. + The length of the buffers should be the same. The buffers can be the same object. -:param out: Bufor do zapisu dowolnej odpowiedzi. -:param in_: Bufor do odczytu danych.""" - ... \ No newline at end of file + :param out: The buffer to write any response to. + :param in_: The buffer to read data from. + """ + ... diff --git a/lang/pl/typeshed/stdlib/microbit/uart.pyi b/lang/pl/typeshed/stdlib/microbit/uart.pyi index 375b560..2ab650f 100644 --- a/lang/pl/typeshed/stdlib/microbit/uart.pyi +++ b/lang/pl/typeshed/stdlib/microbit/uart.pyi @@ -1,79 +1,96 @@ -"""Komunikuj się z urządzeniem za pomocą interfejsu szeregowego.""" +"""Communicate with a device using a serial interface. +""" + from _typeshed import WriteableBuffer from ..microbit import MicroBitDigitalPin from typing import Optional, Union -ODD: int -"""Nieparzysta parzystość""" -EVEN: int -"""Parzysta parzystość""" - -def init(baudrate: int=9600, bits: int=8, parity: Optional[int]=None, stop: int=1, tx: Optional[MicroBitDigitalPin]=None, rx: Optional[MicroBitDigitalPin]=None) -> None: - """Zainicjuj komunikację seryjną. - -Example: ``uart.init(115200, tx=pin0, rx=pin1)`` -:param baudrate: Szybkość komunikacji. -:param bits: Rozmiar przesyłanych bajtów. micro:bit obsługuje tylko 8. -:param parity: Jak sprawdzana jest parzystość, ``None``, ``uart.ODD`` lub ``uart.EVEN``. -:param stop: Liczba bitów stopu musi wynosić 1 dla micro:bita. -:param tx: Transmitując pin. -:param rx: Odbieranie pinu. - -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. +ODD: int +"""Odd parity""" -For more details see `the online documentation `_.""" +EVEN: int +"""Even parity""" + +def init( + baudrate: int = 9600, + bits: int = 8, + parity: Optional[int] = None, + stop: int = 1, + tx: Optional[MicroBitDigitalPin] = None, + rx: Optional[MicroBitDigitalPin] = None, +) -> None: + """Initialize serial communication. + + Example: ``uart.init(115200, tx=pin0, rx=pin1)`` + + :param baudrate: The speed of communication. + :param bits: The size of bytes being transmitted. micro:bit only supports 8. + :param parity: How parity is checked, ``None``, ``uart.ODD`` or ``uart.EVEN``. + :param stop: The number of stop bits, has to be 1 for micro:bit. + :param tx: Transmitting pin. + :param rx: Receiving pin. + + 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. + + For more details see `the online documentation `_. + """ ... def any() -> bool: - """Sprawdź, czy czekają jakieś dane. + """Check if any data is waiting. -Example: ``uart.any()`` + Example: ``uart.any()`` -:return: ``True`` if any data is waiting, else ``False``.""" + :return: ``True`` if any data is waiting, else ``False``. + """ ... -def read(nbytes: Optional[int]=None) -> Optional[bytes]: - """Czytaj bajty. +def read(nbytes: Optional[int] = None) -> Optional[bytes]: + """Read bytes. -Example: ``uart.read()`` + Example: ``uart.read()`` -:param nbytes: Jeśli ``nbytes`` jest określony, przeczytaj co najwyżej tę liczbę bajtów, w przeciwnym razie przeczytaj jak najwięcej bajtów -:return: A bytes object or ``None`` on timeout""" + :param nbytes: If ``nbytes`` is specified then read at most that many bytes, otherwise read as many bytes as possible + :return: A bytes object or ``None`` on timeout + """ ... -def readinto(buf: WriteableBuffer, nbytes: Optional[int]=None) -> Optional[int]: - """Przeczytaj bajty do ``buf``. +def readinto(buf: WriteableBuffer, nbytes: Optional[int] = None) -> Optional[int]: + """Read bytes into the ``buf``. -Example: ``uart.readinto(input_buffer)`` + Example: ``uart.readinto(input_buffer)`` -:param buf: Bufor do zapisu. -:param nbytes: Jeśli ``nbytes`` jest określony, przeczytaj co najwyżej tę liczbę bajtów, w przeciwnym razie przeczytaj ``len(buf)`` bajtów. -:return: number of bytes read and stored into ``buf`` or ``None`` on timeout.""" + :param buf: The buffer to write to. + :param nbytes: If ``nbytes`` is specified then read at most that many bytes, otherwise read ``len(buf)`` bytes. + :return: number of bytes read and stored into ``buf`` or ``None`` on timeout. + """ ... def readline() -> Optional[bytes]: - """Przeczytaj wiersz kończący się znakiem nowej linii. + """Read a line, ending in a newline character. -Example: ``uart.readline()`` + Example: ``uart.readline()`` -:return: The line read or ``None`` on timeout. The newline character is included in the returned bytes.""" + :return: The line read or ``None`` on timeout. The newline character is included in the returned bytes. + """ ... def write(buf: Union[bytes, str]) -> Optional[int]: - """Zapisz bufor na magistrali. + """Write a buffer to the bus. -Example: ``uart.write('hello world')`` + Example: ``uart.write('hello world')`` -:param buf: Obiekt bajtów lub łańcuch. -:return: The number of bytes written, or ``None`` on timeout. + :param buf: A bytes object or a string. + :return: The number of bytes written, or ``None`` on timeout. -Examples:: + Examples:: - uart.write('hello world') - uart.write(b'hello world') - uart.write(bytes([1, 2, 3]))""" - ... \ No newline at end of file + uart.write('hello world') + uart.write(b'hello world') + uart.write(bytes([1, 2, 3])) + """ + ... diff --git a/lang/pl/typeshed/stdlib/micropython.pyi b/lang/pl/typeshed/stdlib/micropython.pyi index 7e87975..7a6079f 100644 --- a/lang/pl/typeshed/stdlib/micropython.pyi +++ b/lang/pl/typeshed/stdlib/micropython.pyi @@ -1,132 +1,144 @@ -"""Wewnątrz MicroPythona. (microPython)""" +"""MicroPython internals.""" + from typing import Any, TypeVar, overload -_T = TypeVar('_T') + +_T = TypeVar("_T") def const(expr: _T) -> _T: - """Służy do zadeklarowania, że wyrażenie jest stałą tak, że kompilator może -je zoptymalizować. + """Used to declare that the expression is a constant so that the compiler can + optimise it. -The use of this function should be as follows:: + The use of this function should be as follows:: - from micropython import const - CONST_X = const(123) - CONST_Y = const(2 * CONST_X + 1) + from micropython import const + CONST_X = const(123) + CONST_Y = const(2 * CONST_X + 1) -Constants declared this way are still accessible as global variables from -outside the module they are declared in. On the other hand, if a constant -begins with an underscore then it is hidden, it is not available as a -global variable, and does not take up any memory during execution. + Constants declared this way are still accessible as global variables from + outside the module they are declared in. On the other hand, if a constant + begins with an underscore then it is hidden, it is not available as a + global variable, and does not take up any memory during execution. -:param expr: Wyrażenie stałe.""" + :param expr: A constant expression. + """ ... @overload def opt_level() -> int: - """Uzyskaj obecny poziom optymalizacji dla kompilacji skryptów. + """Get the current optimisation level for the compilation of scripts. -Example: ``micropython.opt_level()`` + Example: ``micropython.opt_level()`` -The optimisation level controls the following compilation features: + The optimisation level controls the following compilation features: -- Assertions: at level 0 assertion statements are enabled and compiled - into the bytecode; at levels 1 and higher assertions are not compiled. + - Assertions: at level 0 assertion statements are enabled and compiled + into the bytecode; at levels 1 and higher assertions are not compiled. -- Built-in ``__debug__`` variable: at level 0 this variable expands to - True; at levels 1 and higher it expands to False. + - Built-in ``__debug__`` variable: at level 0 this variable expands to + True; at levels 1 and higher it expands to False. -- Source-code line numbers: at levels 0, 1 and 2 source-code line number - are stored along with the bytecode so that exceptions can report the - line number they occurred at; at levels 3 and higher line numbers are - not stored. + - Source-code line numbers: at levels 0, 1 and 2 source-code line number + are stored along with the bytecode so that exceptions can report the + line number they occurred at; at levels 3 and higher line numbers are + not stored. -:return: An integer representing the current level.""" + :return: An integer representing the current level. + """ ... @overload def opt_level(level: int) -> None: - """Ustawia poziom optymalizacji dla późniejszej kompilacji skryptów. + """Sets the optimisation level for subsequent compilation of scripts. -Example: ``micropython.opt_level(1)`` + Example: ``micropython.opt_level(1)`` -The optimisation level controls the following compilation features: + The optimisation level controls the following compilation features: -- Assertions: at level 0 assertion statements are enabled and compiled - into the bytecode; at levels 1 and higher assertions are not compiled. + - Assertions: at level 0 assertion statements are enabled and compiled + into the bytecode; at levels 1 and higher assertions are not compiled. -- Built-in ``__debug__`` variable: at level 0 this variable expands to - True; at levels 1 and higher it expands to False. + - Built-in ``__debug__`` variable: at level 0 this variable expands to + True; at levels 1 and higher it expands to False. -- Source-code line numbers: at levels 0, 1 and 2 source-code line number - are stored along with the bytecode so that exceptions can report the - line number they occurred at; at levels 3 and higher line numbers are - not stored. + - Source-code line numbers: at levels 0, 1 and 2 source-code line number + are stored along with the bytecode so that exceptions can report the + line number they occurred at; at levels 3 and higher line numbers are + not stored. -The default optimisation level is usually level 0. + The default optimisation level is usually level 0. -:param level: Poziom optymalizacji całkowity.""" + :param level: An integer optimisation level. + """ ... -def mem_info(verbose: Any=None) -> None: - """Drukuj informacje o aktualnie używanej pamięci. +def mem_info(verbose: Any = None) -> None: + """Print information about currently used memory. -Example: ``micropython.mem_info()`` + Example: ``micropython.mem_info()`` -:param verbose: Jeśli dany jest argument ``verbose``, drukowane są dodatkowe informacje.""" + :param verbose: If the ``verbose`` argument is given then extra information is printed. + """ ... -def qstr_info(verbose: Any=None) -> None: - """Drukuj informacje o aktualnie internowanych łańcuchach. +def qstr_info(verbose: Any = None) -> None: + """Print information about currently interned strings. -Example: ``micropython.qstr_info()`` + Example: ``micropython.qstr_info()`` -:param verbose: Jeśli dany jest argument ``verbose``, drukowane są dodatkowe informacje. + :param verbose: If the ``verbose`` argument is given then extra information is printed. -The information that is printed is implementation dependent, but currently -includes the number of interned strings and the amount of RAM they use. In -verbose mode it prints out the names of all RAM-interned strings.""" + The information that is printed is implementation dependent, but currently + includes the number of interned strings and the amount of RAM they use. In + verbose mode it prints out the names of all RAM-interned strings. + """ ... def stack_use() -> int: - """Zwróć liczbę całkowitą reprezentującą aktualną wielkość używanego stosu + """Return an integer representing the current amount of stack that is being + used. -Example: ``micropython.stack_use()`` + Example: ``micropython.stack_use()`` -The absolute value of this is not particularly useful, rather it -should be used to compute differences in stack usage at different points. + The absolute value of this is not particularly useful, rather it + should be used to compute differences in stack usage at different points. -:return: An integer representing current stack use.""" + :return: An integer representing current stack use. + """ ... def heap_lock() -> None: - """Zablokuj stos. + """Lock the heap. -Example: ``micropython.heap_lock()`` + Example: ``micropython.heap_lock()`` -When locked no memory allocation can occur and a ``MemoryError`` will be -raised if any heap allocation is attempted.""" + When locked no memory allocation can occur and a ``MemoryError`` will be + raised if any heap allocation is attempted. + """ ... def heap_unlock() -> None: - """Odblokuj stos. + """Unlock the heap. -Example: ``micropython.heap_unlock()`` + Example: ``micropython.heap_unlock()`` -When locked no memory allocation can occur and a ``MemoryError`` will be -raised if any heap allocation is attempted.""" + When locked no memory allocation can occur and a ``MemoryError`` will be + raised if any heap allocation is attempted. + """ ... def kbd_intr(chr: int) -> None: - """Ustaw znak, który zgłosi wyjątek ``KeyboardInterrupt``. + """Set the character that will raise a ``KeyboardInterrupt`` exception. -Example: ``micropython.kbd_intr(-1)`` + Example: ``micropython.kbd_intr(-1)`` -:param chr: Kod znaku, aby zwiększyć przerwę lub -1, aby wyłączyć przechwytywanie Ctrl-C. + :param chr: Character code to raise the interrupt or -1 to disable capture of Ctrl-C. -By default this is set to 3 during script execution, corresponding to Ctrl-C. -Passing -1 to this function will disable capture of Ctrl-C, and passing 3 -will restore it. + By default this is set to 3 during script execution, corresponding to Ctrl-C. + Passing -1 to this function will disable capture of Ctrl-C, and passing 3 + will restore it. -This function can be used to prevent the capturing of Ctrl-C on the -incoming stream of characters that is usually used for the REPL, in case -that stream is used for other purposes.""" - ... \ No newline at end of file + This function can be used to prevent the capturing of Ctrl-C on the + incoming stream of characters that is usually used for the REPL, in case + that stream is used for other purposes. + """ + ... diff --git a/lang/pl/typeshed/stdlib/music.pyi b/lang/pl/typeshed/stdlib/music.pyi index cee40a5..5f4778b 100644 --- a/lang/pl/typeshed/stdlib/music.pyi +++ b/lang/pl/typeshed/stdlib/music.pyi @@ -1,128 +1,167 @@ -"""Twórz i graj w melodie.""" +"""Create and play melodies. +""" from typing import Optional, Tuple, Union, List + from .microbit import MicroBitDigitalPin, pin0 + DADADADUM: Tuple[str, ...] -"""Melodia: otwarcie 5. symfonii Beethovena w C minor""" +"""Melody: the opening to Beethoven’s 5th Symphony in C minor.""" + ENTERTAINER: Tuple[str, ...] -"""Melodia: fragment otwierający klasyczny Scott Joplin Ragtime "The Entertainer".""" +"""Melody: the opening fragment of Scott Joplin’s Ragtime classic “The Entertainer”.""" + PRELUDE: Tuple[str, ...] -"""Melodia: otwarcie pierwszego Preludium w C Major, 48 preludiów i Fug J.S.Bacha.""" +"""Melody: the opening of the first Prelude in C Major of J.S.Bach’s 48 Preludes and Fugues.""" + ODE: Tuple[str, ...] -"""Melodia: motyw Ody do radości z 9. Symfonii Beethovena w D minor.""" +"""Melody: the “Ode to Joy” theme from Beethoven’s 9th Symphony in D minor.""" + NYAN: Tuple[str, ...] -"""Melodia: motyw Nyan Kot (http://www.nyan.cat/). +"""Melody: the Nyan Cat theme (http://www.nyan.cat/). The composer is unknown. This is fair use for educational porpoises (as they say in New York).""" + RINGTONE: Tuple[str, ...] -"""Melodia: coś, co brzmi jak dzwonek telefonu komórkowego. +"""Melody: something that sounds like a mobile phone ringtone. To be used to indicate an incoming message. """ + FUNK: Tuple[str, ...] -"""Melody: funkowa linia basu dla tajnych agentów i geniuszy kryminalnych.""" +"""Melody: a funky bass line for secret agents and criminal masterminds.""" + BLUES: Tuple[str, ...] -"""Melodia: 12-taktowy bluesowy chodzący bas w stylu boogie-woogie.""" +"""Melody: a boogie-woogie 12-bar blues walking bass.""" + BIRTHDAY: Tuple[str, ...] -"""Melodia: "Wszystkiego najlepszego…" +"""Melody: “Happy Birthday to You…” For copyright status see: http://www.bbc.co.uk/news/world-us-canada-34332853 """ + WEDDING: Tuple[str, ...] -"""Melodia: chór panny młodej z opery Wagnera „Lohengrin”. (ślub)""" +"""Melody: the bridal chorus from Wagner’s opera “Lohengrin”.""" + FUNERAL: Tuple[str, ...] -"""Melodia: »Marsz pogrzebowy« znany jako Sonata Fortepianowa No. 2 w B♭ minor, Op. 35 Fryderyka Chopina. (pogrzeb)""" +"""Melody: the “funeral march” otherwise known as Frédéric Chopin’s Piano Sonata No. 2 in B♭ minor, Op. 35.""" + PUNCHLINE: Tuple[str, ...] -"""Melodia: zabawny fragment oznaczający, że zażartowano.""" +"""Melody: a fun fragment that signifies a joke has been made.""" + PYTHON: Tuple[str, ...] -"""Melodia: Marsz John Philip Sousa „Liberty Bell” aka, motyw „Monty Python Flating Circus” (po którym nazwano język programowania Pythona).""" +"""Melody: John Philip Sousa’s march “Liberty Bell” aka, the theme for “Monty Python’s Flying Circus” (after which the Python programming language is named).""" + BADDY: Tuple[str, ...] -"""Melodia: wejście złego człowieka do ery kina niemego.""" +"""Melody: silent movie era entrance of a baddy.""" + CHASE: Tuple[str, ...] -"""Melodia: scena pościgu z epoki kina niemego.""" +"""Melody: silent movie era chase scene.""" + BA_DING: Tuple[str, ...] -"""Melodia: krótki sygnał informujący, że coś się wydarzyło.""" +"""Melody: a short signal to indicate something has happened.""" + WAWAWAWAA: Tuple[str, ...] -"""Melodia: bardzo smutny puzon.""" +"""Melody: a very sad trombone.""" + JUMP_UP: Tuple[str, ...] -"""Melodia: do użytku w grze, wskazujący ruch w górę.""" +"""Melody: for use in a game, indicating upward movement.""" + JUMP_DOWN: Tuple[str, ...] -"""Melodia: do użytku w grze, wskazujący ruch w górę.""" +"""Melody: for use in a game, indicating downward movement.""" + POWER_UP: Tuple[str, ...] -"""Melodia: fanfara oznaczająca odblokowanie osiągnięcia.""" +"""Melody: a fanfare to indicate an achievement unlocked.""" + POWER_DOWN: Tuple[str, ...] -"""Melodia: smutna fanfara oznaczająca utracenie osiągnięcia.""" +"""Melody: a sad fanfare to indicate an achievement lost.""" -def set_tempo(ticks: int=4, bpm: int=120) -> None: - """Ustawia przybliżone tempo dla odtwarzania. +def set_tempo(ticks: int = 4, bpm: int = 120) -> None: + """Sets the approximate tempo for playback. -Example: ``music.set_tempo(bpm=120)`` + Example: ``music.set_tempo(bpm=120)`` -:param ticks: Liczba taktów składających się na uderzenie. -:param bpm: Liczba całkowita określająca liczbę uderzeń na minutę. + :param ticks: The number of ticks constituting a beat. + :param bpm: An integer determining how many beats per minute. -Suggested default values allow the following useful behaviour: + Suggested default values allow the following useful behaviour: -- music.set_tempo() – reset the tempo to default of ticks = 4, bpm = 120 -- music.set_tempo(ticks=8) – change the “definition” of a beat -- music.set_tempo(bpm=180) – just change the tempo + - music.set_tempo() – reset the tempo to default of ticks = 4, bpm = 120 + - music.set_tempo(ticks=8) – change the “definition” of a beat + - music.set_tempo(bpm=180) – just change the tempo -To work out the length of a tick in milliseconds is very simple arithmetic: -60000/bpm/ticks_per_beat. For the default values that’s -60000/120/4 = 125 milliseconds or 1 beat = 500 milliseconds.""" + To work out the length of a tick in milliseconds is very simple arithmetic: + 60000/bpm/ticks_per_beat. For the default values that’s + 60000/120/4 = 125 milliseconds or 1 beat = 500 milliseconds. + """ ... def get_tempo() -> Tuple[int, int]: - """Pobiera bieżące tempo jako parę liczb całkowitych: ``(ticks, bpm)``. + """Gets the current tempo as a tuple of integers: ``(ticks, bpm)``. -Example: ``ticks, beats = music.get_tempo()`` + Example: ``ticks, beats = music.get_tempo()`` -:return: The temp as a tuple with two integer values, the ticks then the beats per minute.""" + :return: The temp as a tuple with two integer values, the ticks then the beats per minute. + """ ... -def play(music: Union[str, List[str], Tuple[str, ...]], pin: Optional[MicroBitDigitalPin]=pin0, wait: bool=True, loop: bool=False) -> None: - """Odtwarzaj muzykę. +def play( + music: Union[str, List[str], Tuple[str, ...]], + pin: Optional[MicroBitDigitalPin] = pin0, + wait: bool = True, + loop: bool = False, +) -> None: + """Plays music. -Example: ``music.play(music.NYAN)`` + Example: ``music.play(music.NYAN)`` -:param music: muzyka określona w `specjalnej notacji `_ -:param pin: pin wyjściowy do użycia z zewnętrznym głośnikiem (domyślnie ``pin0``), ``None`` dla braku dźwięku. -:param wait: Jeśli ``wait`` jest ustawiony na ``True``, ta funkcja jest blokowana. -:param loop: Jeśli ``loop`` jest ustawiony na ``True``, melodia powtarza się, aż ``stop`` jest wywołana lub połączenie blokujące zostanie przerwane. + :param music: music specified in `a special notation `_ + :param pin: the output pin for use with an external speaker (default ``pin0``), ``None`` for no sound. + :param wait: If ``wait`` is set to ``True``, this function is blocking. + :param loop: If ``loop`` is set to ``True``, the tune repeats until ``stop`` is called or the blocking call is interrupted. -Many built-in melodies are defined in this module.""" + Many built-in melodies are defined in this module. + """ ... -def pitch(frequency: int, duration: int=-1, pin: Optional[MicroBitDigitalPin]=pin0, wait: bool=True) -> None: - """Zagraj nutę. +def pitch( + frequency: int, + duration: int = -1, + pin: Optional[MicroBitDigitalPin] = pin0, + wait: bool = True, +) -> None: + """Play a note. -Example: ``music.pitch(185, 1000)`` + Example: ``music.pitch(185, 1000)`` -:param frequency: Częstotliwość całkowitoliczbowa -:param duration: Czas trwania w milisekundach. Jeśli ujemny, to dźwięk jest ciągły aż do następnego połączenia lub połączenia z ``stop``. -:param pin: Opcjonalny pin wyjściowy (domyślny ``pin0``). -:param wait: Jeśli ``wait`` jest ustawiony na ``True``, ta funkcja jest blokowana. + :param frequency: An integer frequency + :param duration: A millisecond duration. If negative then sound is continuous until the next call or a call to ``stop``. + :param pin: Optional output pin (default ``pin0``). + :param wait: If ``wait`` is set to ``True``, this function is blocking. -For example, if the frequency is set to 440 and the length to -1000 then we hear a standard concert A for one second. + For example, if the frequency is set to 440 and the length to + 1000 then we hear a standard concert A for one second. -You can only play one pitch on one pin at any one time.""" + You can only play one pitch on one pin at any one time. + """ ... -def stop(pin: Optional[MicroBitDigitalPin]=pin0) -> None: - """Zatrzymuje odtwarzanie muzyki na wbudowanym głośniku i jakimkolwiek pinie wyjściowym dźwięku. +def stop(pin: Optional[MicroBitDigitalPin] = pin0) -> None: + """Stops all music playback on the built-in speaker and any pin outputting sound. -Example: ``music.stop()`` + Example: ``music.stop()`` -:param pin: Opcjonalny argument może być podany do określenia pinu, np. ``music.stop(pin1)``.""" + :param pin: An optional argument can be provided to specify a pin, e.g. ``music.stop(pin1)``. + """ def reset() -> None: - """Resetuje takty, bpm, czas trwania i oktawę do ich wartości domyślnych. + """Resets ticks, bpm, duration and octave to their default values. -Example: ``music.reset()`` + Example: ``music.reset()`` -Values: -- ``ticks = 4`` -- ``bpm = 120`` -- ``duration = 4`` -- ``octave = 4``""" - ... \ No newline at end of file + Values: + - ``ticks = 4`` + - ``bpm = 120`` + - ``duration = 4`` + - ``octave = 4`` + """ + ... diff --git a/lang/pl/typeshed/stdlib/neopixel.pyi b/lang/pl/typeshed/stdlib/neopixel.pyi index 822e46b..2d5a749 100644 --- a/lang/pl/typeshed/stdlib/neopixel.pyi +++ b/lang/pl/typeshed/stdlib/neopixel.pyi @@ -1,81 +1,82 @@ -"""Indywidualnie adresowalne paski LED RGB i RGBW.""" +"""Individually addressable RGB and RGBW LED strips. +""" from .microbit import MicroBitDigitalPin from typing import Tuple class NeoPixel: + def __init__(self, pin: MicroBitDigitalPin, n: int, bpp: int = 3) -> None: + """Initialise a new strip of neopixel LEDs controlled via a pin. - def __init__(self, pin: MicroBitDigitalPin, n: int, bpp: int=3) -> None: - """Zainicjuj nowy pasek neopikselowych diod LED sterowanych za pomocą pinu. + Example: ``np = neopixel.NeoPixel(pin0, 8)`` -Example: ``np = neopixel.NeoPixel(pin0, 8)`` + To support RGBW neopixels, a third argument can be passed to + ``NeoPixel`` to indicate the number of bytes per pixel (``bpp``). + For RGBW, this is is 4 rather than the default of 3 for RGB and GRB. -To support RGBW neopixels, a third argument can be passed to -``NeoPixel`` to indicate the number of bytes per pixel (``bpp``). -For RGBW, this is is 4 rather than the default of 3 for RGB and GRB. + Each pixel is addressed by a position (starting from 0). Neopixels are + given RGB (red, green, blue) / RGBW (red, green, blue, white) values + between 0-255 as a tuple. For example, in RGB, ``(255,255,255)`` is + white. In RGBW, ``(255,255,255,0)`` or ``(0,0,0,255)`` is white. -Each pixel is addressed by a position (starting from 0). Neopixels are -given RGB (red, green, blue) / RGBW (red, green, blue, white) values -between 0-255 as a tuple. For example, in RGB, ``(255,255,255)`` is -white. In RGBW, ``(255,255,255,0)`` or ``(0,0,0,255)`` is white. + See `the online docs `_ for warnings and other advice. -See `the online docs `_ for warnings and other advice. - -:param pin: Pin kontrolujący pasek neopikseli. -:param n: Liczba neopikseli w pasku. -:param bpp: Bajty na piksel. W przypadku obsługi neopikseli RGBW należy przekazać 4 zamiast domyślnych 3 dla RGB i GRB.""" + :param pin: The pin controlling the neopixel strip. + :param n: The number of neopixels in the strip. + :param bpp: Bytes per pixel. For RGBW neopixel support, pass 4 rather than the default of 3 for RGB and GRB. + """ ... - def clear(self) -> None: - """Wyczyść wszystkie piksele. + """Clear all the pixels. -Example: ``np.clear()``""" + Example: ``np.clear()`` + """ ... - def show(self) -> None: - """Pokaż piksele. + """Show the pixels. -Example: ``np.show()`` + Example: ``np.show()`` -Must be called for any updates to become visible.""" + Must be called for any updates to become visible. + """ ... - def write(self) -> None: - """Pokaż piksele (tylko micro:bit V2). + """Show the pixels (micro:bit V2 only). -Example: ``np.write()`` + Example: ``np.write()`` -Must be called for any updates to become visible. + Must be called for any updates to become visible. -Equivalent to ``show``.""" + Equivalent to ``show``. + """ ... - def fill(self, colour: Tuple[int, ...]) -> None: - """Pokoloruj wszystkie piksele określoną wartością RGB/RGBW (tylko micro:bit V2). + """Colour all pixels a given RGB/RGBW value (micro:bit V2 only). -Example: ``np.fill((0, 0, 255))`` + Example: ``np.fill((0, 0, 255))`` -:param colour: Krotka o takiej samej długości jak liczba bajtów na piksel (bpp). + :param colour: A tuple of the same length as the number of bytes per pixel (bpp). -Use in conjunction with ``show()`` to update the neopixels.""" + Use in conjunction with ``show()`` to update the neopixels. + """ ... - def __setitem__(self, key: int, value: Tuple[int, ...]) -> None: - """Ustaw kolor pikseli. + """Set a pixel colour. -Example: ``np[0] = (255, 0, 0)`` - -:param key: Liczba pikseli. -:param value: Kolor""" + Example: ``np[0] = (255, 0, 0)`` + :param key: The pixel number. + :param value: The colour. + """ def __getitem__(self, key: int) -> Tuple[int, ...]: - """Uzyskaj kolor piksela. - -Example: ``r, g, b = np[0]`` + """Get a pixel colour. -:param key: Liczba pikseli. -:return: The colour tuple.""" + Example: ``r, g, b = np[0]`` + :param key: The pixel number. + :return: The colour tuple. + """ def __len__(self) -> int: - """Uzyskaj długość tego paska pikseli. + """Get length of this pixel strip. -Example: ``len(np)``""" \ No newline at end of file + Example: ``len(np)`` + """ diff --git a/lang/pl/typeshed/stdlib/os.pyi b/lang/pl/typeshed/stdlib/os.pyi index dec924c..2f2db77 100644 --- a/lang/pl/typeshed/stdlib/os.pyi +++ b/lang/pl/typeshed/stdlib/os.pyi @@ -1,63 +1,73 @@ -"""Uzyskaj dostęp do systemu plików.""" +"""Access the file system. +""" + from typing import Tuple from typing import List def listdir() -> List[str]: - """Lista plików. + """List files. -Example: ``os.listdir()`` + Example: ``os.listdir()`` -:return: A list of the names of all the files contained within the local -persistent on-device file system.""" + :return: A list of the names of all the files contained within the local + persistent on-device file system. + """ ... def remove(filename: str) -> None: - """Usuń (usuń) plik. + """Remove (delete) a file. -Example: ``os.remove('data.txt')`` + Example: ``os.remove('data.txt')`` -:param filename: Plik do usunięcia. + :param filename: The file to delete. -If the file does not exist an ``OSError`` exception will occur.""" + If the file does not exist an ``OSError`` exception will occur. + """ ... def size(filename: str) -> int: - """Zwraca rozmiar pliku. + """Returns the size of a file. -Example: ``os.size('data.txt')`` + Example: ``os.size('data.txt')`` -:param filename: Plik -:return: The size in bytes. + :param filename: The file + :return: The size in bytes. -If the file does not exist an ``OSError`` exception will occur.""" + If the file does not exist an ``OSError`` exception will occur. + """ class uname_result(Tuple[str, str, str, str, str]): - """Wynik ``os.uname()``""" + """Result of ``os.uname()``""" sysname: str - """Nazwa systemu operacyjnego.""" + """Operating system name.""" + nodename: str - """Nazwa maszyny w sieci (zdefiniowana w implementacji).""" + """Name of machine on network (implementation-defined).""" + release: str - """Wydanie systemu operacyjnego.""" + """Operating system release.""" + version: str - """Wersja systemu operacyjnego""" + """Operating system version.""" + machine: str - """Identyfikator sprzętu.""" + """Hardware identifier.""" def uname() -> uname_result: - """Zwraca informacje identyfikujące bieżący system operacyjny. + """Returns information identifying the current operating system. -Example: ``os.uname()`` + Example: ``os.uname()`` -The return value is an object with five attributes: + The return value is an object with five attributes: -- ``sysname`` - operating system name -- ``nodename`` - name of machine on network (implementation-defined) -- ``release`` - operating system release -- ``version`` - operating system version -- ``machine`` - hardware identifier + - ``sysname`` - operating system name + - ``nodename`` - name of machine on network (implementation-defined) + - ``release`` - operating system release + - ``version`` - operating system version + - ``machine`` - hardware identifier -There is no underlying operating system in MicroPython. As a result the -information returned by the ``uname`` function is mostly useful for -versioning details.""" - ... \ No newline at end of file + There is no underlying operating system in MicroPython. As a result the + information returned by the ``uname`` function is mostly useful for + versioning details. + """ + ... diff --git a/lang/pl/typeshed/stdlib/radio.pyi b/lang/pl/typeshed/stdlib/radio.pyi index bc27b9e..8dd0267 100644 --- a/lang/pl/typeshed/stdlib/radio.pyi +++ b/lang/pl/typeshed/stdlib/radio.pyi @@ -1,130 +1,152 @@ -"""Komunikuj się pomiędzy micro:bitami za pomocą wbudowanego radia.""" +"""Communicate between micro:bits with the built-in radio. +""" + from _typeshed import WriteableBuffer from typing import Optional, Tuple + RATE_1MBIT: int -"""Stała używana do wskazania przepustowości 1 MBit na sekundę.""" +"""Constant used to indicate a throughput of 1 MBit a second.""" + RATE_2MBIT: int -"""Stała używana do wskazania przepustowości 2 MBit na sekundę.""" +"""Constant used to indicate a throughput of 2 MBit a second.""" def on() -> None: - """Włącza radio + """Turns the radio on. -Example: ``radio.on()`` + Example: ``radio.on()`` -This needs to be explicitly called since the radio draws power and takes -up memory that you may otherwise need.""" + This needs to be explicitly called since the radio draws power and takes + up memory that you may otherwise need. + """ ... def off() -> None: - """Wyłącza radio, oszczędzając energię i pamięć. + """Turns off the radio, saving power and memory. -Example: ``radio.off()``""" + Example: ``radio.off()`` + """ ... -def config(length: int=32, queue: int=3, channel: int=7, power: int=6, address: int=1969383796, group: int=0, data_rate: int=RATE_1MBIT) -> None: - """Konfiguruje radio. - -Example: ``radio.config(group=42)`` - -The default configuration is suitable for most use. - -:param length: (default=32) definiuje maksymalną długość w bajtach wiadomości wysyłanej przez radio. -Może mieć długość do 251 bajtów (254 - 3 bajty dla S0, LENGTH i S1). -:param queue: (default=3) określa liczbę wiadomości, które mogą być przechowywane w kolejce przychodzących wiadomości. -Jeśli w kolejce na wiadomości przychodzące nie ma już wolnych miejsc, wiadomość przychodząca jest odrzucana. -:param channel: (default=7) wartość całkowita od 0 do 83 (włącznie), która definiuje dowolny „kanał”, do którego dostrojone jest radio. -Wiadomości będą wysyłane za pośrednictwem tego kanału i tylko wiadomości otrzymane za pośrednictwem tego kanału zostaną umieszczone w kolejce wiadomości przychodzących. Każdy stopień ma szerokość 1 MHz w oparciu o częstotliwość 2400 MHz. -:param power: (default=6) jest liczb całkowitą od 0 do 7 (włącznie) do oznaczenia siły sygnału używanego podczas nadawania wiadomości. -Im wyższa wartość, tym silniejszy jest sygnał, ale tym większa moc jest zużywana przez urządzenie. Numeracja przekłada się na pozycje w następującym wykazie wartości dBm (decybel miliwat): -30, -20, -16, -12, -8, -4, 0, 4. -:param address: (default=0x75626974) dowolna nazwa wyrażona jako 32-bitowy adres, używana do filtrowania przychodzących pakietów na poziomie sprzętowym, zatrzymując tylko te, które odpowiadają ustawionemu adresowi. -Domyślnym ustawieniem używanym przez inne platformy powiązane z micro:bitem jest ustawienie domyślne używane tutaj. -:param group: (default=0) 8-bitowa wartość (0-255) używana wraz z ``address`` podczas filtrowania wiadomości. -Koncepcyjnie, "adres" jest jak adres domu/biura, a "grupa" jest jak osoba pod tym adresem, na który chcesz wysłać swoją wiadomość. -:param data_rate: (default=``radio.RATE_1MBIT``) wskazuje prędkość, z jaką odbywa się przesyłanie danych. -Może być jedną z następujących stałych zdefiniowanych w module ``radio``:``RATE_250KBIT``, ``RATE_1MBIT`` lub ``RATE_2MBIT``. - -If ``config`` is not called then the defaults described above are assumed.""" +def config( + length: int = 32, + queue: int = 3, + channel: int = 7, + power: int = 6, + address: int = 0x75626974, + group: int = 0, + data_rate: int = RATE_1MBIT, +) -> None: + """Configures the radio. + + Example: ``radio.config(group=42)`` + + The default configuration is suitable for most use. + + :param length: (default=32) defines the maximum length, in bytes, of a message sent via the radio. + It can be up to 251 bytes long (254 - 3 bytes for S0, LENGTH and S1 preamble). + :param queue: (default=3) specifies the number of messages that can be stored on the incoming message queue. + If there are no spaces left on the queue for incoming messages, then the incoming message is dropped. + :param channel: (default=7) an integer value from 0 to 83 (inclusive) that defines an arbitrary "channel" to which the radio is tuned. + Messages will be sent via this channel and only messages received via this channel will be put onto the incoming message queue. Each step is 1MHz wide, based at 2400MHz. + :param power: (default=6) is an integer value from 0 to 7 (inclusive) to indicate the strength of signal used when broadcasting a message. + The higher the value the stronger the signal, but the more power is consumed by the device. The numbering translates to positions in the following list of dBm (decibel milliwatt) values: -30, -20, -16, -12, -8, -4, 0, 4. + :param address: (default=0x75626974) an arbitrary name, expressed as a 32-bit address, that's used to filter incoming packets at the hardware level, keeping only those that match the address you set. + The default used by other micro:bit related platforms is the default setting used here. + :param group: (default=0) an 8-bit value (0-255) used with the ``address`` when filtering messages. + Conceptually, "address" is like a house/office address and "group" is like the person at that address to which you want to send your message. + :param data_rate: (default=``radio.RATE_1MBIT``) indicates the speed at which data throughput takes place. + Can be one of the following constants defined in the ``radio`` module: ``RATE_250KBIT``, ``RATE_1MBIT`` or ``RATE_2MBIT``. + + If ``config`` is not called then the defaults described above are assumed. + """ ... def reset() -> None: - """Resetuj ustawienia do ich wartości domyślnych. + """Reset the settings to their default values. -Example: ``radio.reset()`` + Example: ``radio.reset()`` -The defaults as as per the ``config`` function above.""" + The defaults as as per the ``config`` function above. + """ ... def send_bytes(message: bytes) -> None: - """Wysyła wiadomość zawierającą bajty. + """Sends a message containing bytes. -Example: ``radio.send_bytes(b'hello')`` + Example: ``radio.send_bytes(b'hello')`` -:param message: Bajty do wysłania.""" + :param message: The bytes to send. + """ ... def receive_bytes() -> Optional[bytes]: - """Otrzymuj następną przychodzącą wiadomość w kolejce wiadomości. + """Receive the next incoming message on the message queue. -Example: ``radio.receive_bytes()`` + Example: ``radio.receive_bytes()`` -:return: The message bytes if any, otherwise ``None``.""" + :return: The message bytes if any, otherwise ``None``. + """ ... def receive_bytes_into(buffer: WriteableBuffer) -> Optional[int]: - """Skopiuj następną wiadomość przychodzącą do kolejki wiadomości w buforze. + """Copy the next incoming message on the message queue into a buffer. -Example: ``radio.receive_bytes_info(buffer)`` + Example: ``radio.receive_bytes_info(buffer)`` -:param buffer: Bufor docelowy. Wiadomość jest obcinana, jeśli jest większa niż bufor. -:return: ``None`` if there are no pending messages, otherwise it returns the length of the message (which might be more than the length of the buffer).""" + :param buffer: The target buffer. The message is truncated if larger than the buffer. + :return: ``None`` if there are no pending messages, otherwise it returns the length of the message (which might be more than the length of the buffer). + """ ... def send(message: str) -> None: - """Wysyła łańcuch wiadomości. + """Sends a message string. -Example: ``radio.send('hello')`` + Example: ``radio.send('hello')`` -This is the equivalent of ``radio.send_bytes(bytes(message, 'utf8'))`` but with ``b'\x01\x00\x01'`` -prepended to the front (to make it compatible with other platforms that target the micro:bit). + This is the equivalent of ``radio.send_bytes(bytes(message, 'utf8'))`` but with ``b'\x01\x00\x01'`` + prepended to the front (to make it compatible with other platforms that target the micro:bit). -:param message: Łańcuch do wysłania.""" + :param message: The string to send. + """ ... def receive() -> Optional[str]: - """Działa dokładnie w taki sam sposób, jak ``receive_bytes``, ale zwraca cokolwiek zostało wysłane. (odbierz) + """Works in exactly the same way as ``receive_bytes`` but returns whatever was sent. -Example: ``radio.receive()`` + Example: ``radio.receive()`` -Equivalent to ``str(receive_bytes(), 'utf8')`` but with a check that the the first -three bytes are ``b'\x01\x00\x01'`` (to make it compatible with other platforms that -may target the micro:bit). + Equivalent to ``str(receive_bytes(), 'utf8')`` but with a check that the the first + three bytes are ``b'\x01\x00\x01'`` (to make it compatible with other platforms that + may target the micro:bit). -:return: The message with the prepended bytes stripped and converted to a string. + :return: The message with the prepended bytes stripped and converted to a string. -A ``ValueError`` exception is raised if conversion to string fails.""" + A ``ValueError`` exception is raised if conversion to string fails. + """ ... def receive_full() -> Optional[Tuple[bytes, int, int]]: - """Zwraca krotkę zawierającą trzy wartości reprezentujące następną wiadomość przychodzącą do kolejki wiadomości. + """Returns a tuple containing three values representing the next incoming message on the message queue. -Example: ``radio.receive_full()`` + Example: ``radio.receive_full()`` -If there are no pending messages then ``None`` is returned. + If there are no pending messages then ``None`` is returned. -The three values in the tuple represent: + The three values in the tuple represent: -- the next incoming message on the message queue as bytes. -- the RSSI (signal strength): a value between 0 (strongest) and -255 (weakest) as measured in dBm. -- a microsecond timestamp: the value returned by ``time.ticks_us()`` when the message was received. + - the next incoming message on the message queue as bytes. + - the RSSI (signal strength): a value between 0 (strongest) and -255 (weakest) as measured in dBm. + - a microsecond timestamp: the value returned by ``time.ticks_us()`` when the message was received. -For example:: + For example:: - details = radio.receive_full() - if details: - msg, rssi, timestamp = details + details = radio.receive_full() + if details: + msg, rssi, timestamp = details -This function is useful for providing information needed for triangulation -and/or trilateration with other micro:bit devices. + This function is useful for providing information needed for triangulation + and/or trilateration with other micro:bit devices. -:return: ``None`` if there is no message, otherwise a tuple of length three with the bytes, strength and timestamp values.""" - ... \ No newline at end of file + :return: ``None`` if there is no message, otherwise a tuple of length three with the bytes, strength and timestamp values. + """ + ... diff --git a/lang/pl/typeshed/stdlib/random.pyi b/lang/pl/typeshed/stdlib/random.pyi index c6431c6..a2c2ef3 100644 --- a/lang/pl/typeshed/stdlib/random.pyi +++ b/lang/pl/typeshed/stdlib/random.pyi @@ -1,81 +1,93 @@ -"""Generuj liczb losowe. (losowy)""" +"""Generate random numbers. +""" from typing import TypeVar, Sequence, Union, overload def getrandbits(n: int) -> int: - """Wygeneruj liczbę całkowitą z ``n`` losowymi bitami. + """Generate an integer with ``n`` random bits. -Example: ``random.getrandbits(1)`` + Example: ``random.getrandbits(1)`` -:param n: Wartość między 1–30 (włącznie).""" + :param n: A value between 1-30 (inclusive). + """ ... def seed(n: int) -> None: - """Zainicjuj generator liczb losowych. + """Initialize the random number generator. -Example: ``random.seed(0)`` + Example: ``random.seed(0)`` -:param n: Całkowity zarodek + :param n: The integer seed -This will give you reproducibly deterministic randomness from a given starting -state (``n``).""" + This will give you reproducibly deterministic randomness from a given starting + state (``n``). + """ ... def randint(a: int, b: int) -> int: - """Wybierz losową liczbę całkowitą pomiędzy ``a`` i ``b`` włącznie. + """Choose a random integer between ``a`` and ``b`` inclusive. -Example: ``random.randint(0, 9)`` + Example: ``random.randint(0, 9)`` -:param a: Wartość początkowa dla zakresu (włącznie) -:param b: Wartość końcowa dla zakresu (wyłącznie) + :param a: Start value for the range (inclusive) + :param b: End value for the range (inclusive) -Alias for ``randrange(a, b + 1)``.""" + Alias for ``randrange(a, b + 1)``. + """ ... @overload def randrange(stop: int) -> int: - """Wybierz losowo wybraną liczbę całkowitą między zero aż do (ale nie -włącznie) ``stop``. + """Choose a randomly selected integer between zero and up to (but not + including) ``stop``. -Example: ``random.randrange(10)`` + Example: ``random.randrange(10)`` -:param stop: Wartość końcowa zakresu (wyłącznie)""" + :param stop: End value for the range (exclusive) + """ ... @overload -def randrange(start: int, stop: int, step: int=1) -> int: - """Wybierz losowo wybrany element z ``range(start, stop, step)``. +def randrange(start: int, stop: int, step: int = 1) -> int: + """ + Choose a randomly selected element from ``range(start, stop, step)``. -Example: ``random.randrange(0, 10)`` + Example: ``random.randrange(0, 10)`` -:param start: Początek zakresu (włącznie) -:param stop: Koniec zakresu (wyłącznie) -:param step: Krok""" + :param start: The start of the range (inclusive) + :param stop: The end of the range (exclusive) + :param step: The step. + """ ... -_T = TypeVar('_T') + +_T = TypeVar("_T") def choice(seq: Sequence[_T]) -> _T: - """Wybierz losowy element z niepustego cigu ``seq``. + """Choose a random element from the non-empty sequence ``seq``. -Example: ``random.choice([Image.HAPPY, Image.SAD])`` + Example: ``random.choice([Image.HAPPY, Image.SAD])`` -:param seq: Cig. + :param seq: A sequence. -If ``seq`` is empty, raises ``IndexError``.""" + If ``seq`` is empty, raises ``IndexError``. + """ ... def random() -> float: - """Wygeneruj losową liczbę zmiennopozycyjną w zakresie [0.0, 1.0). + """Generate a random floating point number in the range [0.0, 1.0). -Example: ``random.random()`` + Example: ``random.random()`` -:return: The random floating point number""" + :return: The random floating point number + """ ... def uniform(a: float, b: float) -> float: - """Zwróć losową liczbę zmiennopozycyjnłą między ``a`` i ``b``. + """ + Return a random floating point number between ``a`` and ``b`` inclusive. -Example: ``random.uniform(0, 9)`` + Example: ``random.uniform(0, 9)`` -:param a: Wartość początkowa dla zakresu (włącznie) -:param b: Wartość końcowa dla zakresu (wyłącznie)""" - ... \ No newline at end of file + :param a: Start value for the range (inclusive) + :param b: End value for the range (inclusive) + """ + ... diff --git a/lang/pl/typeshed/stdlib/speech.pyi b/lang/pl/typeshed/stdlib/speech.pyi index cf7dced..349d188 100644 --- a/lang/pl/typeshed/stdlib/speech.pyi +++ b/lang/pl/typeshed/stdlib/speech.pyi @@ -1,79 +1,106 @@ -"""Spraw, by micro:bit mówił, śpiewał i tworzył inne dźwięki podobne do mowy.""" +"""Make the micro:bit talk, sing and make other speech like sounds. +""" + from typing import Optional from .microbit import MicroBitDigitalPin, pin0 def translate(words: str) -> str: - """Tłumacz angielskie słowa na fonemy. + """Translate English words to phonemes. -Example: ``speech.translate('hello world')`` + Example: ``speech.translate('hello world')`` -:param words: Łańcuch słów angielskich. -:return: A string containing a best guess at the appropriate phonemes to pronounce. -The output is generated from this `text to phoneme translation table `_. + :param words: A string of English words. + :return: A string containing a best guess at the appropriate phonemes to pronounce. + The output is generated from this `text to phoneme translation table `_. -This function should be used to generate a first approximation of phonemes -that can be further hand-edited to improve accuracy, inflection and -emphasis. + This function should be used to generate a first approximation of phonemes + that can be further hand-edited to improve accuracy, inflection and + emphasis. -See `the online documentation `_ for detailed information.""" + See `the online documentation `_ for detailed information. + """ ... -def pronounce(phonemes: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: Optional[MicroBitDigitalPin]=pin0) -> None: - """Wymów fonemy. - -Example: ``speech.pronounce(' /HEHLOW WERLD')`` - -:param phonemes: Łańcuch fonemów do wymówienia -:param pitch: Liczba reprezentująca wysokość głosu -:param speed: Liczba reprezentująca szybkość głosu -:param mouth: Liczba reprezentująca usta głosu -:param throat: Liczba reprezentująca gardło głosu -:param pin: Opcjonalny argument do określenia pinu wyjściowego może być użyty do nadpisania domyślnej wartości ``pin0``. -Jeśli nie chcemy, aby jakikolwiek dźwięk wydobywał się z pinów, możemy użyć ``pin=None``. Tylko micro:bit V2. - -Override the optional pitch, speed, mouth and throat settings to change the -timbre (quality) of the voice. - -See `the online documentation `_ for detailed information.""" +def pronounce( + phonemes: str, + pitch: int = 64, + speed: int = 72, + mouth: int = 128, + throat: int = 128, + pin: Optional[MicroBitDigitalPin] = pin0, +) -> None: + """Pronounce phonemes. + + Example: ``speech.pronounce(' /HEHLOW WERLD')`` + + :param phonemes: The string of phonemes to pronounce + :param pitch: A number representing the pitch of the voice + :param speed: A number representing the speed of the voice + :param mouth: A number representing the mouth of the voice + :param throat: A number representing the throat of the voice + :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. + If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. + + Override the optional pitch, speed, mouth and throat settings to change the + timbre (quality) of the voice. + + See `the online documentation `_ for detailed information. + """ ... -def say(words: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: MicroBitDigitalPin=pin0) -> None: - """Powiedz angielskie słowa. - -Example: ``speech.say('hello world')`` - -:param words: Łańcuch słów do powiedzenia. -:param pitch: Liczba reprezentująca wysokość głosu -:param speed: Liczba reprezentująca szybkość głosu -:param mouth: Liczba reprezentująca usta głosu -:param throat: Liczba reprezentująca gardło głosu -:param pin: Opcjonalny argument do określenia pinu wyjściowego może być użyty do nadpisania domyślnej wartości ``pin0``. -Jeśli nie chcemy, aby jakikolwiek dźwięk wydobywał się z pinów, możemy użyć ``pin=None``. Tylko micro:bit V2. - -The result is semi-accurate for English. Override the optional pitch, speed, -mouth and throat settings to change the timbre (quality) of the voice. - -This is a short-hand equivalent of: -``speech.pronounce(speech.translate(words))`` - -See `the online documentation `_ for detailed information.""" +def say( + words: str, + pitch: int = 64, + speed: int = 72, + mouth: int = 128, + throat: int = 128, + pin: MicroBitDigitalPin = pin0, +) -> None: + """Say English words. + + Example: ``speech.say('hello world')`` + + :param words: The string of words to say. + :param pitch: A number representing the pitch of the voice + :param speed: A number representing the speed of the voice + :param mouth: A number representing the mouth of the voice + :param throat: A number representing the throat of the voice + :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. + If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. + + The result is semi-accurate for English. Override the optional pitch, speed, + mouth and throat settings to change the timbre (quality) of the voice. + + This is a short-hand equivalent of: + ``speech.pronounce(speech.translate(words))`` + + See `the online documentation `_ for detailed information. + """ ... -def sing(phonemes: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: MicroBitDigitalPin=pin0) -> None: - """Zaśpiewaj fonemy. - -Example: ``speech.sing(' /HEHLOW WERLD')`` - -:param phonemes: Łańcuch słów do zaśpiewania. -:param pitch: Liczba reprezentująca wysokość głosu -:param speed: Liczba reprezentująca szybkość głosu -:param mouth: Liczba reprezentująca usta głosu -:param throat: Liczba reprezentująca gardło głosu -:param pin: Opcjonalny argument do określenia pinu wyjściowego może być użyty do nadpisania domyślnej wartości ``pin0``. -Jeśli nie chcemy, aby jakikolwiek dźwięk wydobywał się z pinów, możemy użyć ``pin=None``. Tylko micro:bit V2. - -Override the optional pitch, speed, mouth and throat settings to change -the timbre (quality) of the voice. - -See `the online documentation `_ for detailed information.""" - ... \ No newline at end of file +def sing( + phonemes: str, + pitch: int = 64, + speed: int = 72, + mouth: int = 128, + throat: int = 128, + pin: MicroBitDigitalPin = pin0, +) -> None: + """Sing phonemes. + + Example: ``speech.sing(' /HEHLOW WERLD')`` + + :param phonemes: The string of words to sing. + :param pitch: A number representing the pitch of the voice + :param speed: A number representing the speed of the voice + :param mouth: A number representing the mouth of the voice + :param throat: A number representing the throat of the voice + :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. + If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. + + Override the optional pitch, speed, mouth and throat settings to change + the timbre (quality) of the voice. + + See `the online documentation `_ for detailed information. + """ + ... diff --git a/lang/pl/typeshed/stdlib/struct.pyi b/lang/pl/typeshed/stdlib/struct.pyi index ea3d443..53b3e0b 100644 --- a/lang/pl/typeshed/stdlib/struct.pyi +++ b/lang/pl/typeshed/stdlib/struct.pyi @@ -1,56 +1,65 @@ -"""Pakuj i rozpakowuj prymitywne typy danych.""" +"""Pack and unpack primitive data types. +""" + from _typeshed import ReadableBuffer, WriteableBuffer from typing import Any, Tuple, Union def calcsize(fmt: str) -> int: - """Uzyskaj liczbę bajtów potrzebnych do przechowywania podanego ``fmt``. + """Get the number of bytes needed to store the given ``fmt``. -Example: ``struct.calcsize('hf')`` + Example: ``struct.calcsize('hf')`` -:param fmt: Łańcuch formatu. -:return The number of bytes needed to store such a value.""" + :param fmt: A format string. + :return The number of bytes needed to store such a value. + """ ... def pack(fmt: str, v1: Any, *vn: Any) -> bytes: - """Upakuj wartości zgodnie z łńcuchem formatu. + """Pack values according to a format string. -Example: ``struct.pack('hf', 1, 3.1415)`` + Example: ``struct.pack('hf', 1, 3.1415)`` -:param fmt: Łańcuch formatu. -:param v1: Pierwsza wartość. -:param *vn: Pozostałe wartości. -:return A bytes object encoding the values.""" + :param fmt: The format string. + :param v1: The first value. + :param *vn: The remaining values. + :return A bytes object encoding the values. + """ ... -def pack_into(fmt: str, buffer: WriteableBuffer, offset: int, v1: Any, *vn: Any) -> None: - """Upakuj wartości zgodnie z łńcuchem formatu. +def pack_into( + fmt: str, buffer: WriteableBuffer, offset: int, v1: Any, *vn: Any +) -> None: + """Pack values according to a format string. -Example: ``struct.pack_info('hf', buffer, 1, 3.1415)`` + Example: ``struct.pack_info('hf', buffer, 1, 3.1415)`` -:param fmt: Łańcuch formatu. -:param buffer: Bufor docelowy do zapisu. -:param offset: Przesunięcie do bufora. Wartość ujemna może być liczona od końca bufora. -:param v1: (w1) Pierwsza wartość. -:param *vn: Pozostałe wartości.""" + :param fmt: The format string. + :param buffer: The target buffer to write into. + :param offset: The offset into the buffer. May be negative to count from the end of the buffer. + :param v1: The first value. + :param *vn: The remaining values. + """ ... def unpack(fmt: str, data: ReadableBuffer) -> Tuple[Any, ...]: - """Rozpakuj dane zgodnie z łańcuchem formatu. + """Unpack data according to a format string. -Example: ``v1, v2 = struct.unpack('hf', buffer)`` + Example: ``v1, v2 = struct.unpack('hf', buffer)`` -:param fmt: Łańcuch formatu. -:param data: Dane -:return: A tuple of the unpacked values.""" + :param fmt: The format string. + :param data: The data. + :return: A tuple of the unpacked values. + """ ... -def unpack_from(fmt: str, buffer: ReadableBuffer, offset: int=0) -> Tuple: - """Rozpakuj dane z buforu zgodnie z łańcuchem formatu. +def unpack_from(fmt: str, buffer: ReadableBuffer, offset: int = 0) -> Tuple: + """Unpack data from a buffer according to a format string. -Example: ``v1, v2 = struct.unpack_from('hf', buffer)`` + Example: ``v1, v2 = struct.unpack_from('hf', buffer)`` -:param fmt: Łańcuch formatu. -:param buffer: Bufor źródłowy do odczytu. -:param offset: Przesunięcie do bufora. Wartość ujemna może być liczona od końca bufora. -:return: A tuple of the unpacked values.""" - ... \ No newline at end of file + :param fmt: The format string. + :param buffer: The source buffer to read from. + :param offset: The offset into the buffer. May be negative to count from the end of the buffer. + :return: A tuple of the unpacked values. + """ + ... diff --git a/lang/pl/typeshed/stdlib/sys.pyi b/lang/pl/typeshed/stdlib/sys.pyi index c0683cb..320bac9 100644 --- a/lang/pl/typeshed/stdlib/sys.pyi +++ b/lang/pl/typeshed/stdlib/sys.pyi @@ -1,36 +1,43 @@ -"""Funkcje specyficzne dla systemu""" +"""System specific functions""" + from typing import Any, Dict, List, NoReturn, TextIO, Tuple -def exit(retval: object=...) -> NoReturn: - """Zakończ bieżący program z podanym kodem wyjścia. +def exit(retval: object = ...) -> NoReturn: + """Terminate current program with a given exit code. -Example: ``sys.exit(1)`` + Example: ``sys.exit(1)`` -This function raises a ``SystemExit`` exception. If an argument is given, its -value given as an argument to ``SystemExit``. + This function raises a ``SystemExit`` exception. If an argument is given, its + value given as an argument to ``SystemExit``. -:param retval: Kod lub wiadomość wyjściowa.""" + :param retval: The exit code or message. + """ ... def print_exception(exc: Exception) -> None: - """Wydrukuj wyjątek ze śledzeniem. + """ + Print an exception with a traceback. + + Example: ``sys.print_exception(e)`` -Example: ``sys.print_exception(e)`` + :param exc: The exception to print -:param exc: Wyjątek do wydrukowania + This is simplified version of a function which appears in the + ``traceback`` module in CPython. + """ -This is simplified version of a function which appears in the -``traceback`` module in CPython.""" argv: List[str] -"""Zmienna lista argumentów, od których uruchomiono bieżący program.""" +"""A mutable list of arguments the current program was started with.""" + byteorder: str -"""Kolejność bajtów systemu (``"little"`` lub ``"big"``).""" +"""The byte order of the system (``"little"`` or ``"big"``).""" class _implementation: name: str version: Tuple[int, int, int] + implementation: _implementation -"""Obiekt z informacjami o bieżącej implementacji Pythona. +"""Object with information about the current Python implementation. For MicroPython, it has following attributes: @@ -44,12 +51,13 @@ minimal ports). CPython mandates more attributes for this object, but the actual useful bare minimum is implemented in MicroPython. """ + maxsize: int """ -Maksymalna wartość, jaką może przechowywać natywny typ całkowity na bieżącej platformie, -lub maksymalna wartość reprezentowana przez typ całkowity MicroPythona, jeśli jest mniejsza -niż maksymalna wartość platformy (tak jest w przypadku portów MicroPython bez -wsparcia long int). +Maximum value which a native integer type can hold on the current platform, +or maximum value representable by MicroPython integer type, if it's smaller +than platform max value (that is the case for MicroPython ports without +long int support). This attribute is useful for detecting "bitness" of a platform (32-bit vs 64-bit, etc.). It's recommended to not compare this attribute to some @@ -69,14 +77,17 @@ value directly, but instead count number of bits in it:: # (e.g. 31) due to peculiarities described above, so use "> 16", # "> 32", "> 64" style of comparisons. """ + modules: Dict[str, Any] -"""Słownik załadowanych modułów. +"""Dictionary of loaded modules. On some ports, it may not include builtin modules.""" + path: List[str] -"""Zmienna lista katalogów do wyszukiwania importowanych modułów.""" +"""A mutable list of directories to search for imported modules.""" + platform: str -"""Platforma na której działa MicroPython. +"""The platform that MicroPython is running on. For OS/RTOS ports, this is usually an identifier of the OS, e.g. ``"linux"``. For baremetal ports it is an identifier of a board, e.g. ``"pyboard"`` for @@ -86,11 +97,13 @@ distinguish one board from another. If you need to check whether your program runs on MicroPython (vs other Python implementation), use ``sys.implementation`` instead. """ + version: str -"""Wersja Pythona, z którą ta implementacja jest zgodna, jako łańcuch.""" +"""Python language version that this implementation conforms to, as a string.""" + version_info: Tuple[int, int, int] -"""Wersja Pythona, z którą ta implementacja jest zgodna, jako krotka typu int. +"""Python language version that this implementation conforms to, as a tuple of ints. Only the first three version numbers (major, minor, micro) are supported and they can be referenced only by index, not by name. -""" \ No newline at end of file +""" diff --git a/lang/pl/typeshed/stdlib/time.pyi b/lang/pl/typeshed/stdlib/time.pyi index cc4cf6e..598c483 100644 --- a/lang/pl/typeshed/stdlib/time.pyi +++ b/lang/pl/typeshed/stdlib/time.pyi @@ -1,117 +1,132 @@ -"""Zmierz czas i dodaj opóźnienia do programów.""" +"""Measure time and add delays to programs. +""" + from typing import Union def sleep(seconds: Union[int, float]) -> None: - """Opóźnij kilka sekund. + """ + Delay a number of seconds. -Example: ``time.sleep(1)`` + Example: ``time.sleep(1)`` -:param seconds: Liczba sekund snu. -Użyj liczby zmiennopozycyjnej, aby spać przez ułamkową część sekund.""" + :param seconds: The number of seconds to sleep for. + Use a floating-point number to sleep for a fractional number of seconds. + """ ... def sleep_ms(ms: int) -> None: - """Opóźnij o podaną liczbę milisekund. + """ + Delay for given number of milliseconds. -Example: ``time.sleep_ms(1_000_000)`` + Example: ``time.sleep_ms(1_000_000)`` -:param ms: Liczba milisekund opóźnienia (>= 0).""" + :param ms: The number of milliseconds delay (>= 0). + """ ... def sleep_us(us: int) -> None: - """Opóźnij o podaną liczbę milisekund. + """ + Delay for given number of microseconds. -Example: ``time.sleep_us(1000)`` + Example: ``time.sleep_us(1000)`` -:param us: Liczba milisekund opóźnienia (>= 0).""" + :param us: The number of microseconds delay (>= 0). + """ ... def ticks_ms() -> int: - """Uzyskaj rosnący licznik milisekundowy z dowolnym punktem odniesienia, -który zawija się po pewnej wartości. + """ + Get an increasing, millisecond counter with an arbitrary reference point, + that wraps around after some value. -Example: ``time.ticks_ms()`` + Example: ``time.ticks_ms()`` -:return: The counter value in milliseconds.""" + :return: The counter value in milliseconds. + """ ... def ticks_us() -> int: - """Uzyskaj rosnący licznik milisekundowy z dowolnym punktem odniesienia, -który zawija się po pewnej wartości. + """ + Get an increasing, microsecond counter with an arbitrary reference point, + that wraps around after some value. -Example: ``time.ticks_us()`` + Example: ``time.ticks_us()`` -:return: The counter value in microseconds.""" + :return: The counter value in microseconds. + """ ... def ticks_add(ticks: int, delta: int) -> int: - """Przesunięcie zaznacza wartość o podaną liczbę, która może być dodatnia lub -negatywny. -. + """ + Offset ticks value by a given number, which can be either positive or + negative. -Example: ``time.ticks_add(time.ticks_ms(), 200)`` + Example: ``time.ticks_add(time.ticks_ms(), 200)`` -Given a ticks value, this function allows to calculate ticks -value delta ticks before or after it, following modular-arithmetic -definition of tick values. + Given a ticks value, this function allows to calculate ticks + value delta ticks before or after it, following modular-arithmetic + definition of tick values. -:param ticks: Wartość ticków -:param delta: Przesunięcie o liczbę całkowitą + :param ticks: A ticks value + :param delta: An integer offset -Example:: + Example:: - # Find out what ticks value there was 100ms ago - print(ticks_add(time.ticks_ms(), -100)) + # Find out what ticks value there was 100ms ago + print(ticks_add(time.ticks_ms(), -100)) - # Calculate deadline for operation and test for it - deadline = ticks_add(time.ticks_ms(), 200) - while ticks_diff(deadline, time.ticks_ms()) > 0: - do_a_little_of_something() + # Calculate deadline for operation and test for it + deadline = ticks_add(time.ticks_ms(), 200) + while ticks_diff(deadline, time.ticks_ms()) > 0: + do_a_little_of_something() - # Find out TICKS_MAX used by this port - print(ticks_add(0, -1))""" + # Find out TICKS_MAX used by this port + print(ticks_add(0, -1)) + """ ... def ticks_diff(ticks1: int, ticks2: int) -> int: - """Zmierz różnicę ticków między wartościami zwróconymi z -``time.ticks_ms()`` lub ``ticks_us()``, jako wartość ze znakiem, -która może się zawijać. - -Example: ``time.ticks_diff(scheduled_time, now)`` - -:param ticks1: Wartość do odejmowania od -:param ticks2: Wartość do odejmowania - -The argument order is the same as for subtraction operator, -``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. - -``ticks_diff()`` is designed to accommodate various usage -patterns, among them: - -Polling with timeout. In this case, the order of events is known, and you -will deal only with positive results of :func:`time.ticks_diff()`:: - - # Wait for GPIO pin to be asserted, but at most 500us - start = time.ticks_us() - while pin.value() == 0: - if time.ticks_diff(time.ticks_us(), start) > 500: - raise TimeoutError - - -Scheduling events. In this case, :func:`time.ticks_diff()` result may be -negative if an event is overdue:: - - # This code snippet is not optimized - now = time.ticks_ms() - scheduled_time = task.scheduled_time() - if ticks_diff(scheduled_time, now) > 0: - print("Too early, let's nap") - sleep_ms(ticks_diff(scheduled_time, now)) - task.run() - elif ticks_diff(scheduled_time, now) == 0: - print("Right at time!") - task.run() - elif ticks_diff(scheduled_time, now) < 0: - print("Oops, running late, tell task to run faster!") - task.run(run_faster=True)""" - ... \ No newline at end of file + """ + Measure ticks difference between values returned from + ``time.ticks_ms()`` or ``ticks_us()``, as a signed value + which may wrap around. + + Example: ``time.ticks_diff(scheduled_time, now)`` + + :param ticks1: The value to subtract from + :param ticks2: The value to subtract + + The argument order is the same as for subtraction operator, + ``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. + + ``ticks_diff()`` is designed to accommodate various usage + patterns, among them: + + Polling with timeout. In this case, the order of events is known, and you + will deal only with positive results of :func:`time.ticks_diff()`:: + + # Wait for GPIO pin to be asserted, but at most 500us + start = time.ticks_us() + while pin.value() == 0: + if time.ticks_diff(time.ticks_us(), start) > 500: + raise TimeoutError + + + Scheduling events. In this case, :func:`time.ticks_diff()` result may be + negative if an event is overdue:: + + # This code snippet is not optimized + now = time.ticks_ms() + scheduled_time = task.scheduled_time() + if ticks_diff(scheduled_time, now) > 0: + print("Too early, let's nap") + sleep_ms(ticks_diff(scheduled_time, now)) + task.run() + elif ticks_diff(scheduled_time, now) == 0: + print("Right at time!") + task.run() + elif ticks_diff(scheduled_time, now) < 0: + print("Oops, running late, tell task to run faster!") + task.run(run_faster=True) + """ + ... diff --git a/lang/zh-cn/typeshed/stdlib/gc.pyi b/lang/zh-cn/typeshed/stdlib/gc.pyi index ca5a757..1370abf 100644 --- a/lang/zh-cn/typeshed/stdlib/gc.pyi +++ b/lang/zh-cn/typeshed/stdlib/gc.pyi @@ -1,68 +1,73 @@ -"""控制垃圾回收器 (垃圾回收(gc))""" +"""Control the garbage collector""" + from typing import overload def enable() -> None: - """启用自动垃圾回收机制。""" + """Enable automatic garbage collection.""" ... def disable() -> None: - """禁用自动垃圾回收机制。 + """Disable automatic garbage collection. -Heap memory can still be allocated, -and garbage collection can still be initiated manually using ``gc.collect``.""" + Heap memory can still be allocated, + and garbage collection can still be initiated manually using ``gc.collect``.""" def collect() -> None: - """执行一次垃圾回收。""" + """Run a garbage collection.""" ... def mem_alloc() -> int: - """获取分配的堆内存的字节数。 + """Get the number of bytes of heap RAM that are allocated. -:return: The number of bytes allocated. + :return: The number of bytes allocated. -This function is MicroPython extension.""" + This function is MicroPython extension. + """ ... def mem_free() -> int: - """获取可用堆内存的字节数,如果此数量未知,则返回值为 -1。 + """Get the number of bytes of available heap RAM, or -1 if this amount is not known. -:return: The number of bytes free. + :return: The number of bytes free. -This function is MicroPython extension.""" + This function is MicroPython extension. + """ ... @overload def threshold() -> int: - """查询额外的垃圾回收分配阈值。 + """Query the additional GC allocation threshold. -:return: The GC allocation threshold. + :return: The GC allocation threshold. -This function is a MicroPython extension. CPython has a similar -function - ``set_threshold()``, but due to different GC -implementations, its signature and semantics are different.""" + This function is a MicroPython extension. CPython has a similar + function - ``set_threshold()``, but due to different GC + implementations, its signature and semantics are different. + """ ... @overload def threshold(amount: int) -> None: - """设置额外的垃圾回收分配阈值。 - -Normally, a collection is triggered only when a new allocation -cannot be satisfied, i.e. on an out-of-memory (OOM) condition. -If this function is called, in addition to OOM, a collection -will be triggered each time after ``amount`` bytes have been -allocated (in total, since the previous time such an amount of bytes -have been allocated). ``amount`` is usually specified as less than the -full heap size, with the intention to trigger a collection earlier than when the -heap becomes exhausted, and in the hope that an early collection will prevent -excessive memory fragmentation. This is a heuristic measure, the effect -of which will vary from application to application, as well as -the optimal value of the ``amount`` parameter. - -A value of -1 means a disabled allocation threshold. - -This function is a MicroPython extension. CPython has a similar -function - ``set_threshold()``, but due to different GC -implementations, its signature and semantics are different. - -:param amount: 触发进行垃圾回收的字节数。""" - ... \ No newline at end of file + """Set the additional GC allocation threshold. + + Normally, a collection is triggered only when a new allocation + cannot be satisfied, i.e. on an out-of-memory (OOM) condition. + If this function is called, in addition to OOM, a collection + will be triggered each time after ``amount`` bytes have been + allocated (in total, since the previous time such an amount of bytes + have been allocated). ``amount`` is usually specified as less than the + full heap size, with the intention to trigger a collection earlier than when the + heap becomes exhausted, and in the hope that an early collection will prevent + excessive memory fragmentation. This is a heuristic measure, the effect + of which will vary from application to application, as well as + the optimal value of the ``amount`` parameter. + + A value of -1 means a disabled allocation threshold. + + This function is a MicroPython extension. CPython has a similar + function - ``set_threshold()``, but due to different GC + implementations, its signature and semantics are different. + + :param amount: The number of bytes after which a garbage collection should be triggered. + """ + ... diff --git a/lang/zh-cn/typeshed/stdlib/log.pyi b/lang/zh-cn/typeshed/stdlib/log.pyi index 39efb49..c9870fa 100644 --- a/lang/zh-cn/typeshed/stdlib/log.pyi +++ b/lang/zh-cn/typeshed/stdlib/log.pyi @@ -1,89 +1,104 @@ -"""将数据记录到您的 micro:bit V2。 (日志)""" +"""Log data to your micro:bit V2.""" + from typing import Literal, Mapping, Optional, Union, overload + MILLISECONDS = 1 -"""毫秒时间戳格式。 (毫秒)""" +"""Milliseconds timestamp format.""" + SECONDS = 10 -"""秒时间戳格式。 (秒)""" +"""Seconds timestamp format.""" + MINUTES = 600 -"""分钟时间戳格式。 (分钟)""" +"""Minutes timestamp format.""" + HOURS = 36000 -"""小时时间戳格式。 (小时)""" +"""Hours timestamp format.""" + DAYS = 864000 -"""日期时间戳格式。 (天)""" +"""Days timestamp format.""" -def set_labels(*labels: str, timestamp: Optional[Literal[1, 10, 36000, 864000]]=SECONDS) -> None: - """设置日志文件头。 +def set_labels( + *labels: str, timestamp: Optional[Literal[1, 10, 36000, 864000]] = SECONDS +) -> None: + """Set up the log file header. -Example: ``log.set_labels('X', 'Y', 'Z', timestamp=log.MINUTES)`` + Example: ``log.set_labels('X', 'Y', 'Z', timestamp=log.MINUTES)`` -Ideally this function should be called a single time, before any data is -logged, to configure the data table header once. + Ideally this function should be called a single time, before any data is + logged, to configure the data table header once. -If a log file already exists when the program starts, or if this function -is called multiple times, it will check the labels already defined in the -log file. If this function call contains any new labels not already -present, it will generate a new header row with the additional columns. + If a log file already exists when the program starts, or if this function + is called multiple times, it will check the labels already defined in the + log file. If this function call contains any new labels not already + present, it will generate a new header row with the additional columns. -By default the first column contains a timestamp for each row. The time -unit can be selected via the timestamp argument. + By default the first column contains a timestamp for each row. The time + unit can be selected via the timestamp argument. -:param *labels: (*标签) 任何数量的位置参数,每个对应于日志头中的一个标题。 -:param timestamp: 选择将自动添加为每行第一列的时间戳单位。 时间戳值可以是 ``log.MILLISECONDS``, ``log.SECONDS``, ``log.MINUTES``, ``log.HOURS``, ``log.DAYS`` ,或者 ``None`` 来禁用时间戳。 默认值是 ``log.SECONDS``。""" + :param *labels: Any number of positional arguments, each corresponding to an entry in the log header. + :param timestamp: Select the timestamp unit that will be automatically added as the first column in every row. Timestamp values can be one of ``log.MILLISECONDS``, ``log.SECONDS``, ``log.MINUTES``, ``log.HOURS``, ``log.DAYS`` or ``None`` to disable the timestamp. The default value is ``log.SECONDS``. + """ ... @overload -def add(data_dictionary: Optional[Mapping[str, Union[str, int, float]]]) -> None: - """通过传递包含标题和值的字典将数据行添加到日志中。 +def add( + data_dictionary: Optional[Mapping[str, Union[str, int, float]]], +) -> None: + """Add a data row to the log by passing a dictionary of headers and values. -Example: ``log.add({ 'temp': temperature() })`` + Example: ``log.add({ 'temp': temperature() })`` -Each call to this function adds a row to the log. + Each call to this function adds a row to the log. -New labels not previously specified via the set_labels function, or by a -previous call to this function, will trigger a new header entry to be added -to the log with the extra labels. + New labels not previously specified via the set_labels function, or by a + previous call to this function, will trigger a new header entry to be added + to the log with the extra labels. -Labels previously specified and not present in a call to this function will -be skipped with an empty value in the log row. + Labels previously specified and not present in a call to this function will + be skipped with an empty value in the log row. -:param data_dictionary: (数据词典) 要记录为词典的数据,每个标题都有一个键。""" + :param data_dictionary: The data to log as a dictionary with a key for each header. + """ ... @overload def add(**kwargs: Union[str, int, float]) -> None: - """使用关键字参数将数据行添加到日志中。 + """Add a data row to the log using keyword arguments. -Example: ``log.add(temp=temperature())`` + Example: ``log.add(temp=temperature())`` -Each call to this function adds a row to the log. + Each call to this function adds a row to the log. -New labels not previously specified via the set_labels function, or by a -previous call to this function, will trigger a new header entry to be added -to the log with the extra labels. + New labels not previously specified via the set_labels function, or by a + previous call to this function, will trigger a new header entry to be added + to the log with the extra labels. -Labels previously specified and not present in a call to this function will -be skipped with an empty value in the log row.""" + Labels previously specified and not present in a call to this function will + be skipped with an empty value in the log row. + """ ... def delete(full=False): - """删除日志的内容,包括标题。 + """Deletes the contents of the log, including headers. -Example: ``log.delete()`` + Example: ``log.delete()`` -To add the log headers again the ``set_labels`` function should to be called after this function. + To add the log headers again the ``set_labels`` function should to be called after this function. -There are two erase modes; “full” completely removes the data from the physical storage, -and “fast” invalidates the data without removing it. + There are two erase modes; “full” completely removes the data from the physical storage, + and “fast” invalidates the data without removing it. -:param full: ``True`` 选择“完全”擦除, ``False`` 选择“快速”擦除方法。""" + :param full: ``True`` selects a “full” erase and ``False`` selects the “fast” erase method. + """ ... def set_mirroring(serial: bool): - """配置将数据日志活动镜像到串行输出。 + """Configure mirroring of the data logging activity to the serial output. -Example: ``log.set_mirroring(True)`` + Example: ``log.set_mirroring(True)`` -Serial mirroring is disabled by default. When enabled, it will print to serial each row logged into the log file. + Serial mirroring is disabled by default. When enabled, it will print to serial each row logged into the log file. -:param serial: ``True`` 启用了将数据镜像到串行输出。""" - ... \ No newline at end of file + :param serial: ``True`` enables mirroring data to the serial output. + """ + ... diff --git a/lang/zh-cn/typeshed/stdlib/machine.pyi b/lang/zh-cn/typeshed/stdlib/machine.pyi index 9ebcbc0..2e82f5b 100644 --- a/lang/zh-cn/typeshed/stdlib/machine.pyi +++ b/lang/zh-cn/typeshed/stdlib/machine.pyi @@ -1,84 +1,97 @@ -"""低级实用程序。 (机器)""" +"""Low-level utilities. +""" from typing import Any from .microbit import MicroBitDigitalPin def unique_id() -> bytes: - """获取具有板的唯一标识符的字节字符串。 + """Get a byte string with a unique identifier of a board. -Example: ``machine.unique_id()`` + Example: ``machine.unique_id()`` -:return: An identifier that varies from one board instance to another.""" + :return: An identifier that varies from one board instance to another. + """ ... def reset() -> None: - """以类似于按下外部 RESET (重置)按钮的方式重置设备。 + """Reset the device in a manner similar to pushing the external RESET button. -Example: ``machine.reset()``""" + Example: ``machine.reset()`` + """ ... def freq() -> int: - """以赫兹为单位获取 CPU 频率。 + """Get the CPU frequency in hertz. -Example: ``machine.freq()`` + Example: ``machine.freq()`` -:return: The CPU frequency.""" + :return: The CPU frequency. + """ ... def disable_irq() -> Any: - """禁止中断请求。 + """Disable interrupt requests. -Example: ``interrupt_state = machine.disable_irq()`` + Example: ``interrupt_state = machine.disable_irq()`` -:return: the previous IRQ state which should be considered an opaque value + :return: the previous IRQ state which should be considered an opaque value -The return value should be passed to the ``enable_irq`` function to restore -interrupts to their original state.""" + The return value should be passed to the ``enable_irq`` function to restore + interrupts to their original state. + """ ... def enable_irq(state: Any) -> None: - """重新启用中断请求。 + """Re-enable interrupt requests. -Example: ``machine.enable_irq(interrupt_state)`` + Example: ``machine.enable_irq(interrupt_state)`` -:param state: 最近一次调用 ``disable_irq`` 函数得到的返回值。""" + :param state: The value that was returned from the most recent call to the ``disable_irq`` function. + """ ... -def time_pulse_us(pin: MicroBitDigitalPin, pulse_level: int, timeout_us: int=1000000) -> int: - """对引脚上的脉冲计时。 +def time_pulse_us( + pin: MicroBitDigitalPin, pulse_level: int, timeout_us: int = 1000000 +) -> int: + """Time a pulse on a pin. -Example: ``time_pulse_us(pin0, 1)`` + Example: ``time_pulse_us(pin0, 1)`` -If the current input value of the pin is different to ``pulse_level``, the -function first waits until the pin input becomes equal to -``pulse_level``, then times the duration that the pin is equal to -``pulse_level``. If the pin is already equal to ``pulse_level`` then timing -starts straight away. + If the current input value of the pin is different to ``pulse_level``, the + function first waits until the pin input becomes equal to + ``pulse_level``, then times the duration that the pin is equal to + ``pulse_level``. If the pin is already equal to ``pulse_level`` then timing + starts straight away. -:param pin: (引脚) 要使用的引脚 -:param pulse_level: 0 来计时低脉冲或 1 来计时高脉冲。 -:param timeout_us: 微秒超时 -:return: The duration of the pulse in microseconds, or -1 for a timeout waiting for the level to match ``pulse_level``, or -2 on timeout waiting for the pulse to end""" + :param pin: The pin to use + :param pulse_level: 0 to time a low pulse or 1 to time a high pulse + :param timeout_us: A microsecond timeout + :return: The duration of the pulse in microseconds, or -1 for a timeout waiting for the level to match ``pulse_level``, or -2 on timeout waiting for the pulse to end + """ ... class mem: - """``mem8``、 ``mem16`` 和 ``mem32`` 内存视图的类。""" + """The class for the ``mem8``, ``mem16`` and ``mem32`` memory views.""" def __getitem__(self, address: int) -> int: - """从内存中获取一个值。 + """Access a value from memory. -:param address: (地址) 内存地址。 -:return: The value at that address as an integer.""" + :param address: The memory address. + :return: The value at that address as an integer. + """ ... - def __setitem__(self, address: int, value: int) -> None: - """在给定地址处设置一个值。 + """Set a value at the given address. -:param address: (地址) 内存地址。 -:param value: 要设置的整数值。""" + :param address: The memory address. + :param value: The integer value to set. + """ ... + mem8: mem -"""8 位(字节) 内存视图。""" +"""8-bit (byte) view of memory.""" + mem16: mem -"""16 位内存视图。""" +"""16-bit view of memory.""" + mem32: mem -"""32 位内存视图。""" \ No newline at end of file +"""32-bit view of memory.""" diff --git a/lang/zh-cn/typeshed/stdlib/math.pyi b/lang/zh-cn/typeshed/stdlib/math.pyi index 95acc4f..f82d4de 100644 --- a/lang/zh-cn/typeshed/stdlib/math.pyi +++ b/lang/zh-cn/typeshed/stdlib/math.pyi @@ -1,246 +1,273 @@ -"""数学函数。 (数学)""" +"""Mathematical functions. +""" + from typing import Tuple def acos(x: float) -> float: - """计算反余弦。 + """Calculate the inverse cosine. -Example: ``math.acos(1)`` + Example: ``math.acos(1)`` -:param x: 一个数字 -:return: The inverse cosine of ``x``""" + :param x: A number + :return: The inverse cosine of ``x`` + """ ... def asin(x: float) -> float: - """计算反正弦值。 + """Calculate the inverse sine. -Example: ``math.asin(0)`` + Example: ``math.asin(0)`` -:param x: 一个数字 -:return: The inverse sine of ``x``""" + :param x: A number + :return: The inverse sine of ``x`` + """ ... def atan(x: float) -> float: - """计算反正切。 + """Calculate the inverse tangent. -Example: ``math.atan(0)`` + Example: ``math.atan(0)`` -:param x: 一个数字 -:return: The inverse tangent of ``x``""" + :param x: A number + :return: The inverse tangent of ``x`` + """ ... def atan2(y: float, x: float) -> float: - """计算 ``y/x`` 的反正切的主值。 + """Calculate the principal value of the inverse tangent of ``y/x``. -Example: ``math.atan2(0, -1)`` + Example: ``math.atan2(0, -1)`` -:param y: 一个数字 -:param x: 一个数字 -:return: The principal value of the inverse tangent of ``y/x``""" + :param y: A number + :param x: A number + :return: The principal value of the inverse tangent of ``y/x`` + """ ... def ceil(x: float) -> float: - """将数字向正无穷大取整(向上取整) + """Round a number towards positive infinity. -Example: ``math.ceil(0.1)`` + Example: ``math.ceil(0.1)`` -:param x: 一个数字 -:return: ``x`` rounded towards positive infinity.""" + :param x: A number + :return: ``x`` rounded towards positive infinity. + """ ... def copysign(x: float, y: float) -> float: - """获取 ``y`` 的符号和 ``x`` 的绝对值。 + """Calculate ``x`` with the sign of ``y``. -Example: ``math.copysign(1, -1)`` + Example: ``math.copysign(1, -1)`` -:param x: 一个数字 -:param y: 返回值的符号来源 -:return: ``x`` with the sign of ``y``""" + :param x: A number + :param y: The source of the sign for the return value + :return: ``x`` with the sign of ``y`` + """ ... def cos(x: float) -> float: - """计算 ``x`` 的余弦。 + """Calculate the cosine of ``x``. -Example: ``math.cos(0)`` + Example: ``math.cos(0)`` -:param x: 一个数字 -:return: The cosine of ``x``""" + :param x: A number + :return: The cosine of ``x`` + """ ... def degrees(x: float) -> float: - """将弧度转换为度。 + """Convert radians to degrees. -Example: ``math.degrees(2 * math.pi)`` + Example: ``math.degrees(2 * math.pi)`` -:param x: 一个以弧度为单位的值 -:return: The value converted to degrees""" + :param x: A value in radians + :return: The value converted to degrees""" ... def exp(x: float) -> float: - """计算 E 的 ``x`` 指数。 + """Calculate the exponential of ``x``. -Example: ``math.exp(1)`` + Example: ``math.exp(1)`` -:param x: 一个数字 -:return: The exponential of ``x``.""" + :param x: A number + :return: The exponential of ``x``. + """ ... def fabs(x: float) -> float: - """返回 ``x`` 的绝对值。 + """Return the absolute value of ``x``. -Example: ``math.fabs(-0.1)`` + Example: ``math.fabs(-0.1)`` -:param x: 一个数字 -:return: The absolute value of ``x``""" + :param x: A number + :return: The absolute value of ``x`` + """ ... def floor(x: float) -> int: - """将数字向负无穷大取整(向下取整)。 (向下取整) + """Round a number towards negative infinity. -Example: ``math.floor(0.9)`` + Example: ``math.floor(0.9)`` -:param x: 一个数字 -:return: ``x`` rounded towards negative infinity.""" + :param x: A number + :return: ``x`` rounded towards negative infinity. + """ ... def fmod(x: float, y: float) -> float: - """计算 ``x/y`` 的余数。 (浮点余数) + """Calculate the remainder of ``x/y``. -Example: ``math.fmod(10, 3)`` + Example: ``math.fmod(10, 3)`` -:param x: 分子 -:param y: 分母""" + :param x: The numerator + :param y: The denominator + """ ... def frexp(x: float) -> Tuple[float, int]: - """将一个浮点数分解为其尾数和指数。 (浮点指数) + """Decomposes a floating-point number into its mantissa and exponent. -Example: ``mantissa, exponent = math.frexp(2)`` + Example: ``mantissa, exponent = math.frexp(2)`` -The returned value is the tuple ``(m, e)`` such that ``x == m * 2**e`` -exactly. If ``x == 0`` then the function returns ``(0.0, 0)``, otherwise -the relation ``0.5 <= abs(m) < 1`` holds. + The returned value is the tuple ``(m, e)`` such that ``x == m * 2**e`` + exactly. If ``x == 0`` then the function returns ``(0.0, 0)``, otherwise + the relation ``0.5 <= abs(m) < 1`` holds. -:param x: 一个浮点数 -:return: A tuple of length two containing its mantissa then exponent""" + :param x: A floating-point number + :return: A tuple of length two containing its mantissa then exponent + """ ... def isfinite(x: float) -> bool: - """检查值是否有限。 (是有限的) + """Check if a value is finite. -Example: ``math.isfinite(float('inf'))`` + Example: ``math.isfinite(float('inf'))`` -:param x: 一个数字。 -:return: ``True`` if ``x`` is finite, ``False`` otherwise.""" + :param x: A number. + :return: ``True`` if ``x`` is finite, ``False`` otherwise. + """ ... def isinf(x: float) -> bool: - """检查值是否无限。 (是无限的) + """Check if a value is infinite. -Example: ``math.isinf(float('-inf'))`` + Example: ``math.isinf(float('-inf'))`` -:param x: 一个数字。 -:return: ``True`` if ``x`` is infinite, ``False`` otherwise.""" + :param x: A number. + :return: ``True`` if ``x`` is infinite, ``False`` otherwise. + """ ... def isnan(x: float) -> bool: - """检查一个值是否不是一个数字 (NaN)。 (不是数字) + """Check if a value is not-a-number (NaN). -Example: ``math.isnan(float('nan'))`` + Example: ``math.isnan(float('nan'))`` -:param x: 一个数字 -:return: ``True`` if ``x`` is not-a-number (NaN), ``False`` otherwise.""" + :param x: A number + :return: ``True`` if ``x`` is not-a-number (NaN), ``False`` otherwise.""" ... def ldexp(x: float, exp: int) -> float: - """计算 ``x * (2**exp)`` 。 (加载指数) + """Calculate ``x * (2**exp)``. -Example: ``math.ldexp(0.5, 2)`` + Example: ``math.ldexp(0.5, 2)`` -:param x: 一个数字 -:param exp: 整数指数 -:return: ``x * (2**exp)``""" + :param x: A number + :param exp: Integer exponent + :return: ``x * (2**exp)`` + """ ... -def log(x: float, base: float=e) -> float: - """计算给定底数 ``x`` 的对数(默认为自然对数)。 (日志) +def log(x: float, base: float = e) -> float: + """Calculate the logarithm of ``x`` to the given base (defaults to natural logorithm). -Example: ``math.log(math.e)`` + Example: ``math.log(math.e)`` -With one argument, return the natural logarithm of x (to base e). + With one argument, return the natural logarithm of x (to base e). -With two arguments, return the logarithm of x to the given base, calculated as ``log(x)/log(base)``. + With two arguments, return the logarithm of x to the given base, calculated as ``log(x)/log(base)``. -:param x: 一个数字 -:param base: 要使用的底数 -:return: The natural logarithm of ``x``""" + :param x: A number + :param base: The base to use + :return: The natural logarithm of ``x`` + """ ... def modf(x: float) -> Tuple[float, float]: - """计算 ``x`` 的小数和整数部分。 (浮点取模) + """Calculate the fractional and integral parts of ``x``. -Example: ``fractional, integral = math.modf(1.5)`` + Example: ``fractional, integral = math.modf(1.5)`` -:param x: 一个数字 -:return: A tuple of two floats representing the fractional then integral parts of ``x``. + :param x: A number + :return: A tuple of two floats representing the fractional then integral parts of ``x``. -Both the fractional and integral values have the same sign as ``x``.""" + Both the fractional and integral values have the same sign as ``x``. + """ ... def pow(x: float, y: float) -> float: - """返回 ``x`` 的 ``y``次幂。 (幂数) + """Returns ``x`` to the power of ``y``. -Example: ``math.pow(4, 0.5)`` + Example: ``math.pow(4, 0.5)`` -:param x: 一个数字 -:param y: 指数值 -:return: ``x`` to the power of ``y``""" + :param x: A number + :param y: The exponent + :return: ``x`` to the power of ``y`` + """ ... def radians(x: float) -> float: - """将度数转换为弧度。 + """Convert a degrees to radians. -Example: ``math.radians(360)`` + Example: ``math.radians(360)`` -:param x: 以度为单位的值 -:return: The value converted to radians""" + :param x: A value in degrees + :return: The value converted to radians + """ ... def sin(x: float) -> float: - """计算 ``x`` 的正弦值。 (正弦) + """Calculate the sine of ``x``. -Example: ``math.sin(math.pi/2)`` + Example: ``math.sin(math.pi/2)`` -:param x: 一个数字 -:return: The sine of ``x``""" + :param x: A number + :return: The sine of ``x`` + """ ... def sqrt(x: float) -> float: - """计算 ``x`` 的平方根。 (平方根) + """Calculate the square root of ``x``. -Example: ``math.sqrt(4)`` + Example: ``math.sqrt(4)`` -:param x: 一个数字 -:return: The square root of ``x``""" + :param x: A number + :return: The square root of ``x`` + """ ... def tan(x: float) -> float: - """计算 ``x`` 的正切。 (正切) + """Calculate the tangent of ``x``. -Example: ``math.tan(0)`` + Example: ``math.tan(0)`` -:param x: 一个数字 -:return: The tangent of ``x``.""" + :param x: A number + :return: The tangent of ``x``. + """ ... def trunc(x: float) -> int: - """将数字向 0 舍入。 (截断) + """Round a number towards 0. -Example: ``math.trunc(-0.9)`` + Example: ``math.trunc(-0.9)`` -:param x: 一个数字 -:return: ``x`` rounded towards zero.""" + :param x: A number + :return: ``x`` rounded towards zero. + """ ... + e: float -"""自然对数的底数""" +"""Base of the natural logarithm""" + pi: float -"""圆的周长与其直径的比值""" \ No newline at end of file +"""The ratio of a circle's circumference to its diameter""" diff --git a/lang/zh-cn/typeshed/stdlib/microbit/__init__.pyi b/lang/zh-cn/typeshed/stdlib/microbit/__init__.pyi index 092c20e..f12158f 100644 --- a/lang/zh-cn/typeshed/stdlib/microbit/__init__.pyi +++ b/lang/zh-cn/typeshed/stdlib/microbit/__init__.pyi @@ -1,6 +1,11 @@ -"""引脚、图像、声音、温度和音量。 (Microbit)""" +"""Pins, images, sounds, temperature and volume. +""" + from typing import Any, Callable, List, Optional, Tuple, Union, overload + from _typeshed import ReadableBuffer + +# V2 only from . import accelerometer as accelerometer from . import audio as audio from . import compass as compass @@ -11,696 +16,831 @@ from . import speaker as speaker from . import spi as spi from . import uart as uart -def run_every(callback: Optional[Callable[[], None]]=None, days: int=0, h: int=0, min: int=0, s: int=0, ms: int=0) -> Callable[[Callable[[], None]], Callable[[], None]]: - """计划以时间参数指定的时间间隔运行函数**仅限V2** 。 (周期性运行) +def run_every( + callback: Optional[Callable[[], None]] = None, + days: int = 0, + h: int = 0, + min: int = 0, + s: int = 0, + ms: int = 0, +) -> Callable[[Callable[[], None]], Callable[[], None]]: + """Schedule to run a function at the interval specified by the time arguments **V2 only**. -Example: ``run_every(my_logging, min=5)`` + Example: ``run_every(my_logging, min=5)`` -``run_every`` can be used in two ways: + ``run_every`` can be used in two ways: -As a Decorator - placed on top of the function to schedule. For example:: + As a Decorator - placed on top of the function to schedule. For example:: - @run_every(h=1, min=20, s=30, ms=50) - def my_function(): - # Do something here + @run_every(h=1, min=20, s=30, ms=50) + def my_function(): + # Do something here -As a Function - passing the callback as a positional argument. For example:: + As a Function - passing the callback as a positional argument. For example:: - def my_function(): - # Do something here - run_every(my_function, s=30) + def my_function(): + # Do something here + run_every(my_function, s=30) -Each argument corresponds to a different time unit and they are additive. -So ``run_every(min=1, s=30)`` schedules the callback every minute and a half. + Each argument corresponds to a different time unit and they are additive. + So ``run_every(min=1, s=30)`` schedules the callback every minute and a half. -When an exception is thrown inside the callback function it deschedules the -function. To avoid this you can catch exceptions with ``try/except``. + When an exception is thrown inside the callback function it deschedules the + function. To avoid this you can catch exceptions with ``try/except``. -:param callback: 在提供的时间间隔内调用的函数。用作装饰器时省略。 -:param days: (天) 设置定时计划的日期标记。 -:param h: 设置定时计划的小时标记。 -:param min: (分钟) 设置定时计划的分钟标记。 -:param s: (秒) 设置定时计划的秒标记。 -:param ms: (毫秒) 设置定时计划的毫秒标记。""" + :param callback: Function to call at the provided interval. Omit when using as a decorator. + :param days: Sets the day mark for the scheduling. + :param h: Sets the hour mark for the scheduling. + :param min: Sets the minute mark for the scheduling. + :param s: Sets the second mark for the scheduling. + :param ms: Sets the millisecond mark for the scheduling. + """ def panic(n: int) -> None: - """进入 panic (恐慌)模式。 (恐慌) + """Enter a panic mode. -Example: ``panic(127)`` + Example: ``panic(127)`` -:param n: 一个 <= 255 的任意整数,以表示一个状态。 + :param n: An arbitrary integer <= 255 to indicate a status. -Requires restart.""" + Requires restart. + """ def reset() -> None: - """重启主板。""" + """Restart the board.""" + @overload def scale(value: float, from_: Tuple[float, float], to: Tuple[int, int]) -> int: - """将一个数值从一个范围转换为整数范围。 (范围) + """Converts a value from a range to an integer range. -Example: ``volume = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255))`` + Example: ``volume = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255))`` -For example, to convert an accelerometer X value to a speaker volume. + For example, to convert an accelerometer X value to a speaker volume. -If one of the numbers in the ``to`` parameter is a floating point -(i.e a decimal number like ``10.0``), this function will return a -floating point number. + If one of the numbers in the ``to`` parameter is a floating point + (i.e a decimal number like ``10.0``), this function will return a + floating point number. - temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0)) + temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0)) -:param value: 要转换的数字。 -:param from_: (从) 一个元组,用于定义要转换的范围。 -:param to: (至) 一个元组,用于定义要转换到的范围。 -:return: The ``value`` converted to the ``to`` range.""" + :param value: A number to convert. + :param from_: A tuple to define the range to convert from. + :param to: A tuple to define the range to convert to. + :return: The ``value`` converted to the ``to`` range. + """ @overload def scale(value: float, from_: Tuple[float, float], to: Tuple[float, float]) -> float: - """将一个数值从一个范围转换为浮点数范围。 (范围) + """Converts a value from a range to a floating point range. -Example: ``temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0))`` + Example: ``temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0))`` -For example, to convert temperature from a Celsius scale to Fahrenheit. + For example, to convert temperature from a Celsius scale to Fahrenheit. -If one of the numbers in the ``to`` parameter is a floating point -(i.e a decimal number like ``10.0``), this function will return a -floating point number. -If they are both integers (i.e ``10``), it will return an integer:: + If one of the numbers in the ``to`` parameter is a floating point + (i.e a decimal number like ``10.0``), this function will return a + floating point number. + If they are both integers (i.e ``10``), it will return an integer:: - returns_int = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255)) + returns_int = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255)) -:param value: 要转换的数字。 -:param from_: (从) 一个元组,用于定义要转换的范围。 -:param to: (至) 一个元组,用于定义要转换到的范围。 -:return: The ``value`` converted to the ``to`` range.""" + :param value: A number to convert. + :param from_: A tuple to define the range to convert from. + :param to: A tuple to define the range to convert to. + :return: The ``value`` converted to the ``to`` range. + """ def sleep(n: float) -> None: - """等待 ``n`` 毫秒。 (休眠) + """Wait for ``n`` milliseconds. -Example: ``sleep(1000)`` + Example: ``sleep(1000)`` -:param n: 要等待的毫秒数 + :param n: The number of milliseconds to wait -One second is 1000 milliseconds, so:: + One second is 1000 milliseconds, so:: - microbit.sleep(1000) + microbit.sleep(1000) -will pause the execution for one second.""" + will pause the execution for one second. + """ def running_time() -> int: - """获取主板的运行时间。 + """Get the running time of the board. -:return: The number of milliseconds since the board was switched on or restarted.""" + :return: The number of milliseconds since the board was switched on or restarted. + """ def temperature() -> int: - """以摄氏度为单位获取 micro:bit 的温度。""" + """Get the temperature of the micro:bit in degrees Celsius.""" def set_volume(v: int) -> None: - """设置音量。 + """Sets the volume. -Example: ``set_volume(127)`` + Example: ``set_volume(127)`` -:param v: 一个介于 0 (低) 和 255 (高) 之间的值。 + :param v: a value between 0 (low) and 255 (high). -Out of range values will be clamped to 0 or 255. + Out of range values will be clamped to 0 or 255. -**V2** only.""" + **V2** only. + """ ... class Button: - """按钮 ``button_a`` 和 ``button_b`` 的类。""" + """The class for the buttons ``button_a`` and ``button_b``.""" def is_pressed(self) -> bool: - """检查按钮是否被按下。 + """Check if the button is pressed. -:return: ``True`` if the specified button ``button`` is pressed, and ``False`` otherwise.""" + :return: ``True`` if the specified button ``button`` is pressed, and ``False`` otherwise. + """ ... - def was_pressed(self) -> bool: - """检查按钮自设备启动以来或者上次调用此方法之后是否被按下。 + """Check if the button was pressed since the device started or the last time this method was called. -Calling this method will clear the press state so -that the button must be pressed again before this method will return -``True`` again. + Calling this method will clear the press state so + that the button must be pressed again before this method will return + ``True`` again. -:return: ``True`` if the specified button ``button`` was pressed, and ``False`` otherwise""" + :return: ``True`` if the specified button ``button`` was pressed, and ``False`` otherwise + """ ... - def get_presses(self) -> int: - """获得按钮被按下的总计次数,并在返回之前将该总计次数重置为 0。 + """Get the running total of button presses, and resets this total + to zero before returning. -:return: The number of presses since the device started or the last time this method was called""" + :return: The number of presses since the device started or the last time this method was called + """ ... + button_a: Button -"""左键 ``Button`` 对象。 (按钮 a)""" +"""The left button ``Button`` object.""" + button_b: Button -"""右键 ``Button`` 对象。 (按钮 b)""" +"""The right button ``Button`` object.""" class MicroBitDigitalPin: - """数字引脚。 (Microbit 数字引脚) + """A digital pin. + + Some pins support analog and touch features using the ``MicroBitAnalogDigitalPin`` and ``MicroBitTouchPin`` subclasses. + """ -Some pins support analog and touch features using the ``MicroBitAnalogDigitalPin`` and ``MicroBitTouchPin`` subclasses.""" NO_PULL: int PULL_UP: int PULL_DOWN: int - def read_digital(self) -> int: - """获取引脚的数字值。 + """Get the digital value of the pin. -Example: ``value = pin0.read_digital()`` + Example: ``value = pin0.read_digital()`` -:return: 1 if the pin is high, and 0 if it's low.""" + :return: 1 if the pin is high, and 0 if it's low. + """ ... - def write_digital(self, value: int) -> None: - """设置引脚的数字值。 + """Set the digital value of the pin. -Example: ``pin0.write_digital(1)`` + Example: ``pin0.write_digital(1)`` -:param value: 1 将引脚设置为高电平,或 0 将引脚设置为低电平""" + :param value: 1 to set the pin high or 0 to set the pin low""" ... - def set_pull(self, value: int) -> None: - """将拉取状态设置为以下三个可能的值之一:``PULL_UP``、``PULL_DOWN`` 或 N``NO_PULL``。 + """Set the pull state to one of three possible values: ``PULL_UP``, ``PULL_DOWN`` or ``NO_PULL``. -Example: ``pin0.set_pull(pin0.PULL_UP)`` + Example: ``pin0.set_pull(pin0.PULL_UP)`` -:param value: 相关引脚的拉取状态,例如: ``pin0.PULL_UP``。""" + :param value: The pull state from the relevant pin, e.g. ``pin0.PULL_UP``. + """ ... - def get_pull(self) -> int: - """获取引脚上的拉取状态。 + """Get the pull state on a pin. -Example: ``pin0.get_pull()`` + Example: ``pin0.get_pull()`` -:return: ``NO_PULL``, ``PULL_DOWN``, or ``PULL_UP`` + :return: ``NO_PULL``, ``PULL_DOWN``, or ``PULL_UP`` -These are set using the ``set_pull()`` method or automatically configured -when a pin mode requires it.""" + These are set using the ``set_pull()`` method or automatically configured + when a pin mode requires it. + """ ... - def get_mode(self) -> str: - """返回引脚模式。 + """Returns the pin mode. -Example: ``pin0.get_mode()`` + Example: ``pin0.get_mode()`` -When a pin is used for a specific function, like -writing a digital value, or reading an analog value, the pin mode -changes. + When a pin is used for a specific function, like + writing a digital value, or reading an analog value, the pin mode + changes. -:return: ``"unused"``, ``"analog"``, ``"read_digital"``, ``"write_digital"``, ``"display"``, ``"button"``, ``"music"``, ``"audio"``, ``"touch"``, ``"i2c"``, or ``"spi"``""" + :return: ``"unused"``, ``"analog"``, ``"read_digital"``, ``"write_digital"``, ``"display"``, ``"button"``, ``"music"``, ``"audio"``, ``"touch"``, ``"i2c"``, or ``"spi"`` + """ ... - def write_analog(self, value: int) -> None: - """在引脚上输出 PWM 信号,占空比为 ``value``。 - -Example: ``pin0.write_analog(254)`` + """Output a PWM signal on the pin, with the duty cycle proportional to ``value``. -:param value: 介于 0(0% 占空比)和 1023(100% 占空比)之间的整数或浮点数。""" + Example: ``pin0.write_analog(254)`` + :param value: An integer or a floating point number between 0 (0% duty cycle) and 1023 (100% duty). + """ def set_analog_period(self, period: int) -> None: - """将输出的 PWM 信号的周期设置为 ``period``(单位:毫秒)。 + """Set the period of the PWM signal being output to ``period`` in milliseconds. -Example: ``pin0.set_analog_period(10)`` - -:param period: 以毫秒为单位的周期,最小有效值为 1 毫秒。""" + Example: ``pin0.set_analog_period(10)`` + :param period: The period in milliseconds with a minimum valid value of 1ms. + """ def set_analog_period_microseconds(self, period: int) -> None: - """将输出的 PWM 信号的周期设置为 ``period``(单位:微秒)。 + """Set the period of the PWM signal being output to ``period`` in microseconds. -Example: ``pin0.set_analog_period_microseconds(512)`` + Example: ``pin0.set_analog_period_microseconds(512)`` -:param period: 以微秒为单位的周期,最小有效值为 256 毫秒。""" + :param period: The period in microseconds with a minimum valid value of 256µs. + """ class MicroBitAnalogDigitalPin(MicroBitDigitalPin): - """带有模拟和数字功能的引脚。""" + """A pin with analog and digital features.""" def read_analog(self) -> int: - """读取应用于引脚的电压。 + """Read the voltage applied to the pin. -Example: ``pin0.read_analog()`` + Example: ``pin0.read_analog()`` -:return: An integer between 0 (meaning 0V) and 1023 (meaning 3.3V).""" + :return: An integer between 0 (meaning 0V) and 1023 (meaning 3.3V). + """ class MicroBitTouchPin(MicroBitAnalogDigitalPin): - """带有模拟、数字和触摸功能的引脚。""" + """A pin with analog, digital and touch features.""" + CAPACITIVE: int RESISTIVE: int - def is_touched(self) -> bool: - """检查引脚是否被触摸。 + """Check if the pin is being touched. -Example: ``pin0.is_touched()`` + Example: ``pin0.is_touched()`` -The default touch mode for the pins on the edge connector is ``resistive``. -The default for the logo pin **V2** is ``capacitive``. + The default touch mode for the pins on the edge connector is ``resistive``. + The default for the logo pin **V2** is ``capacitive``. -**Resistive touch** -This test is done by measuring how much resistance there is between the -pin and ground. A low resistance gives a reading of ``True``. To get -a reliable reading using a finger you may need to touch the ground pin -with another part of your body, for example your other hand. + **Resistive touch** + This test is done by measuring how much resistance there is between the + pin and ground. A low resistance gives a reading of ``True``. To get + a reliable reading using a finger you may need to touch the ground pin + with another part of your body, for example your other hand. -**Capacitive touch** -This test is done by interacting with the electric field of a capacitor -using a finger as a conductor. `Capacitive touch -`_ -does not require you to make a ground connection as part of a circuit. + **Capacitive touch** + This test is done by interacting with the electric field of a capacitor + using a finger as a conductor. `Capacitive touch + `_ + does not require you to make a ground connection as part of a circuit. -:return: ``True`` if the pin is being touched with a finger, otherwise return ``False``.""" + :return: ``True`` if the pin is being touched with a finger, otherwise return ``False``. + """ ... - def set_touch_mode(self, value: int) -> None: - """设置引脚的触摸模式。 + """Set the touch mode for the pin. -Example: ``pin0.set_touch_mode(pin0.CAPACITIVE)`` + Example: ``pin0.set_touch_mode(pin0.CAPACITIVE)`` -The default touch mode for the pins on the edge connector is -``resistive``. The default for the logo pin **V2** is ``capacitive``. + The default touch mode for the pins on the edge connector is + ``resistive``. The default for the logo pin **V2** is ``capacitive``. -:param value: 来自相关引脚的 ``CAPACITIVE`` 或 ``RESISTIVE``。""" + :param value: ``CAPACITIVE`` or ``RESISTIVE`` from the relevant pin. + """ ... + pin0: MicroBitTouchPin -"""具有数字、模拟和触摸功能的引脚。 (引脚0)""" +"""Pin with digital, analog and touch features.""" + pin1: MicroBitTouchPin -"""具有数字、模拟和触摸功能的引脚。 (引脚1)""" +"""Pin with digital, analog and touch features.""" + pin2: MicroBitTouchPin -"""具有数字、模拟和触摸功能的引脚。 (引脚2)""" +"""Pin with digital, analog and touch features.""" + pin3: MicroBitAnalogDigitalPin -"""具有数字和模拟功能的引脚。 (引脚3)""" +"""Pin with digital and analog features.""" + pin4: MicroBitAnalogDigitalPin -"""具有数字和模拟功能的引脚。 (引脚4)""" +"""Pin with digital and analog features.""" + pin5: MicroBitDigitalPin -"""具有数字功能的引脚。 (引脚5)""" +"""Pin with digital features.""" + pin6: MicroBitDigitalPin -"""具有数字功能的引脚。 (引脚6)""" +"""Pin with digital features.""" + pin7: MicroBitDigitalPin -"""具有数字功能的引脚。 (引脚7)""" +"""Pin with digital features.""" + pin8: MicroBitDigitalPin -"""具有数字功能的引脚。 (引脚8)""" +"""Pin with digital features.""" + pin9: MicroBitDigitalPin -"""具有数字功能的引脚。 (引脚9)""" +"""Pin with digital features.""" + pin10: MicroBitAnalogDigitalPin -"""具有数字和模拟功能的引脚。 (引脚10)""" +"""Pin with digital and analog features.""" + pin11: MicroBitDigitalPin -"""具有数字功能的引脚。 (引脚11)""" +"""Pin with digital features.""" + pin12: MicroBitDigitalPin -"""具有数字功能的引脚。 (引脚12)""" +"""Pin with digital features.""" + pin13: MicroBitDigitalPin -"""具有数字功能的引脚。 (引脚13)""" +"""Pin with digital features.""" + pin14: MicroBitDigitalPin -"""具有数字功能的引脚。 (引脚14)""" +"""Pin with digital features.""" + pin15: MicroBitDigitalPin -"""具有数字功能的引脚。 (引脚15)""" +"""Pin with digital features.""" + pin16: MicroBitDigitalPin -"""具有数字功能的引脚。 (引脚16)""" +"""Pin with digital features.""" + pin19: MicroBitDigitalPin -"""具有数字功能的引脚。 (引脚19)""" +"""Pin with digital features.""" + pin20: MicroBitDigitalPin -"""具有数字功能的引脚。 (引脚20)""" +"""Pin with digital features.""" + pin_logo: MicroBitTouchPin -"""micro:bit 正面的触摸感应标志引脚,默认设置为电容式触摸模式。 (引脚标志)""" +"""A touch sensitive logo pin on the front of the micro:bit, which by default is set to capacitive touch mode.""" + pin_speaker: MicroBitAnalogDigitalPin -"""用于对 micro:bit 扬声器寻址的引脚。 (扬声器引脚) +"""A pin to address the micro:bit speaker. This API is intended only for use in Pulse-Width Modulation pin operations e.g. pin_speaker.write_analog(128). """ class Image: - """在 micro:bit LED 显示屏上显示的图像。 (图像) + """An image to show on the micro:bit LED display. -Given an image object it's possible to display it via the ``display`` API:: + Given an image object it's possible to display it via the ``display`` API:: + + display.show(Image.HAPPY) + """ - display.show(Image.HAPPY)""" HEART: Image - """心形图像 (心形)""" + """Heart image.""" + HEART_SMALL: Image - """小的心形图像。 (小的心形)""" + """Small heart image.""" + HAPPY: Image - """快乐的脸部图像。 (快乐)""" + """Happy face image.""" + SMILE: Image - """微笑的脸部图像。 (微笑)""" + """Smiling mouth image.""" + SAD: Image - """难过的脸部图像。 (难过)""" + """Sad face image.""" + CONFUSED: Image - """困惑的面部图像。 (困惑)""" + """Confused face image.""" + ANGRY: Image - """愤怒的脸部图像。 (愤怒)""" + """Angry face image.""" + ASLEEP: Image - """睡着的脸部图像。 (睡着)""" + """Sleeping face image.""" + SURPRISED: Image - """惊讶的脸部图像。 (惊讶)""" + """Surprised face image.""" + SILLY: Image - """傻傻的脸部图像。 (傻的)""" + """Silly face image.""" + FABULOUS: Image - """戴墨镜的脸部图像。 (极好的)""" + """Sunglasses face image.""" + MEH: Image - """印象平平的脸部图像 (不感兴趣的)""" + """Unimpressed face image.""" + YES: Image - """对勾图像。 (是的)""" + """Tick image.""" + NO: Image - """打叉图像。 (不是)""" + """Cross image.""" + CLOCK12: Image - """指针指向 12 点钟位置的图像。 (时钟12点)""" + """Image with line pointing to 12 o'clock.""" + CLOCK11: Image - """指针指向 11 点钟位置的图像。 (时钟11点)""" + """Image with line pointing to 11 o'clock.""" + CLOCK10: Image - """指针指向 10 点钟位置的图像。 (时钟10点)""" + """Image with line pointing to 10 o'clock.""" + CLOCK9: Image - """指针指向 9 点钟位置的图像。 (时钟9点)""" + """Image with line pointing to 9 o'clock.""" + CLOCK8: Image - """指针指向 8 点钟位置的图像。 (时钟8点)""" + """Image with line pointing to 8 o'clock.""" + CLOCK7: Image - """指针指向 7 点钟位置的图像。 (时钟7点)""" + """Image with line pointing to 7 o'clock.""" + CLOCK6: Image - """指针指向 6 点钟位置的图像。 (时钟6点)""" + """Image with line pointing to 6 o'clock.""" + CLOCK5: Image - """指针指向 5 点钟位置的图像。 (时钟5点)""" + """Image with line pointing to 5 o'clock.""" + CLOCK4: Image - """指针指向 4 点钟位置的图像。 (时钟4点)""" + """Image with line pointing to 4 o'clock.""" + CLOCK3: Image - """指针指向 3 点钟位置的图像。 (时钟3点)""" + """Image with line pointing to 3 o'clock.""" + CLOCK2: Image - """指针指向 2 点钟位置的图像。 (时钟2点)""" + """Image with line pointing to 2 o'clock.""" + CLOCK1: Image - """指针指向 1 点钟位置的图像。 (时钟1点)""" + """Image with line pointing to 1 o'clock.""" + ARROW_N: Image - """指向北方的箭头的图像。 (箭头(指向北))""" + """Image of arrow pointing north.""" + ARROW_NE: Image - """指向东北方的箭头的图像。 (箭头(指向东北))""" + """Image of arrow pointing north east.""" + ARROW_E: Image - """指向东方的箭头的图像。 (箭头(指向东))""" + """Image of arrow pointing east.""" + ARROW_SE: Image - """指向东南方的箭头的图像。 (箭头(指向东南))""" + """Image of arrow pointing south east.""" + ARROW_S: Image - """指向南方的箭头图像。 (箭头(指向南))""" + """Image of arrow pointing south.""" + ARROW_SW: Image - """指向西南方的箭头的图像。 (箭头(指向西南))""" + """Image of arrow pointing south west.""" + ARROW_W: Image - """指向西方的箭头的图像。 (箭头(指向西))""" + """Image of arrow pointing west.""" + ARROW_NW: Image - """指向西北方的箭头的图像。 (箭头(指向西北))""" + """Image of arrow pointing north west.""" + TRIANGLE: Image - """向上的三角形图像。 (三角)""" + """Image of a triangle pointing up.""" + TRIANGLE_LEFT: Image - """左角的三角形图像。 (左三角)""" + """Image of a triangle in the left corner.""" + CHESSBOARD: Image - """按棋盘式交替点亮 LED。 (国际象棋棋盘)""" + """Alternate LEDs lit in a chessboard pattern.""" + DIAMOND: Image - """钻石图像。 (菱形)""" + """Diamond image.""" + DIAMOND_SMALL: Image - """小钻石图像。 (小的菱形)""" + """Small diamond image.""" + SQUARE: Image - """方形图像。 (正方形)""" + """Square image.""" + SQUARE_SMALL: Image - """小的方形图像。 (小方形)""" + """Small square image.""" + RABBIT: Image - """兔子图像。 (兔子)""" + """Rabbit image.""" + COW: Image - """奶牛图像。 (牛)""" + """Cow image.""" + MUSIC_CROTCHET: Image - """音乐音符图像 (音乐音符)""" + """Crotchet note image.""" + MUSIC_QUAVER: Image - """八分音符图像。 (八分音符)""" + """Quaver note image.""" + MUSIC_QUAVERS: Image - """一对八分音符图像。 (一对八分音符)""" + """Pair of quavers note image.""" + PITCHFORK: Image - """干草叉图像。 (干草叉)""" + """Pitchfork image.""" + XMAS: Image - """圣诞树图像。 (圣诞节)""" + """Christmas tree image.""" + PACMAN: Image - """吃豆人游戏角色图像。 (吃豆人)""" + """Pac-Man arcade character image.""" + TARGET: Image - """目标图像 (目标)""" + """Target image.""" + TSHIRT: Image - """T 恤图像。 (T恤)""" + """T-shirt image.""" + ROLLERSKATE: Image - """轮滑图像。 (轮滑)""" + """Rollerskate image.""" + DUCK: Image - """鸭子图像。 (鸭子)""" + """Duck image.""" + HOUSE: Image - """房子图像。 (房子)""" + """House image.""" + TORTOISE: Image - """乌龟图像。 (乌龟)""" + """Tortoise image.""" + BUTTERFLY: Image - """蝴蝶图像 (蝴蝶)""" + """Butterfly image.""" + STICKFIGURE: Image - """火柴人图像。 (简笔人物画)""" + """Stick figure image.""" + GHOST: Image - """幽灵图像。 (幽灵)""" + """Ghost image.""" + SWORD: Image - """利剑图像。 (剑)""" + """Sword image.""" + GIRAFFE: Image - """长颈鹿图像。 (长颈鹿)""" + """Giraffe image.""" + SKULL: Image - """骷髅图像。 (骷髅)""" + """Skull image.""" + UMBRELLA: Image - """雨伞图像。 (雨伞)""" + """Umbrella image.""" + SNAKE: Image - """蛇图像。 (蛇)""" + """Snake image.""" + SCISSORS: Image - """剪刀图像。 (剪刀)""" + """Scissors image.""" + ALL_CLOCKS: List[Image] - """按顺序包含所有 CLOCK_ 图像的列表(时钟)。 (所有时钟)""" - ALL_ARROWS: List[Image] - """按顺序包含所有 ARROW_ 图像的列表(箭头)。 (所有箭头)""" + """A list containing all the CLOCK_ images in sequence.""" + ALL_ARROWS: List[Image] + """A list containing all the ARROW_ images in sequence.""" @overload def __init__(self, string: str) -> None: - """根据描述点亮 LED 的字符串来创建一幅图像。 + """Create an image from a string describing which LEDs are lit. -``string`` has to consist of digits 0-9 arranged into lines, -describing the image, for example:: + ``string`` has to consist of digits 0-9 arranged into lines, + describing the image, for example:: - image = Image("90009:" - "09090:" - "00900:" - "09090:" - "90009") + 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 newlines (\\n) insead of the colons. + 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 newlines (\\n) insead of the colons. -:param string: 描述图像的字符串。""" + :param string: The string describing the image. + """ ... - @overload - def __init__(self, width: int=5, height: int=5, buffer: ReadableBuffer=None) -> None: - """创建一幅具有 ``width`` 列和 ``height`` 行的空白图像。 + def __init__( + self, width: int = 5, height: int = 5, buffer: ReadableBuffer = None + ) -> None: + """Create an empty image with ``width`` columns and ``height`` rows. -:param width: (宽度) 可选的图像宽度 -:param height: (高度) 可选的图像高度 -:param buffer: (缓冲区) 用可选数组或在 0-9 范围内的 ``width`` × ``height`` 整数字节来初始化图像 + :param width: Optional width of the image + :param height: Optional height of the image + :param buffer: Optional array or bytes of ``width``×``height`` integers in range 0-9 to initialize the image -Examples:: + Examples:: - Image(2, 2, b'\x08\x08\x08\x08') - Image(2, 2, bytearray([9,9,9,9])) + Image(2, 2, b'\x08\x08\x08\x08') + Image(2, 2, bytearray([9,9,9,9])) -These create 2 x 2 pixel images at full brightness.""" + These create 2 x 2 pixel images at full brightness. + """ ... - def width(self) -> int: - """获取列数。 (宽度) + """Get the number of columns. -:return: The number of columns in the image""" + :return: The number of columns in the image + """ ... - def height(self) -> int: - """获取行数。 (高度) + """Get the number of rows. -:return: The number of rows in the image""" + :return: The number of rows in the image + """ ... - def set_pixel(self, x: int, y: int, value: int) -> None: - """设置像素亮度。 + """Set the brightness of a pixel. -Example: ``my_image.set_pixel(0, 0, 9)`` + Example: ``my_image.set_pixel(0, 0, 9)`` -:param x: 列号 -:param y: 行号 -:param value: 用 0(暗)和 9(亮)之间的整数来代表亮度 + :param x: The column number + :param y: The row number + :param value: The brightness as an integer 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``.""" + 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: - """获取一个像素的亮度。 + """Get the brightness of a pixel. -Example: ``my_image.get_pixel(0, 0)`` + Example: ``my_image.get_pixel(0, 0)`` -:param x: 列号 -:param y: 行号 -:return: The brightness as an integer between 0 and 9.""" + :param x: The column number + :param y: The row number + :return: The brightness as an integer between 0 and 9. + """ ... - def shift_left(self, n: int) -> Image: - """通过向左移动图片来创建新图像。 + """Create a new image by shifting the picture left. -Example: ``Image.HEART_SMALL.shift_left(1)`` + Example: ``Image.HEART_SMALL.shift_left(1)`` -:param n: 要移动的列数 -:return: The shifted image""" + :param n: The number of columns to shift by + :return: The shifted image + """ ... - def shift_right(self, n: int) -> Image: - """通过向右移动图片来创建新图像。 + """Create a new image by shifting the picture right. -Example: ``Image.HEART_SMALL.shift_right(1)`` + Example: ``Image.HEART_SMALL.shift_right(1)`` -:param n: 要移动的列数 -:return: The shifted image""" + :param n: The number of columns to shift by + :return: The shifted image + """ ... - def shift_up(self, n: int) -> Image: - """通过向上移动图片来创建新图像。 + """Create a new image by shifting the picture up. -Example: ``Image.HEART_SMALL.shift_up(1)`` + Example: ``Image.HEART_SMALL.shift_up(1)`` -:param n: 要移动的行数 -:return: The shifted image""" + :param n: The number of rows to shift by + :return: The shifted image + """ ... - def shift_down(self, n: int) -> Image: - """通过向下移动图片来创建新图像。 + """Create a new image by shifting the picture down. -Example: ``Image.HEART_SMALL.shift_down(1)`` + Example: ``Image.HEART_SMALL.shift_down(1)`` -:param n: 要移动的行数 -:return: The shifted image""" + :param n: The number of rows to shift by + :return: The shifted image + """ ... - def crop(self, x: int, y: int, w: int, h: int) -> Image: - """通过裁剪图片来创建一幅新图像。 (裁剪) + """Create a new image by cropping the picture. -Example: ``Image.HEART.crop(1, 1, 3, 3)`` + Example: ``Image.HEART.crop(1, 1, 3, 3)`` -:param x: 裁剪偏移列 -:param y: 裁剪偏移行 -:param w: 裁剪宽度 -:param h: 裁剪高度 -:return: The new image""" + :param x: The crop offset column + :param y: The crop offset row + :param w: The crop width + :param h: The crop height + :return: The new image + """ ... - def copy(self) -> Image: - """创建图像的精确副本。 (复制) + """Create an exact copy of the image. -Example: ``Image.HEART.copy()`` + Example: ``Image.HEART.copy()`` -:return: The new image""" + :return: The new image + """ ... - def invert(self) -> Image: - """通过反转源图像中像素的亮度来创建一幅新图像。 (反转) + """Create a new image by inverting the brightness of the pixels in the + source image. -Example: ``Image.SMALL_HEART.invert()`` + Example: ``Image.SMALL_HEART.invert()`` -:return: The new image.""" + :return: The new image. + """ ... - def fill(self, value: int) -> None: - """设置图像中所有像素的亮度。 (填充) + """Set the brightness of all the pixels in the image. -Example: ``my_image.fill(5)`` + Example: ``my_image.fill(5)`` -:param value: 新亮度为 0 (暗) 和 9 (明) 之间的数字。 + :param value: The new brightness as a number 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``.""" + 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: - """复制另一幅图像的一部分区域到这幅图像。 - -Example: ``my_image.blit(Image.HEART, 1, 1, 3, 3, 1, 1)`` - -:param src: (来源) 源图像 -:param x: 源图像的起始列偏移量 -:param y: 源图像的起始行偏移量 -:param w: 要复制的列数 -:param h: 要复制的行数 -:param xdest: (x偏离量) 此图像中要修改的列偏移量 -:param ydest: (y偏离量) 此图像中要修改的行偏移量 - -Pixels outside the source image are treated as having a brightness 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 blit( + self, + src: Image, + x: int, + y: int, + w: int, + h: int, + xdest: int = 0, + ydest: int = 0, + ) -> None: + """Copy an area from another image into this image. + + Example: ``my_image.blit(Image.HEART, 1, 1, 3, 3, 1, 1)`` + + :param src: The source image + :param x: The starting column offset in the source image + :param y: The starting row offset in the source image + :param w: The number of columns to copy + :param h: The number of rows to copy + :param xdest: The column offset to modify in this image + :param ydest: The row offset to modify in this image + + Pixels outside the source image are treated as having a brightness 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. -Example: ``Image.HEART + Image.HAPPY`` + Example: ``Image.HEART + Image.HAPPY`` -:param other: (其他) 要添加的图像。""" + :param other: The image to add. + """ ... - def __sub__(self, other: Image) -> Image: - """通过从此图像中减去另一幅图像的亮度值来创建一幅新图像。 (减去) + """Create a new image by subtracting the brightness values of the + other image from this image. -Example: ``Image.HEART - Image.HEART_SMALL`` + Example: ``Image.HEART - Image.HEART_SMALL`` -:param other: (其他) 要减去的图像。""" + :param other: The image to subtract. + """ ... - def __mul__(self, n: float) -> Image: - """通过将每个像素的亮度乘以 ``n`` 来创建一幅新图像。 (相乘) + """Create a new image by multiplying the brightness of each pixel by + ``n``. -Example: ``Image.HEART * 0.5`` + Example: ``Image.HEART * 0.5`` -:param n: 要相乘的数值。""" + :param n: The value to multiply by. + """ ... - def __truediv__(self, n: float) -> Image: - """通过将每个像素的亮度除以 ``n`` 来创建一幅新图像。 (除以) + """Create a new image by dividing the brightness of each pixel by + ``n``. -Example: ``Image.HEART / 2`` + Example: ``Image.HEART / 2`` -:param n: 要除以的数值。""" + :param n: The value to divide by. + """ ... class SoundEvent: LOUD: SoundEvent - """表示声音事件从``quiet``到``loud``的过渡,如拍手或者喊叫。 (大声)""" + """Represents the transition of sound events, from ``quiet`` to ``loud`` like clapping or shouting.""" + QUIET: SoundEvent - """表示声音事件从``loud``到``quiet``的过渡,如说话或者背景音乐。 (安静)""" + """Represents the transition of sound events, from ``loud`` to ``quiet`` like speaking or background music.""" class Sound: - """可以使用 ``audio.play(Sound.NAME)`` 调用内置声音。 (声音)""" + """The built-in sounds can be called using ``audio.play(Sound.NAME)``.""" + GIGGLE: Sound - """咯咯的声音。 (咯咯笑)""" + """Giggling sound.""" + HAPPY: Sound - """快乐的声音。 (快乐)""" + """Happy sound.""" + HELLO: Sound - """问候声。 (你好)""" + """Greeting sound.""" + MYSTERIOUS: Sound - """神秘的声音 (神秘的)""" + """Mysterious sound.""" + SAD: Sound - """悲伤的声音。 (难过)""" + """Sad sound.""" + SLIDE: Sound - """滑动声。 (滑动)""" + """Sliding sound.""" + SOARING: Sound - """翱翔的声音。 (高昂)""" + """Soaring sound.""" + SPRING: Sound - """春天的声音。 (弹簧)""" + """Spring sound.""" + TWINKLE: Sound - """闪烁的声音。 (闪烁)""" + """Twinkling sound.""" + YAWN: Sound - """打哈欠的声音。 (打哈欠)""" \ No newline at end of file + """Yawning sound.""" diff --git a/lang/zh-cn/typeshed/stdlib/microbit/accelerometer.pyi b/lang/zh-cn/typeshed/stdlib/microbit/accelerometer.pyi index bae4607..bac82c0 100644 --- a/lang/zh-cn/typeshed/stdlib/microbit/accelerometer.pyi +++ b/lang/zh-cn/typeshed/stdlib/microbit/accelerometer.pyi @@ -1,103 +1,115 @@ -"""测量 micro:bit 的加速度并识别手势。 (加速度传感器)""" +"""Measure the acceleration of the micro:bit and recognise gestures. +""" + from typing import Tuple def get_x() -> int: - """获取 ``x`` 轴上的加速度测量值(以 milli-g 为单位)。 + """Get the acceleration measurement in the ``x`` axis in milli-g. -Example: ``accelerometer.get_x()`` + Example: ``accelerometer.get_x()`` -:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" + :return: A positive or negative integer depending on direction in the range +/- 2000mg. + """ ... def get_y() -> int: - """获取 ``y`` 轴上的加速度测量值(以 milli-g 为单位)。 + """Get the acceleration measurement in the ``y`` axis in milli-g. -Example: ``accelerometer.get_y()`` + Example: ``accelerometer.get_y()`` -:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" + :return: A positive or negative integer depending on direction in the range +/- 2000mg. + """ ... def get_z() -> int: - """获取 ``z`` 轴上的加速度测量值(以 milli-g 为单位)。 + """Get the acceleration measurement in the ``z`` axis in milli-g. -Example: ``accelerometer.get_z()`` + Example: ``accelerometer.get_z()`` -:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" + :return: A positive or negative integer depending on direction in the range +/- 2000mg. + """ ... def get_values() -> Tuple[int, int, int]: - """一次获取所有轴上的加速度测量值作为元组。 + """Get the acceleration measurements in all axes at once as a tuple. -Example: ``x, y, z = accelerometer.get_values()`` + Example: ``x, y, z = accelerometer.get_values()`` -:return: a three-element tuple of integers ordered as X, Y, Z, each value a positive or negative integer depending on direction in the range +/- 2000mg""" + :return: a three-element tuple of integers ordered as X, Y, Z, each value a positive or negative integer depending on direction in the range +/- 2000mg + """ ... def get_strength() -> int: - """以正整数形式获取所有轴组合的加速度测量值。这是 X、Y 和 Z 轴的毕达哥拉斯(Pythagorean)和。 (获取强度) + """Get the acceleration measurement of all axes combined, as a positive integer. This is the Pythagorean sum of the X, Y and Z axes. -Example: ``accelerometer.get_strength()`` + Example: ``accelerometer.get_strength()`` -:return: The combined acceleration strength of all the axes, in milli-g.""" + :return: The combined acceleration strength of all the axes, in milli-g. + """ ... def current_gesture() -> str: - """获取当前手势的名称。 + """Get the name of the current gesture. -Example: ``accelerometer.current_gesture()`` + Example: ``accelerometer.current_gesture()`` -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. + 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. -:return: The current gesture""" + :return: The current gesture + """ ... def is_gesture(name: str) -> bool: - """检查命名手势当前是否处于活动状态。 + """Check if the named gesture is currently active. -Example: ``accelerometer.is_gesture('shake')`` + Example: ``accelerometer.is_gesture('shake')`` -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. + 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. -:param name: 手势名称。 -:return: ``True`` if the gesture is active, ``False`` otherwise.""" + :param name: The gesture name. + :return: ``True`` if the gesture is active, ``False`` otherwise. + """ ... def was_gesture(name: str) -> bool: - """检查命名手势自上次调用后是否处于活动状态。 + """Check if the named gesture was active since the last call. -Example: ``accelerometer.was_gesture('shake')`` + Example: ``accelerometer.was_gesture('shake')`` -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. + 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. -:param name: 手势名称。 -:return: ``True`` if the gesture was active since the last call, ``False`` otherwise.""" + :param name: The gesture name. + :return: ``True`` if the gesture was active since the last call, ``False`` otherwise. + """ def get_gestures() -> Tuple[str, ...]: - """返回手势历史的元组。 + """Return a tuple of the gesture history. -Example: ``accelerometer.get_gestures()`` + Example: ``accelerometer.get_gestures()`` -Clears the gesture history before returning. + Clears the gesture history before returning. -Gestures are not updated in the background so there needs to be constant -calls to some accelerometer method to do the gesture detection. Usually -gestures can be detected using a loop with a small :func:`microbit.sleep` delay. + Gestures are not updated in the background so there needs to be constant + calls to some accelerometer method to do the gesture detection. Usually + gestures can be detected using a loop with a small :func:`microbit.sleep` delay. -:return: The history as a tuple, most recent last.""" + :return: The history as a tuple, most recent last. + """ ... def set_range(value: int) -> None: - """将加速度计灵敏度范围(以 g(标准重力)为单位)设置为硬件支持的最接近的值,因此它会取近似值为 ``2``、``4`` 或 ``8`` g。 (设置范围) + """Set the accelerometer sensitivity range, in g (standard gravity), to the closest values supported by the hardware, so it rounds to either ``2``, ``4``, or ``8`` g. -Example: ``accelerometer.set_range(8)`` + Example: ``accelerometer.set_range(8)`` -:param value: 加速度计的新范围,``g`` 中的整数。""" \ No newline at end of file + :param value: New range for the accelerometer, an integer in ``g``. + """ diff --git a/lang/zh-cn/typeshed/stdlib/microbit/audio.pyi b/lang/zh-cn/typeshed/stdlib/microbit/audio.pyi index 3c1d5ea..3b1e327 100644 --- a/lang/zh-cn/typeshed/stdlib/microbit/audio.pyi +++ b/lang/zh-cn/typeshed/stdlib/microbit/audio.pyi @@ -1,124 +1,160 @@ -"""使用 micro:bit 播放声音(导入 ``audio`` 以兼容 V1)。 (音频)""" +"""Play sounds using the micro:bit (import ``audio`` for V1 compatibility). +""" + from ..microbit import MicroBitDigitalPin, Sound, pin0 from typing import ClassVar, Iterable, Union -def play(source: Union[Iterable[AudioFrame], Sound, SoundEffect], wait: bool=True, pin: MicroBitDigitalPin=pin0, return_pin: Union[MicroBitDigitalPin, None]=None) -> None: - """播放内置声音、音效或自定义音频帧。 (播放) +def play( + source: Union[Iterable[AudioFrame], Sound, SoundEffect], + wait: bool = True, + pin: MicroBitDigitalPin = pin0, + return_pin: Union[MicroBitDigitalPin, None] = None, +) -> None: + """Play a built-in sound, sound effect or custom audio frames. -Example: ``audio.play(Sound.GIGGLE)`` + Example: ``audio.play(Sound.GIGGLE)`` -:param source: (来源) 内置的 ``Sound``,例如 ``Sound.GIGGLE``、``SoundEffect`` 或作为 ``AudioFrame`` 的可迭代对象的样本数据。 -:param wait: (等待) 如果 ``wait`` 为 ``True``, 此函数将会阻塞直到声音完成。 -:param pin: (引脚) 可选参数, 用于指定可覆盖默认 ``pin0`` 的输出引脚。 如果不想播放任何声音,可以使用 ``pin=None``。 -:param return_pin: 指定一个差分边缘连接器引脚以连接到外部扬声器而不是接地。对于 **V2** 修订版,这将被忽略。""" + :param source: A built-in ``Sound`` such as ``Sound.GIGGLE``, a ``SoundEffect`` or sample data as an iterable of ``AudioFrame`` objects. + :param wait: If ``wait`` is ``True``, this function will block until the sound is complete. + :param pin: An optional argument to specify the output pin can be used to override the default of ``pin0``. If we do not want any sound to play we can use ``pin=None``. + :param return_pin: Specifies a differential edge connector pin to connect to an external speaker instead of ground. This is ignored for the **V2** revision. + """ def is_playing() -> bool: - """检查是否在播放声音。 + """Check whether a sound is playing. -Example: ``audio.is_playing()`` + Example: ``audio.is_playing()`` -:return: ``True`` if audio is playing, otherwise ``False``.""" + :return: ``True`` if audio is playing, otherwise ``False``.""" ... def stop() -> None: - """停止所有音频播放。 (停止) + """Stop all audio playback. -Example: ``audio.stop()``""" + Example: ``audio.stop()`` + """ ... class SoundEffect: - """一种音效,由一组通过构造函数或属性配置的参数组成。 (音效)""" + """A sound effect, composed by a set of parameters configured via the constructor or attributes.""" + WAVEFORM_SINE: ClassVar[int] - """用于 ``waveform`` 参数的正弦波选项。 (波形正弦)""" + """Sine wave option used for the ``waveform`` parameter.""" + WAVEFORM_SAWTOOTH: ClassVar[int] - """用于 ``waveform`` 参数的锯齿波选项。 (波形锯齿)""" + """Sawtooth wave option used for the ``waveform`` parameter.""" + WAVEFORM_TRIANGLE: ClassVar[int] - """用于 ``waveform`` 参数的三角波选项。 (波形三角)""" + """Triangle wave option used for the ``waveform`` parameter.""" + WAVEFORM_SQUARE: ClassVar[int] - """用于 ``waveform`` 参数的方波选项。 (方波)""" + """Square wave option used for the ``waveform`` parameter.""" + WAVEFORM_NOISE: ClassVar[int] - """用于 ``waveform`` 参数的噪声选项。 (波形噪声)""" + """Noise option used for the ``waveform`` parameter.""" + SHAPE_LINEAR: ClassVar[int] - """用于 ``shape`` 参数的线性插值选项。 (形状线性)""" + """Linear interpolation option used for the ``shape`` parameter.""" + SHAPE_CURVE: ClassVar[int] - """用于 ``shape`` 参数的曲线插值选项。 (形状曲线)""" + """Curve interpolation option used for the ``shape`` parameter.""" + SHAPE_LOG: ClassVar[int] - """用于 ``shape`` 参数的对数插值选项。 (形状日志)""" + """Logarithmic interpolation option used for the ``shape`` parameter.""" + FX_NONE: ClassVar[int] - """没有用于 ``fx`` 参数的效果选项。 (fx 无)""" + """No effect option used for the ``fx`` parameter.""" + FX_TREMOLO: ClassVar[int] - """用于 ``fx`` 参数的音量颤音效果选项。 (fx 音量颤音)""" + """Tremolo effect option used for the ``fx`` parameter.""" + FX_VIBRATO: ClassVar[int] - """用于 ``fx`` 参数的音高颤音效果选项。 (fx 音高颤音)""" + """Vibrato effect option used for the ``fx`` parameter.""" + FX_WARBLE: ClassVar[int] - """用于 ``fx`` 参数的柔和颤音效果选项。 (fx 柔和颤音)""" + """Warble effect option used for the ``fx`` parameter.""" + freq_start: int - """开始频率用 Hertz (Hz) 表示, 是一个 ``0`` 和 ``9999`` 之间的数字 (开始频率)""" + """Start frequency in Hertz (Hz), a number between ``0`` and ``9999``""" + freq_end: int - """结束频率用 Hertz (Hz) 表示, 是一个 ``0`` 和 ``9999`` 之间的数字 (结束频率)""" + """End frequency in Hertz (Hz), a number between ``0`` and ``9999``""" + duration: int - """声音持续时间,以毫秒计, 是一个 ``0`` 和 ``9999`` 之间的数字 (持续)""" - vol_start: int - """开始音量值,是一个 ``0`` 和 ``255`` 之间的数字 (开始音量值)""" - vol_end: int - """结束音量值,是一个 ``0`` 和 ``255`` 之间的数字 (结束音量值)""" - waveform: int - """波形类型,是下列值之一: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (随机生成噪音) (波形)""" - fx: int - """对声音添加效果,下列值之一: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, 或 ``FX_NONE``""" - shape: int - """开始频率和结束频率之间的内插曲线类型,不同波形的频率变化速率不同。 以下值之一: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG`` (形状)""" + """Duration of the sound in milliseconds, a number between ``0`` and ``9999``""" - def __init__(self, freq_start: int=500, freq_end: int=2500, duration: int=500, vol_start: int=255, vol_end: int=0, waveform: int=WAVEFORM_SQUARE, fx: int=FX_NONE, shape: int=SHAPE_LOG): - """创建新的音效。 + vol_start: int + """Start volume value, a number between ``0`` and ``255``""" -Example: ``my_effect = SoundEffect(duration=1000)`` + vol_end: int + """End volume value, a number between ``0`` and ``255``""" -All the parameters are optional, with default values as shown above, and -they can all be modified via attributes of the same name. For example, we -can first create an effect ``my_effect = SoundEffect(duration=1000)``, -and then change its attributes ``my_effect.duration = 500``. + waveform: int + """Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise)""" -:param freq_start: (开始频率) 开始频率用 Hertz (Hz) 表示, 是一个 ``0`` 和 ``9999`` 之间的数字. -:param freq_end: (结束频率) 结束频率用 Hertz (Hz) 表示, 是一个 ``0`` 和 ``9999`` 之间的数字. -:param duration: (持续) 声音持续时间,以毫秒计, 是一个 ``0`` 和 ``9999`` 之间的数字. -:param vol_start: (开始音量值) 开始音量值,是一个 ``0`` 和 ``255`` 之间的数字. -:param vol_end: (结束音量值) 结束音量值,是一个 ``0`` 和 ``255`` 之间的数字. -:param waveform: (波形) 波形类型,是下列值之一: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (随机生成噪音). -:param fx: 对声音添加效果,下列值之一: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, 或 ``FX_NONE``. -:param shape: (形状) 开始频率和结束频率之间的内插曲线类型,不同波形的频率变化速度不同。 以下值之一: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``.""" + fx: int + """Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``""" + shape: int + """The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``""" + + def __init__( + self, + freq_start: int = 500, + freq_end: int = 2500, + duration: int = 500, + vol_start: int = 255, + vol_end: int = 0, + waveform: int = WAVEFORM_SQUARE, + fx: int = FX_NONE, + shape: int = SHAPE_LOG, + ): + """Create a new sound effect. + + Example: ``my_effect = SoundEffect(duration=1000)`` + + All the parameters are optional, with default values as shown above, and + they can all be modified via attributes of the same name. For example, we + can first create an effect ``my_effect = SoundEffect(duration=1000)``, + and then change its attributes ``my_effect.duration = 500``. + + :param freq_start: Start frequency in Hertz (Hz), a number between ``0`` and ``9999``. + :param freq_end: End frequency in Hertz (Hz), a number between ``0`` and ``9999``. + :param duration: Duration of the sound in milliseconds, a number between ``0`` and ``9999``. + :param vol_start: Start volume value, a number between ``0`` and ``255``. + :param vol_end: End volume value, a number between ``0`` and ``255``. + :param waveform: Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise). + :param fx: Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``. + :param shape: The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``. + """ def copy(self) -> SoundEffect: - """创建此 ``SoundEffect`` 的副本。 (复制) + """Create a copy of this ``SoundEffect``. -Example: ``sound_2 = sound_1.copy()`` + Example: ``sound_2 = sound_1.copy()`` -:return: A copy of the SoundEffect.""" + :return: A copy of the SoundEffect. + """ class AudioFrame: - """``AudioFrame`` 对象是 一个包含 32 个样本的列表,每个样本都是一个无符号字节 -(0 到 255 之间的整数)。 (音频帧) + """An ``AudioFrame`` object is a list of 32 samples each of which is a unsigned byte + (whole number between 0 and 255). -It takes just over 4 ms to play a single frame. + It takes just over 4 ms to play a single frame. -Example:: + Example:: - frame = AudioFrame() - for i in range(len(frame)): - frame[i] = 252 - i * 8""" + frame = AudioFrame() + for i in range(len(frame)): + frame[i] = 252 - i * 8 + """ def copyfrom(self, other: AudioFrame) -> None: - """用其他 ``AudioFrame`` 实例中的数据覆盖此 ``AudioFrame`` 中的数据。 (复制) - -Example: ``my_frame.copyfrom(source_frame)`` - -:param other: (其他) 从 ``AudioFrame`` 实例中复制数据。""" - - def __len__(self) -> int: - ... + """Overwrite the data in this ``AudioFrame`` with the data from another ``AudioFrame`` instance. - def __setitem__(self, key: int, value: int) -> None: - ... + Example: ``my_frame.copyfrom(source_frame)`` - def __getitem__(self, key: int) -> int: - ... \ No newline at end of file + :param other: ``AudioFrame`` instance from which to copy the data. + """ + def __len__(self) -> int: ... + def __setitem__(self, key: int, value: int) -> None: ... + def __getitem__(self, key: int) -> int: ... diff --git a/lang/zh-cn/typeshed/stdlib/microbit/compass.pyi b/lang/zh-cn/typeshed/stdlib/microbit/compass.pyi index be71499..c74a47b 100644 --- a/lang/zh-cn/typeshed/stdlib/microbit/compass.pyi +++ b/lang/zh-cn/typeshed/stdlib/microbit/compass.pyi @@ -1,70 +1,78 @@ -"""使用内置罗盘。 (罗盘)""" +"""Use the built-in compass. +""" def calibrate() -> None: - """开始校准过程。 (校准) + """Starts the calibration process. -Example: ``compass.calibrate()`` + Example: ``compass.calibrate()`` -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.""" + 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: - """检查罗盘是否已校准。 + """Check is the compass is calibrated. -Example: ``compass.is_calibrated()`` + Example: ``compass.is_calibrated()`` -:return: ``True`` if the compass has been successfully calibrated, ``False`` otherwise.""" + :return: ``True`` if the compass has been successfully calibrated, ``False`` otherwise. + """ ... def clear_calibration() -> None: - """取消校准,将罗盘恢复到未校准状态。 + """Undoes the calibration, making the compass uncalibrated again. -Example: ``compass.clear_calibration()``""" + Example: ``compass.clear_calibration()`` + """ ... def get_x() -> int: - """获取 ``x`` 轴上的磁场强度。 + """Get the magnetic field strength on the ``x`` axis. -Example: ``compass.get_x()`` + Example: ``compass.get_x()`` -Call ``calibrate`` first or the results will be inaccurate. + Call ``calibrate`` first or the results will be inaccurate. -:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" + :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. + """ ... def get_y() -> int: - """获取 ``y`` 轴上的磁场强度。 + """Get the magnetic field strength on the ``y`` axis. -Example: ``compass.get_y()`` + Example: ``compass.get_y()`` -Call ``calibrate`` first or the results will be inaccurate. + Call ``calibrate`` first or the results will be inaccurate. -:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" + :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. + """ ... def get_z() -> int: - """获取 ``z`` 轴上的磁场强度。 + """Get the magnetic field strength on the ``z`` axis. -Example: ``compass.get_z()`` + Example: ``compass.get_z()`` -Call ``calibrate`` first or the results will be inaccurate. + Call ``calibrate`` first or the results will be inaccurate. -:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" + :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. + """ ... def heading() -> int: - """获取罗盘指向。 + """Get the compass heading. -Example: ``compass.heading()`` + Example: ``compass.heading()`` -:return: An integer in the range from 0 to 360, representing the angle in degrees, clockwise, with north as 0.""" + :return: An integer in the range from 0 to 360, representing the angle in degrees, clockwise, with north as 0. + """ ... def get_field_strength() -> int: - """获取设备周围磁场的强度。 (获取磁场强度) + """Get the magnitude of the magnetic field around the device. -Example: ``compass.get_field_strength()`` + Example: ``compass.get_field_strength()`` -:return: An integer indication of the magnitude of the magnetic field in nano tesla.""" - ... \ No newline at end of file + :return: An integer indication of the magnitude of the magnetic field in nano tesla.""" + ... diff --git a/lang/zh-cn/typeshed/stdlib/microbit/display.pyi b/lang/zh-cn/typeshed/stdlib/microbit/display.pyi index d5490e9..aa4013e 100644 --- a/lang/zh-cn/typeshed/stdlib/microbit/display.pyi +++ b/lang/zh-cn/typeshed/stdlib/microbit/display.pyi @@ -1,92 +1,115 @@ -"""在5×5的 LED 显示屏上显示文字、图像和动画。 (显示)""" +"""Show text, images and animations on the 5×5 LED display. +""" + from ..microbit import Image from typing import Union, overload, Iterable def get_pixel(x: int, y: int) -> int: - """获取第``y``行第``x``列的 LED 亮度。 + """Get the brightness of the LED at column ``x`` and row ``y``. -Example: ``display.get_pixel(0, 0)`` + Example: ``display.get_pixel(0, 0)`` -:param x: 显示屏的列(0..4) -:param y: 显示行 (0..4) -:return: A number between 0 (off) and 9 (bright)""" + :param x: The display column (0..4) + :param y: The display row (0..4) + :return: A number between 0 (off) and 9 (bright) + """ ... def set_pixel(x: int, y: int, value: int) -> None: - """设置在 ``x`` 列和 ``y`` 行的 LED 的亮度。 + """Set the brightness of the LED at column ``x`` and row ``y``. -Example: ``display.set_pixel(0, 0, 9)`` + Example: ``display.set_pixel(0, 0, 9)`` -:param x: 显示屏的列(0..4) -:param y: 显示行 (0..4) -:param value: 在 0 (关闭) 和 9 (亮) 之间的亮度""" + :param x: The display column (0..4) + :param y: The display row (0..4) + :param value: The brightness between 0 (off) and 9 (bright) + """ ... def clear() -> None: - """将所有 LED 的亮度设置为 0(关闭)。 (清除) + """Set the brightness of all LEDs to 0 (off). -Example: ``display.clear()``""" + Example: ``display.clear()`` + """ ... -def show(image: Union[str, float, int, Image, Iterable[Image]], delay: int=400, wait: bool=True, loop: bool=False, clear: bool=False) -> None: - """在 LED 显示屏上显示图像、字母或数字。 (显示) +def show( + image: Union[str, float, int, Image, Iterable[Image]], + delay: int = 400, + wait: bool = True, + loop: bool = False, + clear: bool = False, +) -> None: + """Shows images, letters or digits on the LED display. -Example: ``display.show(Image.HEART)`` + Example: ``display.show(Image.HEART)`` -When ``image`` is an image or a list of images then each image is displayed in turn. -If ``image`` is a string or number, each letter or digit is displayed in turn. + When ``image`` is an image or a list of images then each image is displayed in turn. + If ``image`` is a string or number, each letter or digit is displayed in turn. -:param image: (图像) 要显示的一个字符串、数字、图像或图像列表。 -:param delay: (延迟) 每个字母、数字或图像之间显示的间隔时间为 ``delay`` 毫秒。 -:param wait: (等待) 如果 ``wait`` 为 ``True``,此函数将阻塞直到动画完成,否则动画将在后台发生。 -:param loop: 如果 ``loop`` 为 ``True``, 动画将永远重复。 -:param clear: (清除) 如果 ``clear`` 是 ``True``, 则显示将在序列完成后被清除。 + :param image: A string, number, image or list of images to show. + :param delay: Each letter, digit or image is shown with ``delay`` milliseconds between them. + :param wait: If ``wait`` is ``True``, this function will block until the animation is finished, otherwise the animation will happen in the background. + :param loop: If ``loop`` is ``True``, the animation will repeat forever. + :param clear: If ``clear`` is ``True``, the display will be cleared after the sequence has finished. -The ``wait``, ``loop`` and ``clear`` arguments must be specified using their keyword.""" + The ``wait``, ``loop`` and ``clear`` arguments must be specified using their keyword. + """ ... -def scroll(text: Union[str, float, int], delay: int=150, wait: bool=True, loop: bool=False, monospace: bool=False) -> None: - """在 LED 显示屏上滚动一个数字或文本。 (滚动) - -Example: ``display.scroll('micro:bit')`` - -:param text: (文本) 要滚动的字符串。如果 ``text`` 是整数或浮点数,则首先使用 ``str()`` 将其转换为字符串。 -:param delay: (延迟) ``delay`` 参数控制文本滚动的速度。 -:param wait: (等待) 如果 ``wait`` 为 ``True``,此函数将阻塞直到动画完成,否则动画将发生在后台。 -:param loop: 如果 ``loop`` 为 ``True``, 动画将永远重复。 -:param monospace: (等宽) 如果 ``monospace`` 为 ``True``,则字符的宽度都将占用 5 个像素列,否则在滚动时每个字符之间将恰好有 1 个空白像素列。 - -The ``wait``, ``loop`` and ``monospace`` arguments must be specified -using their keyword.""" +def scroll( + text: Union[str, float, int], + delay: int = 150, + wait: bool = True, + loop: bool = False, + monospace: bool = False, +) -> None: + """Scrolls a number or text on the LED display. + + Example: ``display.scroll('micro:bit')`` + + :param text: The string to scroll. If ``text`` is an integer or float it is first converted to a string using ``str()``. + :param delay: The ``delay`` parameter controls how fast the text is scrolling. + :param wait: If ``wait`` is ``True``, this function will block until the animation is finished, otherwise the animation will happen in the background. + :param loop: If ``loop`` is ``True``, the animation will repeat forever. + :param monospace: 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. + + The ``wait``, ``loop`` and ``monospace`` arguments must be specified + using their keyword. + """ ... def on() -> None: - """打开 LED 显示屏。 (打开) + """Turn on the LED display. -Example: ``display.on()``""" + Example: ``display.on()`` + """ ... def off() -> None: - """关闭 LED 显示屏(禁用显示屏可让您将 GPIO 引脚重新用于其他用途)。 (关闭) + """Turn off the LED display (disabling the display allows you to re-use the GPIO pins for other purposes). -Example: ``display.off()``""" + Example: ``display.off()`` + """ ... def is_on() -> bool: - """检查 LED 显示屏是否启用。 + """Check whether the LED display is enabled. -Example: ``display.is_on()`` + Example: ``display.is_on()`` -:return: ``True`` if the display is on, otherwise returns ``False``.""" + :return: ``True`` if the display is on, otherwise returns ``False``. + """ ... def read_light_level() -> int: - """读取亮度。 + """Read the light level. -Example: ``display.read_light_level()`` + Example: ``display.read_light_level()`` -Uses the display's LEDs in reverse-bias mode to sense the amount of light -falling on the display. + Uses the display's LEDs in reverse-bias mode to sense the amount of light + falling on the display. -:return: An integer between 0 and 255 representing the light level, with larger meaning more light.""" - ... \ No newline at end of file + :return: An integer between 0 and 255 representing the light level, with larger meaning more light. + """ + ... diff --git a/lang/zh-cn/typeshed/stdlib/microbit/i2c.pyi b/lang/zh-cn/typeshed/stdlib/microbit/i2c.pyi index 5ad7530..df26efa 100644 --- a/lang/zh-cn/typeshed/stdlib/microbit/i2c.pyi +++ b/lang/zh-cn/typeshed/stdlib/microbit/i2c.pyi @@ -1,49 +1,57 @@ -"""使用 I²C 总线协议与设备通信。 (i2c总线协议)""" +"""Communicate with devices using the I²C bus protocol. +""" + from _typeshed import ReadableBuffer from ..microbit import MicroBitDigitalPin, pin19, pin20 from typing import List -def init(freq: int=100000, sda: MicroBitDigitalPin=pin20, scl: MicroBitDigitalPin=pin19) -> None: - """重新初始化外设。 +def init( + freq: int = 100000, sda: MicroBitDigitalPin = pin20, scl: MicroBitDigitalPin = pin19 +) -> None: + """Re-initialize a peripheral. -Example: ``i2c.init()`` + Example: ``i2c.init()`` -:param freq: 时钟频率 -:param sda: (SDA引脚) ``sda`` 引脚(默认 20) -:param scl: (SCL引脚) ``scl`` 引脚(默认 19) + :param freq: clock frequency + :param sda: ``sda`` pin (default 20) + :param scl: ``scl`` pin (default 19) -On a micro:bit V1 board, changing the I²C pins from defaults will make -the accelerometer and compass stop working, as they are connected -internally to those pins. This warning does not apply to the **V2** -revision of the micro:bit as this has `separate I²C lines `_ -for the motion sensors and the edge connector.""" + On a micro:bit V1 board, changing the I²C pins from defaults will make + the accelerometer and compass stop working, as they are connected + internally to those pins. This warning does not apply to the **V2** + revision of the micro:bit as this has `separate I²C lines `_ + for the motion sensors and the edge connector. + """ ... def scan() -> List[int]: - """扫描总线以查找设备。 (扫描) + """Scan the bus for devices. -Example: ``i2c.scan()`` + Example: ``i2c.scan()`` -:return: A list of 7-bit addresses corresponding to those devices that responded to the scan.""" + :return: A list of 7-bit addresses corresponding to those devices that responded to the scan. + """ ... -def read(addr: int, n: int, repeat: bool=False) -> bytes: - """从设备读取字节. (读取) +def read(addr: int, n: int, repeat: bool = False) -> bytes: + """Read bytes from a device. -Example: ``i2c.read(0x50, 64)`` + Example: ``i2c.read(0x50, 64)`` -:param addr: (地址) 设备的 7 位地址 -:param n: 要读取的字节数 -:param repeat: 如果为 ``True``,则不发送停止位 -:return: The bytes read""" + :param addr: The 7-bit address of the device + :param n: The number of bytes to read + :param repeat: If ``True``, no stop bit will be sent + :return: The bytes read + """ ... -def write(addr: int, buf: ReadableBuffer, repeat: bool=False) -> None: - """将字节写入设备。 (写入) +def write(addr: int, buf: ReadableBuffer, repeat: bool = False) -> None: + """Write bytes to a device. -Example: ``i2c.write(0x50, bytes([1, 2, 3]))`` + Example: ``i2c.write(0x50, bytes([1, 2, 3]))`` -:param addr: (地址) 设备的 7 位地址 -:param buf: (缓冲区) 包含要写入的字节的缓冲区 -:param repeat: 如果为 ``True``,则不发送停止位""" - ... \ No newline at end of file + :param addr: The 7-bit address of the device + :param buf: A buffer containing the bytes to write + :param repeat: If ``True``, no stop bit will be sent + """ + ... diff --git a/lang/zh-cn/typeshed/stdlib/microbit/microphone.pyi b/lang/zh-cn/typeshed/stdlib/microbit/microphone.pyi index 44db995..68e8f3a 100644 --- a/lang/zh-cn/typeshed/stdlib/microbit/microphone.pyi +++ b/lang/zh-cn/typeshed/stdlib/microbit/microphone.pyi @@ -1,62 +1,70 @@ -"""使用内置麦克风响应声音(仅限 V2)。 (麦克风)""" +"""Respond to sound using the built-in microphone (V2 only). +""" + from typing import Optional, Tuple from ..microbit import SoundEvent def current_event() -> Optional[SoundEvent]: - """获取最后录制的声音事件 + """Get the last recorded sound event -Example: ``microphone.current_event()`` + Example: ``microphone.current_event()`` -:return: The event, ``SoundEvent('loud')`` or ``SoundEvent('quiet')``.""" + :return: The event, ``SoundEvent('loud')`` or ``SoundEvent('quiet')``. + """ ... def was_event(event: SoundEvent) -> bool: - """检查自上次通话后是否至少听到一次声音。 (曾经是事件) + """Check if a sound was heard at least once since the last call. -Example: ``microphone.was_event(SoundEvent.LOUD)`` + Example: ``microphone.was_event(SoundEvent.LOUD)`` -This call clears the sound history before returning. + This call clears the sound history before returning. -:param event: (事件) 要检查的事件,例如 ``SoundEvent.LOUD`` 或 ``SoundEvent.QUIET`` -:return: ``True`` if sound was heard at least once since the last call, otherwise ``False``.""" + :param event: The event to check for, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET`` + :return: ``True`` if sound was heard at least once since the last call, otherwise ``False``. + """ ... def is_event(event: SoundEvent) -> bool: - """检查最近检测到的声音事件。 (是事件) + """Check the most recent sound event detected. -Example: ``microphone.is_event(SoundEvent.LOUD)`` + Example: ``microphone.is_event(SoundEvent.LOUD)`` -This call does not clear the sound event history. + This call does not clear the sound event history. -:param event: (事件) 要检查的事件,例如 ``SoundEvent.LOUD`` 或 ``SoundEvent.QUIET`` -:return: ``True`` if sound was the most recent heard, ``False`` otherwise.""" + :param event: The event to check for, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET`` + :return: ``True`` if sound was the most recent heard, ``False`` otherwise. + """ ... def get_events() -> Tuple[SoundEvent, ...]: - """以元组的形式获取声音事件历史。 + """Get the sound event history as a tuple. -Example: ``microphone.get_events()`` + Example: ``microphone.get_events()`` -This call clears the sound history before returning. + This call clears the sound history before returning. -:return: A tuple of the event history with the most recent event last.""" + :return: A tuple of the event history with the most recent event last. + """ ... def set_threshold(event: SoundEvent, value: int) -> None: - """设置声音事件的阈值。 + """Set the threshold for a sound event. -Example: ``microphone.set_threshold(SoundEvent.LOUD, 250)`` + Example: ``microphone.set_threshold(SoundEvent.LOUD, 250)`` -A high threshold means the event will only trigger if the sound is very loud (>= 250 in the example). + A high threshold means the event will only trigger if the sound is very loud (>= 250 in the example). -:param event: (事件) 声音事件,如``SoundEvent.LOUD``或``SoundEvent.QUIET``。 -:param value: 范围为0到255的阈值水平。""" + :param event: A sound event, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET``. + :param value: The threshold level in the range 0-255. + """ ... def sound_level() -> int: - """获取声压级。 (音量) + """Get the sound pressure level. -Example: ``microphone.sound_level()`` + Example: ``microphone.sound_level()`` -:return: A representation of the sound pressure level in the range 0 to 255.""" - ... \ No newline at end of file + :return: A representation of the sound pressure level in the range 0 to 255. + """ + ... diff --git a/lang/zh-cn/typeshed/stdlib/microbit/speaker.pyi b/lang/zh-cn/typeshed/stdlib/microbit/speaker.pyi index cdc0992..5a74a4d 100644 --- a/lang/zh-cn/typeshed/stdlib/microbit/speaker.pyi +++ b/lang/zh-cn/typeshed/stdlib/microbit/speaker.pyi @@ -1,15 +1,18 @@ -"""控制内置扬声器(仅限 V2)。 (扬声器\u200b\u200b\u200b\u200b)""" +"""Control the built-in speaker (V2 only). +""" def off() -> None: - """关闭扬声器\u200b\u200b\u200b\u200b。 (关闭) + """Turn the speaker off. -Example: ``speaker.off()`` + Example: ``speaker.off()`` -This does not disable sound output to an edge connector pin.""" + This does not disable sound output to an edge connector pin. + """ ... def on() -> None: - """打开扬声器\u200b\u200b\u200b\u200b。 (打开) + """Turn the speaker on. -Example: ``speaker.on()``""" - ... \ No newline at end of file + Example: ``speaker.on()`` + """ + ... diff --git a/lang/zh-cn/typeshed/stdlib/microbit/spi.pyi b/lang/zh-cn/typeshed/stdlib/microbit/spi.pyi index bbca0c1..09c4046 100644 --- a/lang/zh-cn/typeshed/stdlib/microbit/spi.pyi +++ b/lang/zh-cn/typeshed/stdlib/microbit/spi.pyi @@ -1,47 +1,60 @@ -"""通过串行外设接口(SPI)总线与设备通信。 (串行外围接口(SPI))""" +"""Communicate with devices using the serial peripheral interface (SPI) bus. +""" + from _typeshed import ReadableBuffer, WriteableBuffer from ..microbit import pin13, pin14, pin15, MicroBitDigitalPin -def init(baudrate: int=1000000, bits: int=8, mode: int=0, sclk: MicroBitDigitalPin=pin13, mosi: MicroBitDigitalPin=pin15, miso: MicroBitDigitalPin=pin14) -> None: - """初始化串行外设接口(SPI )通信。 - -Example: ``spi.init()`` - -For correct communication, the parameters have to be the same on both communicating devices. - -:param baudrate: (波特率) 通信速度。 -:param bits: (位) 每次传输的宽度(单位:bit)。目前只支持 ``bits=8``,但是未来可能支持其他宽度。 -:param mode: (模式) 决定时钟极性和相位的组合——“参见在线表格”。 -:param sclk: (SCLK) sclk 引脚(默认 13) -:param mosi: (MOSI) mosi 引脚(默认 15) -:param miso: (MISO) MISO引脚(默认值14)""" +def init( + baudrate: int = 1000000, + bits: int = 8, + mode: int = 0, + sclk: MicroBitDigitalPin = pin13, + mosi: MicroBitDigitalPin = pin15, + miso: MicroBitDigitalPin = pin14, +) -> None: + """Initialize SPI communication. + + Example: ``spi.init()`` + + For correct communication, the parameters have to be the same on both communicating devices. + + :param baudrate: The speed of communication. + :param bits: The width in bits of each transfer. Currently only ``bits=8`` is supported. However, this may change in the future. + :param mode: Determines the combination of clock polarity and phase - `see online table `_. + :param sclk: sclk pin (default 13) + :param mosi: mosi pin (default 15) + :param miso: miso pin (default 14) + """ ... -def read(nbytes: int, out: int=0) -> bytes: - """读取字节数。 (读取) +def read(nbytes: int, out: int = 0) -> bytes: + """Read at most ``nbytes`` while continuously writing the single byte given by ``out``. -Example: ``spi.read(64)`` + Example: ``spi.read(64)`` -:param nbytes: (字节数) 要读取的最大字节数。 -:param out: (写出) The byte value to write (default 0). -:return: The bytes read.""" + :param nbytes: Maximum number of bytes to read. + :param out: The byte value to write (default 0). + :return: The bytes read. + """ ... def write(buffer: ReadableBuffer) -> None: - """将字节写入总线。 (写入) + """Write bytes to the bus. -Example: ``spi.write(bytes([1, 2, 3]))`` + Example: ``spi.write(bytes([1, 2, 3]))`` -:param buffer: (缓冲区) 读取数据的缓冲区。""" + :param buffer: A buffer to read data from. + """ ... def write_readinto(out: WriteableBuffer, in_: ReadableBuffer) -> None: - """将 ``out`` 缓冲区写入总线,并将任何响应读入 ``in_`` 缓冲区。 (写并读入) + """Write the ``out`` buffer to the bus and read any response into the ``in_`` buffer. -Example: ``spi.write_readinto(out_buffer, in_buffer)`` + Example: ``spi.write_readinto(out_buffer, in_buffer)`` -The length of the buffers should be the same. The buffers can be the same object. + The length of the buffers should be the same. The buffers can be the same object. -:param out: (写出) 写入任何响应的缓冲区。 -:param in_: (读入) 读取数据的缓冲区。""" - ... \ No newline at end of file + :param out: The buffer to write any response to. + :param in_: The buffer to read data from. + """ + ... diff --git a/lang/zh-cn/typeshed/stdlib/microbit/uart.pyi b/lang/zh-cn/typeshed/stdlib/microbit/uart.pyi index 63a5bed..2ab650f 100644 --- a/lang/zh-cn/typeshed/stdlib/microbit/uart.pyi +++ b/lang/zh-cn/typeshed/stdlib/microbit/uart.pyi @@ -1,79 +1,96 @@ -"""使用串行接口与设备通信。 (通用异步收发器(UART))""" +"""Communicate with a device using a serial interface. +""" + from _typeshed import WriteableBuffer from ..microbit import MicroBitDigitalPin from typing import Optional, Union -ODD: int -"""奇校验 (奇数)""" -EVEN: int -"""偶校验 (偶数)""" - -def init(baudrate: int=9600, bits: int=8, parity: Optional[int]=None, stop: int=1, tx: Optional[MicroBitDigitalPin]=None, rx: Optional[MicroBitDigitalPin]=None) -> None: - """初始化串行通信。 - -Example: ``uart.init(115200, tx=pin0, rx=pin1)`` -:param baudrate: (波特率) 通信速度。 -:param bits: (位数) 正在传输的字节大小。micro:bit 仅支持 8 字节。 -:param parity: (奇偶校验) 如何检查奇偶性,``None``、``uart.ODD`` 或 ``uart.EVEN``。 -:param stop: (停止) 停止位的数量,对于 micro:bit,必须为 1。 -:param tx: (发送引脚) 传输引脚。 -:param rx: (接收引脚) 接收引脚。 - -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. +ODD: int +"""Odd parity""" -For more details see `the online documentation `_.""" +EVEN: int +"""Even parity""" + +def init( + baudrate: int = 9600, + bits: int = 8, + parity: Optional[int] = None, + stop: int = 1, + tx: Optional[MicroBitDigitalPin] = None, + rx: Optional[MicroBitDigitalPin] = None, +) -> None: + """Initialize serial communication. + + Example: ``uart.init(115200, tx=pin0, rx=pin1)`` + + :param baudrate: The speed of communication. + :param bits: The size of bytes being transmitted. micro:bit only supports 8. + :param parity: How parity is checked, ``None``, ``uart.ODD`` or ``uart.EVEN``. + :param stop: The number of stop bits, has to be 1 for micro:bit. + :param tx: Transmitting pin. + :param rx: Receiving pin. + + 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. + + For more details see `the online documentation `_. + """ ... def any() -> bool: - """检查是否有任何数据正在等待。 (任何) + """Check if any data is waiting. -Example: ``uart.any()`` + Example: ``uart.any()`` -:return: ``True`` if any data is waiting, else ``False``.""" + :return: ``True`` if any data is waiting, else ``False``. + """ ... -def read(nbytes: Optional[int]=None) -> Optional[bytes]: - """读取字节。 (读取) +def read(nbytes: Optional[int] = None) -> Optional[bytes]: + """Read bytes. -Example: ``uart.read()`` + Example: ``uart.read()`` -:param nbytes: (字节数) 如果指定了 ``nbytes``,则最多读取那么多字节,否则读取尽可能多的字节 -:return: A bytes object or ``None`` on timeout""" + :param nbytes: If ``nbytes`` is specified then read at most that many bytes, otherwise read as many bytes as possible + :return: A bytes object or ``None`` on timeout + """ ... -def readinto(buf: WriteableBuffer, nbytes: Optional[int]=None) -> Optional[int]: - """读取字节到 ``buf``。 (读入) +def readinto(buf: WriteableBuffer, nbytes: Optional[int] = None) -> Optional[int]: + """Read bytes into the ``buf``. -Example: ``uart.readinto(input_buffer)`` + Example: ``uart.readinto(input_buffer)`` -:param buf: (缓冲区) 要写入的缓存。 -:param nbytes: (字节数) 如果指定了 ``nbytes``,则最多读取那么多字节,否则读取 ``len(buf)`` 个字节。 -:return: number of bytes read and stored into ``buf`` or ``None`` on timeout.""" + :param buf: The buffer to write to. + :param nbytes: If ``nbytes`` is specified then read at most that many bytes, otherwise read ``len(buf)`` bytes. + :return: number of bytes read and stored into ``buf`` or ``None`` on timeout. + """ ... def readline() -> Optional[bytes]: - """读取一行,以换行符结尾。 (读取一行) + """Read a line, ending in a newline character. -Example: ``uart.readline()`` + Example: ``uart.readline()`` -:return: The line read or ``None`` on timeout. The newline character is included in the returned bytes.""" + :return: The line read or ``None`` on timeout. The newline character is included in the returned bytes. + """ ... def write(buf: Union[bytes, str]) -> Optional[int]: - """将缓冲区写入总线。 (写入) + """Write a buffer to the bus. -Example: ``uart.write('hello world')`` + Example: ``uart.write('hello world')`` -:param buf: (缓冲区) 一个字节对象或一个字符串。 -:return: The number of bytes written, or ``None`` on timeout. + :param buf: A bytes object or a string. + :return: The number of bytes written, or ``None`` on timeout. -Examples:: + Examples:: - uart.write('hello world') - uart.write(b'hello world') - uart.write(bytes([1, 2, 3]))""" - ... \ No newline at end of file + uart.write('hello world') + uart.write(b'hello world') + uart.write(bytes([1, 2, 3])) + """ + ... diff --git a/lang/zh-cn/typeshed/stdlib/micropython.pyi b/lang/zh-cn/typeshed/stdlib/micropython.pyi index 8d63617..7a6079f 100644 --- a/lang/zh-cn/typeshed/stdlib/micropython.pyi +++ b/lang/zh-cn/typeshed/stdlib/micropython.pyi @@ -1,131 +1,144 @@ -"""MicroPython 内设。 (MicroPython)""" +"""MicroPython internals.""" + from typing import Any, TypeVar, overload -_T = TypeVar('_T') + +_T = TypeVar("_T") def const(expr: _T) -> _T: - """用于声明表达式是一个常量,以便编译器可以优化它。 (常数) + """Used to declare that the expression is a constant so that the compiler can + optimise it. -The use of this function should be as follows:: + The use of this function should be as follows:: - from micropython import const - CONST_X = const(123) - CONST_Y = const(2 * CONST_X + 1) + from micropython import const + CONST_X = const(123) + CONST_Y = const(2 * CONST_X + 1) -Constants declared this way are still accessible as global variables from -outside the module they are declared in. On the other hand, if a constant -begins with an underscore then it is hidden, it is not available as a -global variable, and does not take up any memory during execution. + Constants declared this way are still accessible as global variables from + outside the module they are declared in. On the other hand, if a constant + begins with an underscore then it is hidden, it is not available as a + global variable, and does not take up any memory during execution. -:param expr: (表达式) 一个常量表达式。""" + :param expr: A constant expression. + """ ... @overload def opt_level() -> int: - """获取脚本编译的当前优化级别。 (优化级别) + """Get the current optimisation level for the compilation of scripts. -Example: ``micropython.opt_level()`` + Example: ``micropython.opt_level()`` -The optimisation level controls the following compilation features: + The optimisation level controls the following compilation features: -- Assertions: at level 0 assertion statements are enabled and compiled - into the bytecode; at levels 1 and higher assertions are not compiled. + - Assertions: at level 0 assertion statements are enabled and compiled + into the bytecode; at levels 1 and higher assertions are not compiled. -- Built-in ``__debug__`` variable: at level 0 this variable expands to - True; at levels 1 and higher it expands to False. + - Built-in ``__debug__`` variable: at level 0 this variable expands to + True; at levels 1 and higher it expands to False. -- Source-code line numbers: at levels 0, 1 and 2 source-code line number - are stored along with the bytecode so that exceptions can report the - line number they occurred at; at levels 3 and higher line numbers are - not stored. + - Source-code line numbers: at levels 0, 1 and 2 source-code line number + are stored along with the bytecode so that exceptions can report the + line number they occurred at; at levels 3 and higher line numbers are + not stored. -:return: An integer representing the current level.""" + :return: An integer representing the current level. + """ ... @overload def opt_level(level: int) -> None: - """设置后续脚本编译的优化级别。 (优化级别) + """Sets the optimisation level for subsequent compilation of scripts. -Example: ``micropython.opt_level(1)`` + Example: ``micropython.opt_level(1)`` -The optimisation level controls the following compilation features: + The optimisation level controls the following compilation features: -- Assertions: at level 0 assertion statements are enabled and compiled - into the bytecode; at levels 1 and higher assertions are not compiled. + - Assertions: at level 0 assertion statements are enabled and compiled + into the bytecode; at levels 1 and higher assertions are not compiled. -- Built-in ``__debug__`` variable: at level 0 this variable expands to - True; at levels 1 and higher it expands to False. + - Built-in ``__debug__`` variable: at level 0 this variable expands to + True; at levels 1 and higher it expands to False. -- Source-code line numbers: at levels 0, 1 and 2 source-code line number - are stored along with the bytecode so that exceptions can report the - line number they occurred at; at levels 3 and higher line numbers are - not stored. + - Source-code line numbers: at levels 0, 1 and 2 source-code line number + are stored along with the bytecode so that exceptions can report the + line number they occurred at; at levels 3 and higher line numbers are + not stored. -The default optimisation level is usually level 0. + The default optimisation level is usually level 0. -:param level: (级别) 整数优化级别。""" + :param level: An integer optimisation level. + """ ... -def mem_info(verbose: Any=None) -> None: - """打印与当前使用内存相关的信息。 +def mem_info(verbose: Any = None) -> None: + """Print information about currently used memory. -Example: ``micropython.mem_info()`` + Example: ``micropython.mem_info()`` -:param verbose: (详细) 如果给出 ``verbose`` 参数,则打印额外信息。""" + :param verbose: If the ``verbose`` argument is given then extra information is printed. + """ ... -def qstr_info(verbose: Any=None) -> None: - """打印与当前驻留字符串相关的信息。 (字符串信息) +def qstr_info(verbose: Any = None) -> None: + """Print information about currently interned strings. -Example: ``micropython.qstr_info()`` + Example: ``micropython.qstr_info()`` -:param verbose: (详细) 如果给出 ``verbose`` 参数,则打印额外信息。 + :param verbose: If the ``verbose`` argument is given then extra information is printed. -The information that is printed is implementation dependent, but currently -includes the number of interned strings and the amount of RAM they use. In -verbose mode it prints out the names of all RAM-interned strings.""" + The information that is printed is implementation dependent, but currently + includes the number of interned strings and the amount of RAM they use. In + verbose mode it prints out the names of all RAM-interned strings. + """ ... def stack_use() -> int: - """返回一个整数,来表示当前正在使用的堆栈数量。 (堆栈使用) + """Return an integer representing the current amount of stack that is being + used. -Example: ``micropython.stack_use()`` + Example: ``micropython.stack_use()`` -The absolute value of this is not particularly useful, rather it -should be used to compute differences in stack usage at different points. + The absolute value of this is not particularly useful, rather it + should be used to compute differences in stack usage at different points. -:return: An integer representing current stack use.""" + :return: An integer representing current stack use. + """ ... def heap_lock() -> None: - """锁定堆。 (锁住堆) + """Lock the heap. -Example: ``micropython.heap_lock()`` + Example: ``micropython.heap_lock()`` -When locked no memory allocation can occur and a ``MemoryError`` will be -raised if any heap allocation is attempted.""" + When locked no memory allocation can occur and a ``MemoryError`` will be + raised if any heap allocation is attempted. + """ ... def heap_unlock() -> None: - """解锁堆。 (解锁堆) + """Unlock the heap. -Example: ``micropython.heap_unlock()`` + Example: ``micropython.heap_unlock()`` -When locked no memory allocation can occur and a ``MemoryError`` will be -raised if any heap allocation is attempted.""" + When locked no memory allocation can occur and a ``MemoryError`` will be + raised if any heap allocation is attempted. + """ ... def kbd_intr(chr: int) -> None: - """设置将引发``KeyboardInterrupt``异常的字符。 (键盘中断) + """Set the character that will raise a ``KeyboardInterrupt`` exception. -Example: ``micropython.kbd_intr(-1)`` + Example: ``micropython.kbd_intr(-1)`` -:param chr: (字符) 用于提高中断的字符代码;或者-1,用于禁止捕获 Ctrl-C。 + :param chr: Character code to raise the interrupt or -1 to disable capture of Ctrl-C. -By default this is set to 3 during script execution, corresponding to Ctrl-C. -Passing -1 to this function will disable capture of Ctrl-C, and passing 3 -will restore it. + By default this is set to 3 during script execution, corresponding to Ctrl-C. + Passing -1 to this function will disable capture of Ctrl-C, and passing 3 + will restore it. -This function can be used to prevent the capturing of Ctrl-C on the -incoming stream of characters that is usually used for the REPL, in case -that stream is used for other purposes.""" - ... \ No newline at end of file + This function can be used to prevent the capturing of Ctrl-C on the + incoming stream of characters that is usually used for the REPL, in case + that stream is used for other purposes. + """ + ... diff --git a/lang/zh-cn/typeshed/stdlib/music.pyi b/lang/zh-cn/typeshed/stdlib/music.pyi index 061c3af..5f4778b 100644 --- a/lang/zh-cn/typeshed/stdlib/music.pyi +++ b/lang/zh-cn/typeshed/stdlib/music.pyi @@ -1,128 +1,167 @@ -"""创建并播放旋律。 (音乐)""" +"""Create and play melodies. +""" from typing import Optional, Tuple, Union, List + from .microbit import MicroBitDigitalPin, pin0 + DADADADUM: Tuple[str, ...] -"""旋律:《贝多芬 C 小调第五交响曲》开场曲。""" +"""Melody: the opening to Beethoven’s 5th Symphony in C minor.""" + ENTERTAINER: Tuple[str, ...] -"""旋律:斯科特·乔普林的拉格泰姆经典“演艺人”的开场片段。 (演艺人)""" +"""Melody: the opening fragment of Scott Joplin’s Ragtime classic “The Entertainer”.""" + PRELUDE: Tuple[str, ...] -"""旋律:约翰·塞巴斯蒂安·巴赫48首前奏曲和赋格曲中 C 大调第一前奏曲的开场。 (序幕)""" +"""Melody: the opening of the first Prelude in C Major of J.S.Bach’s 48 Preludes and Fugues.""" + ODE: Tuple[str, ...] -"""旋律:贝多芬 D 小调第九交响曲中的“欢乐颂”主题。 (欢乐颂)""" +"""Melody: the “Ode to Joy” theme from Beethoven’s 9th Symphony in D minor.""" + NYAN: Tuple[str, ...] -"""旋律:彩虹猫主题 (http://www.nyan.cat/)。 (彩虹猫) +"""Melody: the Nyan Cat theme (http://www.nyan.cat/). The composer is unknown. This is fair use for educational porpoises (as they say in New York).""" + RINGTONE: Tuple[str, ...] -"""旋律:听起来像手机铃声的乐曲。 (铃声) +"""Melody: something that sounds like a mobile phone ringtone. To be used to indicate an incoming message. """ + FUNK: Tuple[str, ...] -"""旋律:一曲为特工和犯罪主谋制作的 funky bass。 (朋克)""" +"""Melody: a funky bass line for secret agents and criminal masterminds.""" + BLUES: Tuple[str, ...] -"""旋律:布吉伍吉 12 小节布鲁斯 walking bass。 (布鲁斯)""" +"""Melody: a boogie-woogie 12-bar blues walking bass.""" + BIRTHDAY: Tuple[str, ...] -"""旋律:“祝你生日快乐……” (生日) +"""Melody: “Happy Birthday to You…” For copyright status see: http://www.bbc.co.uk/news/world-us-canada-34332853 """ + WEDDING: Tuple[str, ...] -"""旋律:瓦格纳歌剧《罗恩格林》中的新娘合唱。 (婚礼)""" +"""Melody: the bridal chorus from Wagner’s opera “Lohengrin”.""" + FUNERAL: Tuple[str, ...] -"""旋律:“葬礼进行曲”,也被称为弗雷德里克肖邦的 B♭ 小调第二钢琴奏鸣曲,Op. 35。 (哀乐)""" +"""Melody: the “funeral march” otherwise known as Frédéric Chopin’s Piano Sonata No. 2 in B♭ minor, Op. 35.""" + PUNCHLINE: Tuple[str, ...] -"""旋律:一个有趣的片段,表示开了一个玩笑。 (笑点)""" +"""Melody: a fun fragment that signifies a joke has been made.""" + PYTHON: Tuple[str, ...] -"""旋律:约翰·菲利普·苏萨的进行曲《自由钟》,即《巨蟒剧团之飞翔的马戏团》的主题曲(Python 编程语言以此命名)。 (Python)""" +"""Melody: John Philip Sousa’s march “Liberty Bell” aka, the theme for “Monty Python’s Flying Circus” (after which the Python programming language is named).""" + BADDY: Tuple[str, ...] -"""旋律:默片时代反面角色的入场曲。 (反面角色)""" +"""Melody: silent movie era entrance of a baddy.""" + CHASE: Tuple[str, ...] -"""旋律:无声电影时代的追逐场景。 (追逐)""" +"""Melody: silent movie era chase scene.""" + BA_DING: Tuple[str, ...] -"""旋律:表示某事发生的简短信号。""" +"""Melody: a short signal to indicate something has happened.""" + WAWAWAWAA: Tuple[str, ...] -"""旋律:非常悲伤的长号。""" +"""Melody: a very sad trombone.""" + JUMP_UP: Tuple[str, ...] -"""旋律:用于游戏中,表示向上运动。 (向上跳)""" +"""Melody: for use in a game, indicating upward movement.""" + JUMP_DOWN: Tuple[str, ...] -"""旋律:用于游戏中,表示向下运动。 (向下跳)""" +"""Melody: for use in a game, indicating downward movement.""" + POWER_UP: Tuple[str, ...] -"""旋律:表示解锁成就的号角。 (能力增强)""" +"""Melody: a fanfare to indicate an achievement unlocked.""" + POWER_DOWN: Tuple[str, ...] -"""旋律:表示失去成就的悲伤号角。 (能力减弱)""" +"""Melody: a sad fanfare to indicate an achievement lost.""" -def set_tempo(ticks: int=4, bpm: int=120) -> None: - """设置播放的大致节奏。 (设置节奏) +def set_tempo(ticks: int = 4, bpm: int = 120) -> None: + """Sets the approximate tempo for playback. -Example: ``music.set_tempo(bpm=120)`` + Example: ``music.set_tempo(bpm=120)`` -:param ticks: (刻度) 构成一个节拍的刻度数。 -:param bpm: (每分钟节拍数) 一个整数,确定每分钟有多少拍。 + :param ticks: The number of ticks constituting a beat. + :param bpm: An integer determining how many beats per minute. -Suggested default values allow the following useful behaviour: + Suggested default values allow the following useful behaviour: -- music.set_tempo() – reset the tempo to default of ticks = 4, bpm = 120 -- music.set_tempo(ticks=8) – change the “definition” of a beat -- music.set_tempo(bpm=180) – just change the tempo + - music.set_tempo() – reset the tempo to default of ticks = 4, bpm = 120 + - music.set_tempo(ticks=8) – change the “definition” of a beat + - music.set_tempo(bpm=180) – just change the tempo -To work out the length of a tick in milliseconds is very simple arithmetic: -60000/bpm/ticks_per_beat. For the default values that’s -60000/120/4 = 125 milliseconds or 1 beat = 500 milliseconds.""" + To work out the length of a tick in milliseconds is very simple arithmetic: + 60000/bpm/ticks_per_beat. For the default values that’s + 60000/120/4 = 125 milliseconds or 1 beat = 500 milliseconds. + """ ... def get_tempo() -> Tuple[int, int]: - """以整数元组的形式获取当前节奏:``(ticks, bpm)``。 (获得节奏值) + """Gets the current tempo as a tuple of integers: ``(ticks, bpm)``. -Example: ``ticks, beats = music.get_tempo()`` + Example: ``ticks, beats = music.get_tempo()`` -:return: The temp as a tuple with two integer values, the ticks then the beats per minute.""" + :return: The temp as a tuple with two integer values, the ticks then the beats per minute. + """ ... -def play(music: Union[str, List[str], Tuple[str, ...]], pin: Optional[MicroBitDigitalPin]=pin0, wait: bool=True, loop: bool=False) -> None: - """播放音乐。 (播放) +def play( + music: Union[str, List[str], Tuple[str, ...]], + pin: Optional[MicroBitDigitalPin] = pin0, + wait: bool = True, + loop: bool = False, +) -> None: + """Plays music. -Example: ``music.play(music.NYAN)`` + Example: ``music.play(music.NYAN)`` -:param music: (音乐) `a special notation `_中指定的音乐 -:param pin: (引脚) 用于外接扬声器的输出引脚(默认为 ``pin0``),``None`` 表示无声音。 -:param wait: (等待) 如果 ``wait`` 设置为 ``True``,则此函数阻塞。 -:param loop: 如果 ``loop`` 设置为 ``True``,曲调会重复直到调用 ``stop`` 或阻塞调用被中断。 + :param music: music specified in `a special notation `_ + :param pin: the output pin for use with an external speaker (default ``pin0``), ``None`` for no sound. + :param wait: If ``wait`` is set to ``True``, this function is blocking. + :param loop: If ``loop`` is set to ``True``, the tune repeats until ``stop`` is called or the blocking call is interrupted. -Many built-in melodies are defined in this module.""" + Many built-in melodies are defined in this module. + """ ... -def pitch(frequency: int, duration: int=-1, pin: Optional[MicroBitDigitalPin]=pin0, wait: bool=True) -> None: - """播放一个音符。 (音高) +def pitch( + frequency: int, + duration: int = -1, + pin: Optional[MicroBitDigitalPin] = pin0, + wait: bool = True, +) -> None: + """Play a note. -Example: ``music.pitch(185, 1000)`` + Example: ``music.pitch(185, 1000)`` -:param frequency: (频率) 整数频率 -:param duration: (持续) 一毫秒的持续时间。如果是负的,则声音将持续到下一次调用或对 ``stop`` 的调用。 -:param pin: (引脚) 可选输出引脚(默认值``pin0``)。 -:param wait: (等待) 如果 ``wait`` 设置为 ``True``,则此函数阻塞。 + :param frequency: An integer frequency + :param duration: A millisecond duration. If negative then sound is continuous until the next call or a call to ``stop``. + :param pin: Optional output pin (default ``pin0``). + :param wait: If ``wait`` is set to ``True``, this function is blocking. -For example, if the frequency is set to 440 and the length to -1000 then we hear a standard concert A for one second. + For example, if the frequency is set to 440 and the length to + 1000 then we hear a standard concert A for one second. -You can only play one pitch on one pin at any one time.""" + You can only play one pitch on one pin at any one time. + """ ... -def stop(pin: Optional[MicroBitDigitalPin]=pin0) -> None: - """停止内置扬声器播放任何音乐,并停止发出任何引脚输出的声音。 (停止) +def stop(pin: Optional[MicroBitDigitalPin] = pin0) -> None: + """Stops all music playback on the built-in speaker and any pin outputting sound. -Example: ``music.stop()`` + Example: ``music.stop()`` -:param pin: (引脚) 可以提供可选参数来指定一个引脚,如``music.stop(pin1)``。""" + :param pin: An optional argument can be provided to specify a pin, e.g. ``music.stop(pin1)``. + """ def reset() -> None: - """将 ticks、bpm、duration 和 octave重置为默认值。 + """Resets ticks, bpm, duration and octave to their default values. -Example: ``music.reset()`` + Example: ``music.reset()`` -Values: -- ``ticks = 4`` -- ``bpm = 120`` -- ``duration = 4`` -- ``octave = 4``""" - ... \ No newline at end of file + Values: + - ``ticks = 4`` + - ``bpm = 120`` + - ``duration = 4`` + - ``octave = 4`` + """ + ... diff --git a/lang/zh-cn/typeshed/stdlib/neopixel.pyi b/lang/zh-cn/typeshed/stdlib/neopixel.pyi index 6d53501..2d5a749 100644 --- a/lang/zh-cn/typeshed/stdlib/neopixel.pyi +++ b/lang/zh-cn/typeshed/stdlib/neopixel.pyi @@ -1,81 +1,82 @@ -"""可单独寻址的 RGB 和 RGBW LED 灯带。 (Neopixel)""" +"""Individually addressable RGB and RGBW LED strips. +""" from .microbit import MicroBitDigitalPin from typing import Tuple class NeoPixel: + def __init__(self, pin: MicroBitDigitalPin, n: int, bpp: int = 3) -> None: + """Initialise a new strip of neopixel LEDs controlled via a pin. - def __init__(self, pin: MicroBitDigitalPin, n: int, bpp: int=3) -> None: - """初始化一条通过一个引脚控制的新 neopixel LED 灯带。 + Example: ``np = neopixel.NeoPixel(pin0, 8)`` -Example: ``np = neopixel.NeoPixel(pin0, 8)`` + To support RGBW neopixels, a third argument can be passed to + ``NeoPixel`` to indicate the number of bytes per pixel (``bpp``). + For RGBW, this is is 4 rather than the default of 3 for RGB and GRB. -To support RGBW neopixels, a third argument can be passed to -``NeoPixel`` to indicate the number of bytes per pixel (``bpp``). -For RGBW, this is is 4 rather than the default of 3 for RGB and GRB. + Each pixel is addressed by a position (starting from 0). Neopixels are + given RGB (red, green, blue) / RGBW (red, green, blue, white) values + between 0-255 as a tuple. For example, in RGB, ``(255,255,255)`` is + white. In RGBW, ``(255,255,255,0)`` or ``(0,0,0,255)`` is white. -Each pixel is addressed by a position (starting from 0). Neopixels are -given RGB (red, green, blue) / RGBW (red, green, blue, white) values -between 0-255 as a tuple. For example, in RGB, ``(255,255,255)`` is -white. In RGBW, ``(255,255,255,0)`` or ``(0,0,0,255)`` is white. + See `the online docs `_ for warnings and other advice. -See `the online docs `_ for warnings and other advice. - -:param pin: (引脚) 控制 neopixel 灯带的引脚。 -:param n: 灯带中 neopixel 灯珠的数量。 -:param bpp: (每像素字节数) 每个像素的字节数。对于 RGB 和 GRB 而言,只有将该值设置为 4 而不是默认值 3,RGBW neopixel 才能支持。""" + :param pin: The pin controlling the neopixel strip. + :param n: The number of neopixels in the strip. + :param bpp: Bytes per pixel. For RGBW neopixel support, pass 4 rather than the default of 3 for RGB and GRB. + """ ... - def clear(self) -> None: - """清除所有像素。 (清除) + """Clear all the pixels. -Example: ``np.clear()``""" + Example: ``np.clear()`` + """ ... - def show(self) -> None: - """显示像素。 (显示) + """Show the pixels. -Example: ``np.show()`` + Example: ``np.show()`` -Must be called for any updates to become visible.""" + Must be called for any updates to become visible. + """ ... - def write(self) -> None: - """显示像素(仅限 micro:bit V2)。 (写入) + """Show the pixels (micro:bit V2 only). -Example: ``np.write()`` + Example: ``np.write()`` -Must be called for any updates to become visible. + Must be called for any updates to become visible. -Equivalent to ``show``.""" + Equivalent to ``show``. + """ ... - def fill(self, colour: Tuple[int, ...]) -> None: - """用给定的 RGB/RGBW 值为所有像素着色(仅限 micro:bit V2)。 (填充) + """Colour all pixels a given RGB/RGBW value (micro:bit V2 only). -Example: ``np.fill((0, 0, 255))`` + Example: ``np.fill((0, 0, 255))`` -:param colour: (颜色) 长度与每像素字节数 (bpp) 相同的元组。 + :param colour: A tuple of the same length as the number of bytes per pixel (bpp). -Use in conjunction with ``show()`` to update the neopixels.""" + Use in conjunction with ``show()`` to update the neopixels. + """ ... - def __setitem__(self, key: int, value: Tuple[int, ...]) -> None: - """设置像素颜色 + """Set a pixel colour. -Example: ``np[0] = (255, 0, 0)`` - -:param key: (键) 像素数。 -:param value: 颜色。""" + Example: ``np[0] = (255, 0, 0)`` + :param key: The pixel number. + :param value: The colour. + """ def __getitem__(self, key: int) -> Tuple[int, ...]: - """获取像素颜色。 - -Example: ``r, g, b = np[0]`` + """Get a pixel colour. -:param key: (键) 像素数。 -:return: The colour tuple.""" + Example: ``r, g, b = np[0]`` + :param key: The pixel number. + :return: The colour tuple. + """ def __len__(self) -> int: - """获取此像素条的长度。 (长度) + """Get length of this pixel strip. -Example: ``len(np)``""" \ No newline at end of file + Example: ``len(np)`` + """ diff --git a/lang/zh-cn/typeshed/stdlib/os.pyi b/lang/zh-cn/typeshed/stdlib/os.pyi index 1c6f9f9..2f2db77 100644 --- a/lang/zh-cn/typeshed/stdlib/os.pyi +++ b/lang/zh-cn/typeshed/stdlib/os.pyi @@ -1,63 +1,73 @@ -"""访问文件系统。 (操作系统)""" +"""Access the file system. +""" + from typing import Tuple from typing import List def listdir() -> List[str]: - """列出文件。 (列出目录) + """List files. -Example: ``os.listdir()`` + Example: ``os.listdir()`` -:return: A list of the names of all the files contained within the local -persistent on-device file system.""" + :return: A list of the names of all the files contained within the local + persistent on-device file system. + """ ... def remove(filename: str) -> None: - """移除(删除)一份文件。 (删除) + """Remove (delete) a file. -Example: ``os.remove('data.txt')`` + Example: ``os.remove('data.txt')`` -:param filename: (文件名) 要删除的文件。 + :param filename: The file to delete. -If the file does not exist an ``OSError`` exception will occur.""" + If the file does not exist an ``OSError`` exception will occur. + """ ... def size(filename: str) -> int: - """返回文件的大小。 (大小) + """Returns the size of a file. -Example: ``os.size('data.txt')`` + Example: ``os.size('data.txt')`` -:param filename: (文件名) 此文件 -:return: The size in bytes. + :param filename: The file + :return: The size in bytes. -If the file does not exist an ``OSError`` exception will occur.""" + If the file does not exist an ``OSError`` exception will occur. + """ class uname_result(Tuple[str, str, str, str, str]): - """``os.uname()`` 的结果 (当前系统名称的返回结果)""" + """Result of ``os.uname()``""" sysname: str - """操作系统名称。 (系统名字)""" + """Operating system name.""" + nodename: str - """网络上机器的名称(实现-定义)。 (节点名字)""" + """Name of machine on network (implementation-defined).""" + release: str - """操作系统发布版本。 (发布)""" + """Operating system release.""" + version: str - """操作系统版本。 (版本)""" + """Operating system version.""" + machine: str - """硬件标识符。 (机器)""" + """Hardware identifier.""" def uname() -> uname_result: - """返回标识当前操作系统的信息。 (当前系统名称) + """Returns information identifying the current operating system. -Example: ``os.uname()`` + Example: ``os.uname()`` -The return value is an object with five attributes: + The return value is an object with five attributes: -- ``sysname`` - operating system name -- ``nodename`` - name of machine on network (implementation-defined) -- ``release`` - operating system release -- ``version`` - operating system version -- ``machine`` - hardware identifier + - ``sysname`` - operating system name + - ``nodename`` - name of machine on network (implementation-defined) + - ``release`` - operating system release + - ``version`` - operating system version + - ``machine`` - hardware identifier -There is no underlying operating system in MicroPython. As a result the -information returned by the ``uname`` function is mostly useful for -versioning details.""" - ... \ No newline at end of file + There is no underlying operating system in MicroPython. As a result the + information returned by the ``uname`` function is mostly useful for + versioning details. + """ + ... diff --git a/lang/zh-cn/typeshed/stdlib/radio.pyi b/lang/zh-cn/typeshed/stdlib/radio.pyi index 883febe..8dd0267 100644 --- a/lang/zh-cn/typeshed/stdlib/radio.pyi +++ b/lang/zh-cn/typeshed/stdlib/radio.pyi @@ -1,129 +1,152 @@ -"""使用内置无线电在 micro:bit 之间进行通信。 (无线电)""" +"""Communicate between micro:bits with the built-in radio. +""" + from _typeshed import WriteableBuffer from typing import Optional, Tuple + RATE_1MBIT: int -"""用于表示每秒 1 兆字节吞吐量的常数。 (速率 1Mbit)""" +"""Constant used to indicate a throughput of 1 MBit a second.""" + RATE_2MBIT: int -"""用于表示每秒 2 兆字节吞吐量的常数。 (速率 2Mbit)""" +"""Constant used to indicate a throughput of 2 MBit a second.""" def on() -> None: - """打开无线电。 (打开) + """Turns the radio on. -Example: ``radio.on()`` + Example: ``radio.on()`` -This needs to be explicitly called since the radio draws power and takes -up memory that you may otherwise need.""" + This needs to be explicitly called since the radio draws power and takes + up memory that you may otherwise need. + """ ... def off() -> None: - """关闭无线电以节省电量和内存。 (关闭) + """Turns off the radio, saving power and memory. -Example: ``radio.off()``""" + Example: ``radio.off()`` + """ ... -def config(length: int=32, queue: int=3, channel: int=7, power: int=6, address: int=1969383796, group: int=0, data_rate: int=RATE_1MBIT) -> None: - """配置无线电。 (配置) - -Example: ``radio.config(group=42)`` - -The default configuration is suitable for most use. - -:param length: (长度) (默认值32)以字节为单位,定义了通过无线电传输消息的最大长度。 -其长度可达 251 字节(S0、LENGTH 和 S1 前导码:254-3 字节)。 -:param queue: (队列) (默认值3)规定了传入消息队列中可以存储的消息数量。 -如果队列中没有多余的空间留给传入的消息,那么传入的消息就会被丢弃。 -:param channel: (信道) (缺省值7)范围为从0到83(含83)的整数,用于定义一任意“信道”,以便将无线电调到该信道。信息通过该信道发送,并且只有通过该信道接收到的消息才被放到传入消息队列中。每一步的宽度为 1 MHz,基于 2400 MHz。 -:param power: (幂数) (默认值6)用于表示广播消息时所使用信号强度的整数值,其范围为从0到7(包含7)。 -该值越大,信号越强,但设备消耗的功率也越大。其编码转换为以下 dBm(分贝毫瓦)值列表中的不同值:-30, -20, -16, -12, -8, -4, 0, 4。 -:param address: (地址) (default=0x75626974) 任意名称,表示为 32 位地址,用于在硬件级别过滤传入的数据包,仅保留与您设置的地址匹配的数据包。 -其他 micro:bit 相关平台使用的默认设置与此处的默认设置相同。 -:param group: (群组) (默认值0)过滤消息时与 ``address`` 一起使用的 8 位的数值(0-255)。 -从概念上讲,"address”就像房屋或办公室的地址,而“group”就像住在该地址,并且你想给他或她发消息的那个人。 -:param data_rate: (数据传输速率) (默认值``radio.RATE_1MBIT``)表示数据吞吐速度。 -可以是``radio``模块中定义的以下常数之一:``RATE_250KBIT``、``RATE_1MBIT`` 或 ``RATE_2MBIT``。 - -If ``config`` is not called then the defaults described above are assumed.""" +def config( + length: int = 32, + queue: int = 3, + channel: int = 7, + power: int = 6, + address: int = 0x75626974, + group: int = 0, + data_rate: int = RATE_1MBIT, +) -> None: + """Configures the radio. + + Example: ``radio.config(group=42)`` + + The default configuration is suitable for most use. + + :param length: (default=32) defines the maximum length, in bytes, of a message sent via the radio. + It can be up to 251 bytes long (254 - 3 bytes for S0, LENGTH and S1 preamble). + :param queue: (default=3) specifies the number of messages that can be stored on the incoming message queue. + If there are no spaces left on the queue for incoming messages, then the incoming message is dropped. + :param channel: (default=7) an integer value from 0 to 83 (inclusive) that defines an arbitrary "channel" to which the radio is tuned. + Messages will be sent via this channel and only messages received via this channel will be put onto the incoming message queue. Each step is 1MHz wide, based at 2400MHz. + :param power: (default=6) is an integer value from 0 to 7 (inclusive) to indicate the strength of signal used when broadcasting a message. + The higher the value the stronger the signal, but the more power is consumed by the device. The numbering translates to positions in the following list of dBm (decibel milliwatt) values: -30, -20, -16, -12, -8, -4, 0, 4. + :param address: (default=0x75626974) an arbitrary name, expressed as a 32-bit address, that's used to filter incoming packets at the hardware level, keeping only those that match the address you set. + The default used by other micro:bit related platforms is the default setting used here. + :param group: (default=0) an 8-bit value (0-255) used with the ``address`` when filtering messages. + Conceptually, "address" is like a house/office address and "group" is like the person at that address to which you want to send your message. + :param data_rate: (default=``radio.RATE_1MBIT``) indicates the speed at which data throughput takes place. + Can be one of the following constants defined in the ``radio`` module: ``RATE_250KBIT``, ``RATE_1MBIT`` or ``RATE_2MBIT``. + + If ``config`` is not called then the defaults described above are assumed. + """ ... def reset() -> None: - """将设置重设为默认值。 + """Reset the settings to their default values. -Example: ``radio.reset()`` + Example: ``radio.reset()`` -The defaults as as per the ``config`` function above.""" + The defaults as as per the ``config`` function above. + """ ... def send_bytes(message: bytes) -> None: - """发送一条包含字节的消息。 (发送字节) + """Sends a message containing bytes. -Example: ``radio.send_bytes(b'hello')`` + Example: ``radio.send_bytes(b'hello')`` -:param message: (消息) 待发送的字节。""" + :param message: The bytes to send. + """ ... def receive_bytes() -> Optional[bytes]: - """接收消息队列中的下一条传入消息。 (接收字节) + """Receive the next incoming message on the message queue. -Example: ``radio.receive_bytes()`` + Example: ``radio.receive_bytes()`` -:return: The message bytes if any, otherwise ``None``.""" + :return: The message bytes if any, otherwise ``None``. + """ ... def receive_bytes_into(buffer: WriteableBuffer) -> Optional[int]: - """将消息队列中的下一条传入消息复制到缓冲区。 (接收传入的字节) + """Copy the next incoming message on the message queue into a buffer. -Example: ``radio.receive_bytes_info(buffer)`` + Example: ``radio.receive_bytes_info(buffer)`` -:param buffer: (缓冲区) 目标缓冲区。如果消息大小大于缓冲区,则消息会被截断。 -:return: ``None`` if there are no pending messages, otherwise it returns the length of the message (which might be more than the length of the buffer).""" + :param buffer: The target buffer. The message is truncated if larger than the buffer. + :return: ``None`` if there are no pending messages, otherwise it returns the length of the message (which might be more than the length of the buffer). + """ ... def send(message: str) -> None: - """发送消息字符串。 (发送) + """Sends a message string. -Example: ``radio.send('hello')`` + Example: ``radio.send('hello')`` -This is the equivalent of ``radio.send_bytes(bytes(message, 'utf8'))`` but with ``b'\x01\x00\x01'`` -prepended to the front (to make it compatible with other platforms that target the micro:bit). + This is the equivalent of ``radio.send_bytes(bytes(message, 'utf8'))`` but with ``b'\x01\x00\x01'`` + prepended to the front (to make it compatible with other platforms that target the micro:bit). -:param message: (消息) 待发送的字符串。""" + :param message: The string to send. + """ ... def receive() -> Optional[str]: - """按照与``receive_bytes``完全相同的工作方式,但是返回所发送的内容。 (接收) + """Works in exactly the same way as ``receive_bytes`` but returns whatever was sent. -Example: ``radio.receive()`` + Example: ``radio.receive()`` -Equivalent to ``str(receive_bytes(), 'utf8')`` but with a check that the the first -three bytes are ``b'\x01\x00\x01'`` (to make it compatible with other platforms that -may target the micro:bit). + Equivalent to ``str(receive_bytes(), 'utf8')`` but with a check that the the first + three bytes are ``b'\x01\x00\x01'`` (to make it compatible with other platforms that + may target the micro:bit). -:return: The message with the prepended bytes stripped and converted to a string. + :return: The message with the prepended bytes stripped and converted to a string. -A ``ValueError`` exception is raised if conversion to string fails.""" + A ``ValueError`` exception is raised if conversion to string fails. + """ ... def receive_full() -> Optional[Tuple[bytes, int, int]]: - """返回一个包含三个数值的元组,用来代表消息队列中的下一条传入消息。 (接受完整消息) + """Returns a tuple containing three values representing the next incoming message on the message queue. -Example: ``radio.receive_full()`` + Example: ``radio.receive_full()`` -If there are no pending messages then ``None`` is returned. + If there are no pending messages then ``None`` is returned. -The three values in the tuple represent: + The three values in the tuple represent: -- the next incoming message on the message queue as bytes. -- the RSSI (signal strength): a value between 0 (strongest) and -255 (weakest) as measured in dBm. -- a microsecond timestamp: the value returned by ``time.ticks_us()`` when the message was received. + - the next incoming message on the message queue as bytes. + - the RSSI (signal strength): a value between 0 (strongest) and -255 (weakest) as measured in dBm. + - a microsecond timestamp: the value returned by ``time.ticks_us()`` when the message was received. -For example:: + For example:: - details = radio.receive_full() - if details: - msg, rssi, timestamp = details + details = radio.receive_full() + if details: + msg, rssi, timestamp = details -This function is useful for providing information needed for triangulation -and/or trilateration with other micro:bit devices. + This function is useful for providing information needed for triangulation + and/or trilateration with other micro:bit devices. -:return: ``None`` if there is no message, otherwise a tuple of length three with the bytes, strength and timestamp values.""" - ... \ No newline at end of file + :return: ``None`` if there is no message, otherwise a tuple of length three with the bytes, strength and timestamp values. + """ + ... diff --git a/lang/zh-cn/typeshed/stdlib/random.pyi b/lang/zh-cn/typeshed/stdlib/random.pyi index 0695b70..a2c2ef3 100644 --- a/lang/zh-cn/typeshed/stdlib/random.pyi +++ b/lang/zh-cn/typeshed/stdlib/random.pyi @@ -1,80 +1,93 @@ -"""生成随机数。 (随机数)""" +"""Generate random numbers. +""" from typing import TypeVar, Sequence, Union, overload def getrandbits(n: int) -> int: - """生成一个具有``n``个随机位的整数。 (生成随机位) + """Generate an integer with ``n`` random bits. -Example: ``random.getrandbits(1)`` + Example: ``random.getrandbits(1)`` -:param n: 一个在1到30之间(包含30)的数值。""" + :param n: A value between 1-30 (inclusive). + """ ... def seed(n: int) -> None: - """初始化随机数生成器。 (种子) + """Initialize the random number generator. -Example: ``random.seed(0)`` + Example: ``random.seed(0)`` -:param n: 整数种子 + :param n: The integer seed -This will give you reproducibly deterministic randomness from a given starting -state (``n``).""" + This will give you reproducibly deterministic randomness from a given starting + state (``n``). + """ ... def randint(a: int, b: int) -> int: - """在``a``到``b``(包含``b``)之间随机选择一个整数。 (随机整数) + """Choose a random integer between ``a`` and ``b`` inclusive. -Example: ``random.randint(0, 9)`` + Example: ``random.randint(0, 9)`` -:param a: 区间起始值(包含) -:param b: 区间结束值(包含) + :param a: Start value for the range (inclusive) + :param b: End value for the range (inclusive) -Alias for ``randrange(a, b + 1)``.""" + Alias for ``randrange(a, b + 1)``. + """ ... @overload def randrange(stop: int) -> int: - """在零到``stop``(不含``stop``)之间随机选择一个整数。 (随机区间) + """Choose a randomly selected integer between zero and up to (but not + including) ``stop``. -Example: ``random.randrange(10)`` + Example: ``random.randrange(10)`` -:param stop: (结束值) 区间结束值(不含)""" + :param stop: End value for the range (exclusive) + """ ... @overload -def randrange(start: int, stop: int, step: int=1) -> int: - """从区间``range(start, stop, step)``中随机选择一个元素。 (随机区间) +def randrange(start: int, stop: int, step: int = 1) -> int: + """ + Choose a randomly selected element from ``range(start, stop, step)``. -Example: ``random.randrange(0, 10)`` + Example: ``random.randrange(0, 10)`` -:param start: (起始值) 区间起始值(包含) -:param stop: (结束值) 区间结束值(不含) -:param step: (步长) 步长。""" + :param start: The start of the range (inclusive) + :param stop: The end of the range (exclusive) + :param step: The step. + """ ... -_T = TypeVar('_T') + +_T = TypeVar("_T") def choice(seq: Sequence[_T]) -> _T: - """从非空序列``seq``中选择一个随机元素。 (选择) + """Choose a random element from the non-empty sequence ``seq``. -Example: ``random.choice([Image.HAPPY, Image.SAD])`` + Example: ``random.choice([Image.HAPPY, Image.SAD])`` -:param seq: (序列) 序列。 + :param seq: A sequence. -If ``seq`` is empty, raises ``IndexError``.""" + If ``seq`` is empty, raises ``IndexError``. + """ ... def random() -> float: - """在区间[0.0, 1.0)内生成一个随机浮点数。 (随机) + """Generate a random floating point number in the range [0.0, 1.0). -Example: ``random.random()`` + Example: ``random.random()`` -:return: The random floating point number""" + :return: The random floating point number + """ ... def uniform(a: float, b: float) -> float: - """返回一个介于``a``和``b``(包含``b``)之间的随机浮点数。 (均匀分布随机数) + """ + Return a random floating point number between ``a`` and ``b`` inclusive. -Example: ``random.uniform(0, 9)`` + Example: ``random.uniform(0, 9)`` -:param a: 区间起始值(包含) -:param b: 区间结束值(包含)""" - ... \ No newline at end of file + :param a: Start value for the range (inclusive) + :param b: End value for the range (inclusive) + """ + ... diff --git a/lang/zh-cn/typeshed/stdlib/speech.pyi b/lang/zh-cn/typeshed/stdlib/speech.pyi index edb82d7..349d188 100644 --- a/lang/zh-cn/typeshed/stdlib/speech.pyi +++ b/lang/zh-cn/typeshed/stdlib/speech.pyi @@ -1,79 +1,106 @@ -"""使 micro:bit 说话、唱歌和发出其他类似语音的声音。 (语音)""" +"""Make the micro:bit talk, sing and make other speech like sounds. +""" + from typing import Optional from .microbit import MicroBitDigitalPin, pin0 def translate(words: str) -> str: - """把英语单词翻译成音素。 (翻译) + """Translate English words to phonemes. -Example: ``speech.translate('hello world')`` + Example: ``speech.translate('hello world')`` -:param words: (单词) 一连串英语单词。 -:return: A string containing a best guess at the appropriate phonemes to pronounce. -The output is generated from this `text to phoneme translation table `_. + :param words: A string of English words. + :return: A string containing a best guess at the appropriate phonemes to pronounce. + The output is generated from this `text to phoneme translation table `_. -This function should be used to generate a first approximation of phonemes -that can be further hand-edited to improve accuracy, inflection and -emphasis. + This function should be used to generate a first approximation of phonemes + that can be further hand-edited to improve accuracy, inflection and + emphasis. -See `the online documentation `_ for detailed information.""" + See `the online documentation `_ for detailed information. + """ ... -def pronounce(phonemes: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: Optional[MicroBitDigitalPin]=pin0) -> None: - """发出音素的声音。 (发音) - -Example: ``speech.pronounce(' /HEHLOW WERLD')`` - -:param phonemes: (音素) 要发音的音素串 -:param pitch: (音高) 代表声音音高的数字 -:param speed: (速度:) 代表声音速度的数字 -:param mouth: (嘴巴) 表示声音口型的数字 -:param throat: (喉部) 表示声音喉型的数字 -:param pin: (引脚) 可选参数,可用于指定输出引脚来覆盖 ``pin0`` 默认值。 -如果不想从引脚上播放任何声音,可以使用 ``pin=None``。仅限micro:bit V2。 - -Override the optional pitch, speed, mouth and throat settings to change the -timbre (quality) of the voice. - -See `the online documentation `_ for detailed information.""" +def pronounce( + phonemes: str, + pitch: int = 64, + speed: int = 72, + mouth: int = 128, + throat: int = 128, + pin: Optional[MicroBitDigitalPin] = pin0, +) -> None: + """Pronounce phonemes. + + Example: ``speech.pronounce(' /HEHLOW WERLD')`` + + :param phonemes: The string of phonemes to pronounce + :param pitch: A number representing the pitch of the voice + :param speed: A number representing the speed of the voice + :param mouth: A number representing the mouth of the voice + :param throat: A number representing the throat of the voice + :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. + If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. + + Override the optional pitch, speed, mouth and throat settings to change the + timbre (quality) of the voice. + + See `the online documentation `_ for detailed information. + """ ... -def say(words: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: MicroBitDigitalPin=pin0) -> None: - """说英语单词。 (说) - -Example: ``speech.say('hello world')`` - -:param words: (单词) 要说的词串。 -:param pitch: (音高) 代表声音音高的数字 -:param speed: (速度) 代表声音速度的数字 -:param mouth: (嘴部) 表示声音口型的数字 -:param throat: (喉部) 表示声音喉型的数字 -:param pin: (引脚) 可选参数,可用于指定输出引脚来覆盖 ``pin0`` 默认值。 -如果不想从引脚上播放任何声音,可以使用 ``pin=None``。仅限micro:bit V2。 - -The result is semi-accurate for English. Override the optional pitch, speed, -mouth and throat settings to change the timbre (quality) of the voice. - -This is a short-hand equivalent of: -``speech.pronounce(speech.translate(words))`` - -See `the online documentation `_ for detailed information.""" +def say( + words: str, + pitch: int = 64, + speed: int = 72, + mouth: int = 128, + throat: int = 128, + pin: MicroBitDigitalPin = pin0, +) -> None: + """Say English words. + + Example: ``speech.say('hello world')`` + + :param words: The string of words to say. + :param pitch: A number representing the pitch of the voice + :param speed: A number representing the speed of the voice + :param mouth: A number representing the mouth of the voice + :param throat: A number representing the throat of the voice + :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. + If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. + + The result is semi-accurate for English. Override the optional pitch, speed, + mouth and throat settings to change the timbre (quality) of the voice. + + This is a short-hand equivalent of: + ``speech.pronounce(speech.translate(words))`` + + See `the online documentation `_ for detailed information. + """ ... -def sing(phonemes: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: MicroBitDigitalPin=pin0) -> None: - """唱音素。 (唱歌) - -Example: ``speech.sing(' /HEHLOW WERLD')`` - -:param phonemes: (音素) 要唱的词串。 -:param pitch: (音高) 代表声音音高的数字 -:param speed: (速度) 代表声音速度的数字 -:param mouth: (嘴部) 表示声音口型的数字 -:param throat: (喉部) 表示声音喉型的数字 -:param pin: (引脚) 可选参数,可用于指定输出引脚来覆盖 ``pin0`` 默认值。 -如果不想从引脚上播放任何声音,可以使用 ``pin=None``。仅限micro:bit V2。 - -Override the optional pitch, speed, mouth and throat settings to change -the timbre (quality) of the voice. - -See `the online documentation `_ for detailed information.""" - ... \ No newline at end of file +def sing( + phonemes: str, + pitch: int = 64, + speed: int = 72, + mouth: int = 128, + throat: int = 128, + pin: MicroBitDigitalPin = pin0, +) -> None: + """Sing phonemes. + + Example: ``speech.sing(' /HEHLOW WERLD')`` + + :param phonemes: The string of words to sing. + :param pitch: A number representing the pitch of the voice + :param speed: A number representing the speed of the voice + :param mouth: A number representing the mouth of the voice + :param throat: A number representing the throat of the voice + :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. + If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. + + Override the optional pitch, speed, mouth and throat settings to change + the timbre (quality) of the voice. + + See `the online documentation `_ for detailed information. + """ + ... diff --git a/lang/zh-cn/typeshed/stdlib/struct.pyi b/lang/zh-cn/typeshed/stdlib/struct.pyi index e67b12e..53b3e0b 100644 --- a/lang/zh-cn/typeshed/stdlib/struct.pyi +++ b/lang/zh-cn/typeshed/stdlib/struct.pyi @@ -1,56 +1,65 @@ -"""打包和解包原始数据类型。 (结构)""" +"""Pack and unpack primitive data types. +""" + from _typeshed import ReadableBuffer, WriteableBuffer from typing import Any, Tuple, Union def calcsize(fmt: str) -> int: - """获取存储给定 ``fmt`` 所需的字节数。 (计算大小) + """Get the number of bytes needed to store the given ``fmt``. -Example: ``struct.calcsize('hf')`` + Example: ``struct.calcsize('hf')`` -:param fmt: (格式字符串) 格式字符串。 -:return The number of bytes needed to store such a value.""" + :param fmt: A format string. + :return The number of bytes needed to store such a value. + """ ... def pack(fmt: str, v1: Any, *vn: Any) -> bytes: - """根据格式字符串打包值。 (打包) + """Pack values according to a format string. -Example: ``struct.pack('hf', 1, 3.1415)`` + Example: ``struct.pack('hf', 1, 3.1415)`` -:param fmt: (格式字符串) 格式字符串。 -:param v1: 第一个值。 -:param *vn: 剩余值。 -:return A bytes object encoding the values.""" + :param fmt: The format string. + :param v1: The first value. + :param *vn: The remaining values. + :return A bytes object encoding the values. + """ ... -def pack_into(fmt: str, buffer: WriteableBuffer, offset: int, v1: Any, *vn: Any) -> None: - """根据格式字符串打包值。 +def pack_into( + fmt: str, buffer: WriteableBuffer, offset: int, v1: Any, *vn: Any +) -> None: + """Pack values according to a format string. -Example: ``struct.pack_info('hf', buffer, 1, 3.1415)`` + Example: ``struct.pack_info('hf', buffer, 1, 3.1415)`` -:param fmt: (格式字符串) 格式字符串。 -:param buffer: (缓冲区) 待写入的目标缓冲区。 -:param offset: (偏移量) 缓冲区内的偏移量。如果从缓冲区末端开始算起,该偏移量可能是负数。 -:param v1: 第一个值。 -:param *vn: 剩余值。""" + :param fmt: The format string. + :param buffer: The target buffer to write into. + :param offset: The offset into the buffer. May be negative to count from the end of the buffer. + :param v1: The first value. + :param *vn: The remaining values. + """ ... def unpack(fmt: str, data: ReadableBuffer) -> Tuple[Any, ...]: - """根据格式字符串解压数据。 (解包) + """Unpack data according to a format string. -Example: ``v1, v2 = struct.unpack('hf', buffer)`` + Example: ``v1, v2 = struct.unpack('hf', buffer)`` -:param fmt: (格式字符串) 格式字符串。 -:param data: (数据) 数据。 -:return: A tuple of the unpacked values.""" + :param fmt: The format string. + :param data: The data. + :return: A tuple of the unpacked values. + """ ... -def unpack_from(fmt: str, buffer: ReadableBuffer, offset: int=0) -> Tuple: - """根据格式字符串从缓冲区解压数据。 +def unpack_from(fmt: str, buffer: ReadableBuffer, offset: int = 0) -> Tuple: + """Unpack data from a buffer according to a format string. -Example: ``v1, v2 = struct.unpack_from('hf', buffer)`` + Example: ``v1, v2 = struct.unpack_from('hf', buffer)`` -:param fmt: (格式字符串) 格式字符串。 -:param buffer: 待读取的源缓冲区。 -:param offset: (偏移量) 缓冲区内的偏移量。如果从缓冲区末端开始算起,该偏移量可能是负数。 -:return: A tuple of the unpacked values.""" - ... \ No newline at end of file + :param fmt: The format string. + :param buffer: The source buffer to read from. + :param offset: The offset into the buffer. May be negative to count from the end of the buffer. + :return: A tuple of the unpacked values. + """ + ... diff --git a/lang/zh-cn/typeshed/stdlib/sys.pyi b/lang/zh-cn/typeshed/stdlib/sys.pyi index 80c2502..320bac9 100644 --- a/lang/zh-cn/typeshed/stdlib/sys.pyi +++ b/lang/zh-cn/typeshed/stdlib/sys.pyi @@ -1,36 +1,43 @@ -"""系统特定功能 (系统)""" +"""System specific functions""" + from typing import Any, Dict, List, NoReturn, TextIO, Tuple -def exit(retval: object=...) -> NoReturn: - """根据给定退出代码终止当前程序。 (退出) +def exit(retval: object = ...) -> NoReturn: + """Terminate current program with a given exit code. -Example: ``sys.exit(1)`` + Example: ``sys.exit(1)`` -This function raises a ``SystemExit`` exception. If an argument is given, its -value given as an argument to ``SystemExit``. + This function raises a ``SystemExit`` exception. If an argument is given, its + value given as an argument to ``SystemExit``. -:param retval: (返回值) 退出代码或者消息。""" + :param retval: The exit code or message. + """ ... def print_exception(exc: Exception) -> None: - """打印带有回溯的异常。 (打印异常) + """ + Print an exception with a traceback. + + Example: ``sys.print_exception(e)`` -Example: ``sys.print_exception(e)`` + :param exc: The exception to print -:param exc: (异常) 需打印的异常 + This is simplified version of a function which appears in the + ``traceback`` module in CPython. + """ -This is simplified version of a function which appears in the -``traceback`` module in CPython.""" argv: List[str] -"""当前程序启动时使用的参数的可变列表。 (参数)""" +"""A mutable list of arguments the current program was started with.""" + byteorder: str -"""系统的字节顺序 (``"little"`` 或 ``"big"``)。 (字节序)""" +"""The byte order of the system (``"little"`` or ``"big"``).""" class _implementation: name: str version: Tuple[int, int, int] + implementation: _implementation -"""包含有关当前 Python 实现的信息的对象。 (实现) +"""Object with information about the current Python implementation. For MicroPython, it has following attributes: @@ -44,11 +51,13 @@ minimal ports). CPython mandates more attributes for this object, but the actual useful bare minimum is implemented in MicroPython. """ + maxsize: int """ -在当前平台上可以容纳的整数类型的最大值, -或 MicroPython 整数类型可表示的最大值,如果它小于 -平台的最大值(这见于 MicroPython 端口不支持长整数的情况)。 (最大值) +Maximum value which a native integer type can hold on the current platform, +or maximum value representable by MicroPython integer type, if it's smaller +than platform max value (that is the case for MicroPython ports without +long int support). This attribute is useful for detecting "bitness" of a platform (32-bit vs 64-bit, etc.). It's recommended to not compare this attribute to some @@ -68,14 +77,17 @@ value directly, but instead count number of bits in it:: # (e.g. 31) due to peculiarities described above, so use "> 16", # "> 32", "> 64" style of comparisons. """ + modules: Dict[str, Any] -"""已加载模块的字典。 (模块) +"""Dictionary of loaded modules. On some ports, it may not include builtin modules.""" + path: List[str] -"""用于搜索导入模块的目录的可变列表。 (路径)""" +"""A mutable list of directories to search for imported modules.""" + platform: str -"""正在运行 MicroPython 的平台。 (平台) +"""The platform that MicroPython is running on. For OS/RTOS ports, this is usually an identifier of the OS, e.g. ``"linux"``. For baremetal ports it is an identifier of a board, e.g. ``"pyboard"`` for @@ -85,11 +97,13 @@ distinguish one board from another. If you need to check whether your program runs on MicroPython (vs other Python implementation), use ``sys.implementation`` instead. """ + version: str -"""此实现符合的 Python 语言版本,为字符串。 (版本)""" +"""Python language version that this implementation conforms to, as a string.""" + version_info: Tuple[int, int, int] -"""此实现符合的 Python 语言版本,为整数元组。 (版本信息) +"""Python language version that this implementation conforms to, as a tuple of ints. Only the first three version numbers (major, minor, micro) are supported and they can be referenced only by index, not by name. -""" \ No newline at end of file +""" diff --git a/lang/zh-cn/typeshed/stdlib/time.pyi b/lang/zh-cn/typeshed/stdlib/time.pyi index 04baa25..598c483 100644 --- a/lang/zh-cn/typeshed/stdlib/time.pyi +++ b/lang/zh-cn/typeshed/stdlib/time.pyi @@ -1,111 +1,132 @@ -"""测量时间并给程序添加延迟。 (时间)""" +"""Measure time and add delays to programs. +""" + from typing import Union def sleep(seconds: Union[int, float]) -> None: - """延迟几秒钟。 (休眠) + """ + Delay a number of seconds. -Example: ``time.sleep(1)`` + Example: ``time.sleep(1)`` -:param seconds: (秒) 休眠的秒数。 -使用浮点数休眠小数秒数。""" + :param seconds: The number of seconds to sleep for. + Use a floating-point number to sleep for a fractional number of seconds. + """ ... def sleep_ms(ms: int) -> None: - """延迟给定的毫秒数。 (休眠延迟以毫秒计算) + """ + Delay for given number of milliseconds. -Example: ``time.sleep_ms(1_000_000)`` + Example: ``time.sleep_ms(1_000_000)`` -:param ms: (毫秒) 延迟的毫秒数 (>= 0)。""" + :param ms: The number of milliseconds delay (>= 0). + """ ... def sleep_us(us: int) -> None: - """延迟给定的微秒数。 (休眠延迟以微秒计算) + """ + Delay for given number of microseconds. -Example: ``time.sleep_us(1000)`` + Example: ``time.sleep_us(1000)`` -:param us: (微秒) 延迟的微秒数 (>= 0)。""" + :param us: The number of microseconds delay (>= 0). + """ ... def ticks_ms() -> int: - """获取一个具有任意参考点、递增的毫秒级计数器,该计数器在某个值之后能够绕回。 (毫秒级刻度) + """ + Get an increasing, millisecond counter with an arbitrary reference point, + that wraps around after some value. -Example: ``time.ticks_ms()`` + Example: ``time.ticks_ms()`` -:return: The counter value in milliseconds.""" + :return: The counter value in milliseconds. + """ ... def ticks_us() -> int: - """获取一个具有任意参考点、递增的微秒级计数器,该计数器在某个值之后能够绕回。 (微秒级刻度) + """ + Get an increasing, microsecond counter with an arbitrary reference point, + that wraps around after some value. -Example: ``time.ticks_us()`` + Example: ``time.ticks_us()`` -:return: The counter value in microseconds.""" + :return: The counter value in microseconds. + """ ... def ticks_add(ticks: int, delta: int) -> int: - """给定数字的偏移刻度值,可以是正数或负数。 (增加刻度) + """ + Offset ticks value by a given number, which can be either positive or + negative. -Example: ``time.ticks_add(time.ticks_ms(), 200)`` + Example: ``time.ticks_add(time.ticks_ms(), 200)`` -Given a ticks value, this function allows to calculate ticks -value delta ticks before or after it, following modular-arithmetic -definition of tick values. + Given a ticks value, this function allows to calculate ticks + value delta ticks before or after it, following modular-arithmetic + definition of tick values. -:param ticks: (刻度) 一个刻度值 -:param delta: 整数偏移量 + :param ticks: A ticks value + :param delta: An integer offset -Example:: + Example:: - # Find out what ticks value there was 100ms ago - print(ticks_add(time.ticks_ms(), -100)) + # Find out what ticks value there was 100ms ago + print(ticks_add(time.ticks_ms(), -100)) - # Calculate deadline for operation and test for it - deadline = ticks_add(time.ticks_ms(), 200) - while ticks_diff(deadline, time.ticks_ms()) > 0: - do_a_little_of_something() + # Calculate deadline for operation and test for it + deadline = ticks_add(time.ticks_ms(), 200) + while ticks_diff(deadline, time.ticks_ms()) > 0: + do_a_little_of_something() - # Find out TICKS_MAX used by this port - print(ticks_add(0, -1))""" + # Find out TICKS_MAX used by this port + print(ticks_add(0, -1)) + """ ... def ticks_diff(ticks1: int, ticks2: int) -> int: - """测量函数``time.ticks_ms()``或者函数``ticks_us()``返回值之间的刻度差。本参数为一个有可能绕回的带符号数值。 (刻度差) - -Example: ``time.ticks_diff(scheduled_time, now)`` - -:param ticks1: (刻度1) 要被减的值 -:param ticks2: (刻度2) 要减去的值 - -The argument order is the same as for subtraction operator, -``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. - -``ticks_diff()`` is designed to accommodate various usage -patterns, among them: - -Polling with timeout. In this case, the order of events is known, and you -will deal only with positive results of :func:`time.ticks_diff()`:: - - # Wait for GPIO pin to be asserted, but at most 500us - start = time.ticks_us() - while pin.value() == 0: - if time.ticks_diff(time.ticks_us(), start) > 500: - raise TimeoutError - - -Scheduling events. In this case, :func:`time.ticks_diff()` result may be -negative if an event is overdue:: - - # This code snippet is not optimized - now = time.ticks_ms() - scheduled_time = task.scheduled_time() - if ticks_diff(scheduled_time, now) > 0: - print("Too early, let's nap") - sleep_ms(ticks_diff(scheduled_time, now)) - task.run() - elif ticks_diff(scheduled_time, now) == 0: - print("Right at time!") - task.run() - elif ticks_diff(scheduled_time, now) < 0: - print("Oops, running late, tell task to run faster!") - task.run(run_faster=True)""" - ... \ No newline at end of file + """ + Measure ticks difference between values returned from + ``time.ticks_ms()`` or ``ticks_us()``, as a signed value + which may wrap around. + + Example: ``time.ticks_diff(scheduled_time, now)`` + + :param ticks1: The value to subtract from + :param ticks2: The value to subtract + + The argument order is the same as for subtraction operator, + ``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. + + ``ticks_diff()`` is designed to accommodate various usage + patterns, among them: + + Polling with timeout. In this case, the order of events is known, and you + will deal only with positive results of :func:`time.ticks_diff()`:: + + # Wait for GPIO pin to be asserted, but at most 500us + start = time.ticks_us() + while pin.value() == 0: + if time.ticks_diff(time.ticks_us(), start) > 500: + raise TimeoutError + + + Scheduling events. In this case, :func:`time.ticks_diff()` result may be + negative if an event is overdue:: + + # This code snippet is not optimized + now = time.ticks_ms() + scheduled_time = task.scheduled_time() + if ticks_diff(scheduled_time, now) > 0: + print("Too early, let's nap") + sleep_ms(ticks_diff(scheduled_time, now)) + task.run() + elif ticks_diff(scheduled_time, now) == 0: + print("Right at time!") + task.run() + elif ticks_diff(scheduled_time, now) < 0: + print("Oops, running late, tell task to run faster!") + task.run(run_faster=True) + """ + ... diff --git a/lang/zh-tw/typeshed/stdlib/gc.pyi b/lang/zh-tw/typeshed/stdlib/gc.pyi index 595bd6e..1370abf 100644 --- a/lang/zh-tw/typeshed/stdlib/gc.pyi +++ b/lang/zh-tw/typeshed/stdlib/gc.pyi @@ -1,68 +1,73 @@ -"""控管記憶體回收器""" +"""Control the garbage collector""" + from typing import overload def enable() -> None: - """啟用自動化記憶體回收。""" + """Enable automatic garbage collection.""" ... def disable() -> None: - """停用自動化記憶體回收。 + """Disable automatic garbage collection. -Heap memory can still be allocated, -and garbage collection can still be initiated manually using ``gc.collect``.""" + Heap memory can still be allocated, + and garbage collection can still be initiated manually using ``gc.collect``.""" def collect() -> None: - """執行自動記憶體管理""" + """Run a garbage collection.""" ... def mem_alloc() -> int: - """取得已分配的堆積 RAM 位元組數。 (記憶體分配) + """Get the number of bytes of heap RAM that are allocated. -:return: The number of bytes allocated. + :return: The number of bytes allocated. -This function is MicroPython extension.""" + This function is MicroPython extension. + """ ... def mem_free() -> int: - """取得可用堆積 RAM 的位元組,如果此數量未知,則為 -1。 + """Get the number of bytes of available heap RAM, or -1 if this amount is not known. -:return: The number of bytes free. + :return: The number of bytes free. -This function is MicroPython extension.""" + This function is MicroPython extension. + """ ... @overload def threshold() -> int: - """查詢其他 GC 分配閾值。 + """Query the additional GC allocation threshold. -:return: The GC allocation threshold. + :return: The GC allocation threshold. -This function is a MicroPython extension. CPython has a similar -function - ``set_threshold()``, but due to different GC -implementations, its signature and semantics are different.""" + This function is a MicroPython extension. CPython has a similar + function - ``set_threshold()``, but due to different GC + implementations, its signature and semantics are different. + """ ... @overload def threshold(amount: int) -> None: - """設定其他 GC 分配閾值。 - -Normally, a collection is triggered only when a new allocation -cannot be satisfied, i.e. on an out-of-memory (OOM) condition. -If this function is called, in addition to OOM, a collection -will be triggered each time after ``amount`` bytes have been -allocated (in total, since the previous time such an amount of bytes -have been allocated). ``amount`` is usually specified as less than the -full heap size, with the intention to trigger a collection earlier than when the -heap becomes exhausted, and in the hope that an early collection will prevent -excessive memory fragmentation. This is a heuristic measure, the effect -of which will vary from application to application, as well as -the optimal value of the ``amount`` parameter. - -A value of -1 means a disabled allocation threshold. - -This function is a MicroPython extension. CPython has a similar -function - ``set_threshold()``, but due to different GC -implementations, its signature and semantics are different. - -:param amount: 會觸發記憶體自動管理的位元數超標值。""" - ... \ No newline at end of file + """Set the additional GC allocation threshold. + + Normally, a collection is triggered only when a new allocation + cannot be satisfied, i.e. on an out-of-memory (OOM) condition. + If this function is called, in addition to OOM, a collection + will be triggered each time after ``amount`` bytes have been + allocated (in total, since the previous time such an amount of bytes + have been allocated). ``amount`` is usually specified as less than the + full heap size, with the intention to trigger a collection earlier than when the + heap becomes exhausted, and in the hope that an early collection will prevent + excessive memory fragmentation. This is a heuristic measure, the effect + of which will vary from application to application, as well as + the optimal value of the ``amount`` parameter. + + A value of -1 means a disabled allocation threshold. + + This function is a MicroPython extension. CPython has a similar + function - ``set_threshold()``, but due to different GC + implementations, its signature and semantics are different. + + :param amount: The number of bytes after which a garbage collection should be triggered. + """ + ... diff --git a/lang/zh-tw/typeshed/stdlib/log.pyi b/lang/zh-tw/typeshed/stdlib/log.pyi index 9853de3..c9870fa 100644 --- a/lang/zh-tw/typeshed/stdlib/log.pyi +++ b/lang/zh-tw/typeshed/stdlib/log.pyi @@ -1,89 +1,104 @@ -"""將資料記錄到您的 micro:bit V2。""" +"""Log data to your micro:bit V2.""" + from typing import Literal, Mapping, Optional, Union, overload + MILLISECONDS = 1 -"""毫秒時間戳記格式。""" +"""Milliseconds timestamp format.""" + SECONDS = 10 -"""秒時間戳記格式。""" +"""Seconds timestamp format.""" + MINUTES = 600 -"""分鐘時間戳記格式""" +"""Minutes timestamp format.""" + HOURS = 36000 -"""小時時間戳記格式。 (小時)""" +"""Hours timestamp format.""" + DAYS = 864000 -"""天時間戳記格式。""" +"""Days timestamp format.""" -def set_labels(*labels: str, timestamp: Optional[Literal[1, 10, 36000, 864000]]=SECONDS) -> None: - """設定紀錄檔案標頭。 +def set_labels( + *labels: str, timestamp: Optional[Literal[1, 10, 36000, 864000]] = SECONDS +) -> None: + """Set up the log file header. -Example: ``log.set_labels('X', 'Y', 'Z', timestamp=log.MINUTES)`` + Example: ``log.set_labels('X', 'Y', 'Z', timestamp=log.MINUTES)`` -Ideally this function should be called a single time, before any data is -logged, to configure the data table header once. + Ideally this function should be called a single time, before any data is + logged, to configure the data table header once. -If a log file already exists when the program starts, or if this function -is called multiple times, it will check the labels already defined in the -log file. If this function call contains any new labels not already -present, it will generate a new header row with the additional columns. + If a log file already exists when the program starts, or if this function + is called multiple times, it will check the labels already defined in the + log file. If this function call contains any new labels not already + present, it will generate a new header row with the additional columns. -By default the first column contains a timestamp for each row. The time -unit can be selected via the timestamp argument. + By default the first column contains a timestamp for each row. The time + unit can be selected via the timestamp argument. -:param *labels: (標籤) Any number of positional arguments, each corresponding to an entry in the log header. -:param timestamp: (時間戳記) Select the timestamp unit that will be automatically added as the first column in every row. Timestamp values can be one of ``log.MILLISECONDS``, ``log.SECONDS``, ``log.MINUTES``, ``log.HOURS``, ``log.DAYS`` or ``None`` to disable the timestamp. The default value is ``log.SECONDS``.""" + :param *labels: Any number of positional arguments, each corresponding to an entry in the log header. + :param timestamp: Select the timestamp unit that will be automatically added as the first column in every row. Timestamp values can be one of ``log.MILLISECONDS``, ``log.SECONDS``, ``log.MINUTES``, ``log.HOURS``, ``log.DAYS`` or ``None`` to disable the timestamp. The default value is ``log.SECONDS``. + """ ... @overload -def add(data_dictionary: Optional[Mapping[str, Union[str, int, float]]]) -> None: - """透過傳遞包含標頭和數值的字典,將資料列新增至紀錄中。 +def add( + data_dictionary: Optional[Mapping[str, Union[str, int, float]]], +) -> None: + """Add a data row to the log by passing a dictionary of headers and values. -Example: ``log.add({ 'temp': temperature() })`` + Example: ``log.add({ 'temp': temperature() })`` -Each call to this function adds a row to the log. + Each call to this function adds a row to the log. -New labels not previously specified via the set_labels function, or by a -previous call to this function, will trigger a new header entry to be added -to the log with the extra labels. + New labels not previously specified via the set_labels function, or by a + previous call to this function, will trigger a new header entry to be added + to the log with the extra labels. -Labels previously specified and not present in a call to this function will -be skipped with an empty value in the log row. + Labels previously specified and not present in a call to this function will + be skipped with an empty value in the log row. -:param data_dictionary: (資料字典) The data to log as a dictionary with a key for each header.""" + :param data_dictionary: The data to log as a dictionary with a key for each header. + """ ... @overload def add(**kwargs: Union[str, int, float]) -> None: - """使用關鍵字引數,將資料列新增至紀錄中。 + """Add a data row to the log using keyword arguments. -Example: ``log.add(temp=temperature())`` + Example: ``log.add(temp=temperature())`` -Each call to this function adds a row to the log. + Each call to this function adds a row to the log. -New labels not previously specified via the set_labels function, or by a -previous call to this function, will trigger a new header entry to be added -to the log with the extra labels. + New labels not previously specified via the set_labels function, or by a + previous call to this function, will trigger a new header entry to be added + to the log with the extra labels. -Labels previously specified and not present in a call to this function will -be skipped with an empty value in the log row.""" + Labels previously specified and not present in a call to this function will + be skipped with an empty value in the log row. + """ ... def delete(full=False): - """刪除紀錄的內容,包括標題。 + """Deletes the contents of the log, including headers. -Example: ``log.delete()`` + Example: ``log.delete()`` -To add the log headers again the ``set_labels`` function should to be called after this function. + To add the log headers again the ``set_labels`` function should to be called after this function. -There are two erase modes; “full” completely removes the data from the physical storage, -and “fast” invalidates the data without removing it. + There are two erase modes; “full” completely removes the data from the physical storage, + and “fast” invalidates the data without removing it. -:param full: ``True`` selects a “full” erase and ``False`` selects the “fast” erase method.""" + :param full: ``True`` selects a “full” erase and ``False`` selects the “fast” erase method. + """ ... def set_mirroring(serial: bool): """Configure mirroring of the data logging activity to the serial output. -Example: ``log.set_mirroring(True)`` + Example: ``log.set_mirroring(True)`` -Serial mirroring is disabled by default. When enabled, it will print to serial each row logged into the log file. + Serial mirroring is disabled by default. When enabled, it will print to serial each row logged into the log file. -:param serial: ``True`` enables mirroring data to the serial output.""" - ... \ No newline at end of file + :param serial: ``True`` enables mirroring data to the serial output. + """ + ... diff --git a/lang/zh-tw/typeshed/stdlib/machine.pyi b/lang/zh-tw/typeshed/stdlib/machine.pyi index 77a54b5..2e82f5b 100644 --- a/lang/zh-tw/typeshed/stdlib/machine.pyi +++ b/lang/zh-tw/typeshed/stdlib/machine.pyi @@ -1,84 +1,97 @@ -"""低階公用程式。""" +"""Low-level utilities. +""" from typing import Any from .microbit import MicroBitDigitalPin def unique_id() -> bytes: - """取得具有開發板的唯一識別碼之位元組字串。 + """Get a byte string with a unique identifier of a board. -Example: ``machine.unique_id()`` + Example: ``machine.unique_id()`` -:return: An identifier that varies from one board instance to another.""" + :return: An identifier that varies from one board instance to another. + """ ... def reset() -> None: - """以類似於按下外部 RESET 按鍵的方式重置裝置。 + """Reset the device in a manner similar to pushing the external RESET button. -Example: ``machine.reset()``""" + Example: ``machine.reset()`` + """ ... def freq() -> int: - """取得以赫茲為單位的 CPU 頻率。 (頻率) + """Get the CPU frequency in hertz. -Example: ``machine.freq()`` + Example: ``machine.freq()`` -:return: The CPU frequency.""" + :return: The CPU frequency. + """ ... def disable_irq() -> Any: - """禁用中斷請求。 (禁用 irq) + """Disable interrupt requests. -Example: ``interrupt_state = machine.disable_irq()`` + Example: ``interrupt_state = machine.disable_irq()`` -:return: the previous IRQ state which should be considered an opaque value + :return: the previous IRQ state which should be considered an opaque value -The return value should be passed to the ``enable_irq`` function to restore -interrupts to their original state.""" + The return value should be passed to the ``enable_irq`` function to restore + interrupts to their original state. + """ ... def enable_irq(state: Any) -> None: - """重新啟用中斷請求。 (啟用 irq) + """Re-enable interrupt requests. -Example: ``machine.enable_irq(interrupt_state)`` + Example: ``machine.enable_irq(interrupt_state)`` -:param state: 從最近一次調用 ``disable_irq`` 函式傳回的值。""" + :param state: The value that was returned from the most recent call to the ``disable_irq`` function. + """ ... -def time_pulse_us(pin: MicroBitDigitalPin, pulse_level: int, timeout_us: int=1000000) -> int: - """計時引腳上的脈衝。 +def time_pulse_us( + pin: MicroBitDigitalPin, pulse_level: int, timeout_us: int = 1000000 +) -> int: + """Time a pulse on a pin. -Example: ``time_pulse_us(pin0, 1)`` + Example: ``time_pulse_us(pin0, 1)`` -If the current input value of the pin is different to ``pulse_level``, the -function first waits until the pin input becomes equal to -``pulse_level``, then times the duration that the pin is equal to -``pulse_level``. If the pin is already equal to ``pulse_level`` then timing -starts straight away. + If the current input value of the pin is different to ``pulse_level``, the + function first waits until the pin input becomes equal to + ``pulse_level``, then times the duration that the pin is equal to + ``pulse_level``. If the pin is already equal to ``pulse_level`` then timing + starts straight away. -:param pin: (引腳) 要使用的引腳 -:param pulse_level: 0 到計時低脈衝或 1 到計時高脈衝 -:param timeout_us: 微秒逾時 -:return: The duration of the pulse in microseconds, or -1 for a timeout waiting for the level to match ``pulse_level``, or -2 on timeout waiting for the pulse to end""" + :param pin: The pin to use + :param pulse_level: 0 to time a low pulse or 1 to time a high pulse + :param timeout_us: A microsecond timeout + :return: The duration of the pulse in microseconds, or -1 for a timeout waiting for the level to match ``pulse_level``, or -2 on timeout waiting for the pulse to end + """ ... class mem: - """``mem8``、``mem16`` 和 ``mem32`` 記憶體檢視的類別。""" + """The class for the ``mem8``, ``mem16`` and ``mem32`` memory views.""" def __getitem__(self, address: int) -> int: - """從記憶體中存取一個值。 + """Access a value from memory. -:param address: 記憶體位址。 -:return: The value at that address as an integer.""" + :param address: The memory address. + :return: The value at that address as an integer. + """ ... - def __setitem__(self, address: int, value: int) -> None: - """在指定位址設定一個值。 + """Set a value at the given address. -:param address: 記憶體位址。 -:param value: 要設定的整數值。""" + :param address: The memory address. + :param value: The integer value to set. + """ ... + mem8: mem -"""8 位元 (位元組) 的記憶體檢視。""" +"""8-bit (byte) view of memory.""" + mem16: mem -"""16 位元的記憶體檢視。""" +"""16-bit view of memory.""" + mem32: mem -"""32 位元的記憶體檢視。""" \ No newline at end of file +"""32-bit view of memory.""" diff --git a/lang/zh-tw/typeshed/stdlib/math.pyi b/lang/zh-tw/typeshed/stdlib/math.pyi index c4117a7..f82d4de 100644 --- a/lang/zh-tw/typeshed/stdlib/math.pyi +++ b/lang/zh-tw/typeshed/stdlib/math.pyi @@ -1,246 +1,273 @@ -"""數學函式。""" +"""Mathematical functions. +""" + from typing import Tuple def acos(x: float) -> float: - """計算反餘弦。 + """Calculate the inverse cosine. -Example: ``math.acos(1)`` + Example: ``math.acos(1)`` -:param x: 一個數字 -:return: The inverse cosine of ``x``""" + :param x: A number + :return: The inverse cosine of ``x`` + """ ... def asin(x: float) -> float: - """計算反正弦。 + """Calculate the inverse sine. -Example: ``math.asin(0)`` + Example: ``math.asin(0)`` -:param x: 一個數字 -:return: The inverse sine of ``x``""" + :param x: A number + :return: The inverse sine of ``x`` + """ ... def atan(x: float) -> float: - """計算反正切。 + """Calculate the inverse tangent. -Example: ``math.atan(0)`` + Example: ``math.atan(0)`` -:param x: 一個數字 -:return: The inverse tangent of ``x``""" + :param x: A number + :return: The inverse tangent of ``x`` + """ ... def atan2(y: float, x: float) -> float: - """計算 ``y/x`` 的反正切主值。 + """Calculate the principal value of the inverse tangent of ``y/x``. -Example: ``math.atan2(0, -1)`` + Example: ``math.atan2(0, -1)`` -:param y: 一個數字 -:param x: 一個數字 -:return: The principal value of the inverse tangent of ``y/x``""" + :param y: A number + :param x: A number + :return: The principal value of the inverse tangent of ``y/x`` + """ ... def ceil(x: float) -> float: - """將數字向正無限大捨入。 + """Round a number towards positive infinity. -Example: ``math.ceil(0.1)`` + Example: ``math.ceil(0.1)`` -:param x: 一個數字 -:return: ``x`` rounded towards positive infinity.""" + :param x: A number + :return: ``x`` rounded towards positive infinity. + """ ... def copysign(x: float, y: float) -> float: - """用 ``y`` 的符號計算 ``x``。 + """Calculate ``x`` with the sign of ``y``. -Example: ``math.copysign(1, -1)`` + Example: ``math.copysign(1, -1)`` -:param x: 一個數字 -:param y: 傳回值的符號來源 -:return: ``x`` with the sign of ``y``""" + :param x: A number + :param y: The source of the sign for the return value + :return: ``x`` with the sign of ``y`` + """ ... def cos(x: float) -> float: - """計算 ``x`` 的餘弦。 + """Calculate the cosine of ``x``. -Example: ``math.cos(0)`` + Example: ``math.cos(0)`` -:param x: 一個數字 -:return: The cosine of ``x``""" + :param x: A number + :return: The cosine of ``x`` + """ ... def degrees(x: float) -> float: - """將弧度 (Radians) 轉換為度 (Degrees) (度) + """Convert radians to degrees. -Example: ``math.degrees(2 * math.pi)`` + Example: ``math.degrees(2 * math.pi)`` -:param x: 單位為弧度的數值 -:return: The value converted to degrees""" + :param x: A value in radians + :return: The value converted to degrees""" ... def exp(x: float) -> float: - """計算 ``x`` 的指數。 (指數) + """Calculate the exponential of ``x``. -Example: ``math.exp(1)`` + Example: ``math.exp(1)`` -:param x: 一個數字 -:return: The exponential of ``x``.""" + :param x: A number + :return: The exponential of ``x``. + """ ... def fabs(x: float) -> float: - """傳回 ``x`` 的絕對值。 + """Return the absolute value of ``x``. -Example: ``math.fabs(-0.1)`` + Example: ``math.fabs(-0.1)`` -:param x: 一個數字 -:return: The absolute value of ``x``""" + :param x: A number + :return: The absolute value of ``x`` + """ ... def floor(x: float) -> int: - """將數字向負無限大捨入。 + """Round a number towards negative infinity. -Example: ``math.floor(0.9)`` + Example: ``math.floor(0.9)`` -:param x: 一個數字 -:return: ``x`` rounded towards negative infinity.""" + :param x: A number + :return: ``x`` rounded towards negative infinity. + """ ... def fmod(x: float, y: float) -> float: - """計算 ``x/y`` 的餘數。 + """Calculate the remainder of ``x/y``. -Example: ``math.fmod(10, 3)`` + Example: ``math.fmod(10, 3)`` -:param x: 分子 -:param y: 分母""" + :param x: The numerator + :param y: The denominator + """ ... def frexp(x: float) -> Tuple[float, int]: - """將一個浮點數分解為其尾數和指數。 + """Decomposes a floating-point number into its mantissa and exponent. -Example: ``mantissa, exponent = math.frexp(2)`` + Example: ``mantissa, exponent = math.frexp(2)`` -The returned value is the tuple ``(m, e)`` such that ``x == m * 2**e`` -exactly. If ``x == 0`` then the function returns ``(0.0, 0)``, otherwise -the relation ``0.5 <= abs(m) < 1`` holds. + The returned value is the tuple ``(m, e)`` such that ``x == m * 2**e`` + exactly. If ``x == 0`` then the function returns ``(0.0, 0)``, otherwise + the relation ``0.5 <= abs(m) < 1`` holds. -:param x: 一個浮點數 -:return: A tuple of length two containing its mantissa then exponent""" + :param x: A floating-point number + :return: A tuple of length two containing its mantissa then exponent + """ ... def isfinite(x: float) -> bool: - """檢查值是否為有限。 + """Check if a value is finite. -Example: ``math.isfinite(float('inf'))`` + Example: ``math.isfinite(float('inf'))`` -:param x: 一個數字。 -:return: ``True`` if ``x`` is finite, ``False`` otherwise.""" + :param x: A number. + :return: ``True`` if ``x`` is finite, ``False`` otherwise. + """ ... def isinf(x: float) -> bool: - """檢查值是否為無限。 + """Check if a value is infinite. -Example: ``math.isinf(float('-inf'))`` + Example: ``math.isinf(float('-inf'))`` -:param x: 一個數字。 -:return: ``True`` if ``x`` is infinite, ``False`` otherwise.""" + :param x: A number. + :return: ``True`` if ``x`` is infinite, ``False`` otherwise. + """ ... def isnan(x: float) -> bool: - """檢查值是否為非數字 (NaN)。 + """Check if a value is not-a-number (NaN). -Example: ``math.isnan(float('nan'))`` + Example: ``math.isnan(float('nan'))`` -:param x: 一個數字 -:return: ``True`` if ``x`` is not-a-number (NaN), ``False`` otherwise.""" + :param x: A number + :return: ``True`` if ``x`` is not-a-number (NaN), ``False`` otherwise.""" ... def ldexp(x: float, exp: int) -> float: - """計算 ``x * (2**exp)``。 + """Calculate ``x * (2**exp)``. -Example: ``math.ldexp(0.5, 2)`` + Example: ``math.ldexp(0.5, 2)`` -:param x: 一個數字 -:param exp: (指數) 整數指數 -:return: ``x * (2**exp)``""" + :param x: A number + :param exp: Integer exponent + :return: ``x * (2**exp)`` + """ ... -def log(x: float, base: float=e) -> float: - """計算指定底數 ``x`` 的對數 (預設為自然對數)。 +def log(x: float, base: float = e) -> float: + """Calculate the logarithm of ``x`` to the given base (defaults to natural logorithm). -Example: ``math.log(math.e)`` + Example: ``math.log(math.e)`` -With one argument, return the natural logarithm of x (to base e). + With one argument, return the natural logarithm of x (to base e). -With two arguments, return the logarithm of x to the given base, calculated as ``log(x)/log(base)``. + With two arguments, return the logarithm of x to the given base, calculated as ``log(x)/log(base)``. -:param x: 一個數字 -:param base: 要使用的底數 -:return: The natural logarithm of ``x``""" + :param x: A number + :param base: The base to use + :return: The natural logarithm of ``x`` + """ ... def modf(x: float) -> Tuple[float, float]: - """計算 ``x`` 的小數部分和整數部分。 + """Calculate the fractional and integral parts of ``x``. -Example: ``fractional, integral = math.modf(1.5)`` + Example: ``fractional, integral = math.modf(1.5)`` -:param x: 一個數字 -:return: A tuple of two floats representing the fractional then integral parts of ``x``. + :param x: A number + :return: A tuple of two floats representing the fractional then integral parts of ``x``. -Both the fractional and integral values have the same sign as ``x``.""" + Both the fractional and integral values have the same sign as ``x``. + """ ... def pow(x: float, y: float) -> float: - """傳回 ``x`` 的 ``y`` 次方。 + """Returns ``x`` to the power of ``y``. -Example: ``math.pow(4, 0.5)`` + Example: ``math.pow(4, 0.5)`` -:param x: 一個數字 -:param y: 指數 -:return: ``x`` to the power of ``y``""" + :param x: A number + :param y: The exponent + :return: ``x`` to the power of ``y`` + """ ... def radians(x: float) -> float: - """將角度轉換為弧度。 + """Convert a degrees to radians. -Example: ``math.radians(360)`` + Example: ``math.radians(360)`` -:param x: 以角度為單位的值 -:return: The value converted to radians""" + :param x: A value in degrees + :return: The value converted to radians + """ ... def sin(x: float) -> float: - """計算 ``x`` 的正弦。 + """Calculate the sine of ``x``. -Example: ``math.sin(math.pi/2)`` + Example: ``math.sin(math.pi/2)`` -:param x: 一個數字 -:return: The sine of ``x``""" + :param x: A number + :return: The sine of ``x`` + """ ... def sqrt(x: float) -> float: - """計算 ``x`` 的平方根。 + """Calculate the square root of ``x``. -Example: ``math.sqrt(4)`` + Example: ``math.sqrt(4)`` -:param x: 一個數字 -:return: The square root of ``x``""" + :param x: A number + :return: The square root of ``x`` + """ ... def tan(x: float) -> float: - """計算 ``x`` 的正切。 + """Calculate the tangent of ``x``. -Example: ``math.tan(0)`` + Example: ``math.tan(0)`` -:param x: 一個數字 -:return: The tangent of ``x``.""" + :param x: A number + :return: The tangent of ``x``. + """ ... def trunc(x: float) -> int: - """將數字向 0 捨入。 + """Round a number towards 0. -Example: ``math.trunc(-0.9)`` + Example: ``math.trunc(-0.9)`` -:param x: 一個數字 -:return: ``x`` rounded towards zero.""" + :param x: A number + :return: ``x`` rounded towards zero. + """ ... + e: float -"""自然對數的底數""" +"""Base of the natural logarithm""" + pi: float -"""圓的周長與其直徑的比率""" \ No newline at end of file +"""The ratio of a circle's circumference to its diameter""" diff --git a/lang/zh-tw/typeshed/stdlib/microbit/__init__.pyi b/lang/zh-tw/typeshed/stdlib/microbit/__init__.pyi index 0e2e313..f12158f 100644 --- a/lang/zh-tw/typeshed/stdlib/microbit/__init__.pyi +++ b/lang/zh-tw/typeshed/stdlib/microbit/__init__.pyi @@ -1,6 +1,11 @@ -"""引腳、影像、聲音、溫度和音量。""" +"""Pins, images, sounds, temperature and volume. +""" + from typing import Any, Callable, List, Optional, Tuple, Union, overload + from _typeshed import ReadableBuffer + +# V2 only from . import accelerometer as accelerometer from . import audio as audio from . import compass as compass @@ -11,696 +16,831 @@ from . import speaker as speaker from . import spi as spi from . import uart as uart -def run_every(callback: Optional[Callable[[], None]]=None, days: int=0, h: int=0, min: int=0, s: int=0, ms: int=0) -> Callable[[Callable[[], None]], Callable[[], None]]: +def run_every( + callback: Optional[Callable[[], None]] = None, + days: int = 0, + h: int = 0, + min: int = 0, + s: int = 0, + ms: int = 0, +) -> Callable[[Callable[[], None]], Callable[[], None]]: """Schedule to run a function at the interval specified by the time arguments **V2 only**. -Example: ``run_every(my_logging, min=5)`` + Example: ``run_every(my_logging, min=5)`` -``run_every`` can be used in two ways: + ``run_every`` can be used in two ways: -As a Decorator - placed on top of the function to schedule. For example:: + As a Decorator - placed on top of the function to schedule. For example:: - @run_every(h=1, min=20, s=30, ms=50) - def my_function(): - # Do something here + @run_every(h=1, min=20, s=30, ms=50) + def my_function(): + # Do something here -As a Function - passing the callback as a positional argument. For example:: + As a Function - passing the callback as a positional argument. For example:: - def my_function(): - # Do something here - run_every(my_function, s=30) + def my_function(): + # Do something here + run_every(my_function, s=30) -Each argument corresponds to a different time unit and they are additive. -So ``run_every(min=1, s=30)`` schedules the callback every minute and a half. + Each argument corresponds to a different time unit and they are additive. + So ``run_every(min=1, s=30)`` schedules the callback every minute and a half. -When an exception is thrown inside the callback function it deschedules the -function. To avoid this you can catch exceptions with ``try/except``. + When an exception is thrown inside the callback function it deschedules the + function. To avoid this you can catch exceptions with ``try/except``. -:param callback: Function to call at the provided interval. Omit when using as a decorator. -:param days: Sets the day mark for the scheduling. -:param h: Sets the hour mark for the scheduling. -:param min: Sets the minute mark for the scheduling. -:param s: Sets the second mark for the scheduling. -:param ms: Sets the millisecond mark for the scheduling.""" + :param callback: Function to call at the provided interval. Omit when using as a decorator. + :param days: Sets the day mark for the scheduling. + :param h: Sets the hour mark for the scheduling. + :param min: Sets the minute mark for the scheduling. + :param s: Sets the second mark for the scheduling. + :param ms: Sets the millisecond mark for the scheduling. + """ def panic(n: int) -> None: - """進入緊急模式。 + """Enter a panic mode. -Example: ``panic(127)`` + Example: ``panic(127)`` -:param n: 任意整數 <= 255 以表示狀態。 + :param n: An arbitrary integer <= 255 to indicate a status. -Requires restart.""" + Requires restart. + """ def reset() -> None: - """重啟開發板。""" + """Restart the board.""" + @overload def scale(value: float, from_: Tuple[float, float], to: Tuple[int, int]) -> int: """Converts a value from a range to an integer range. -Example: ``volume = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255))`` + Example: ``volume = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255))`` -For example, to convert an accelerometer X value to a speaker volume. + For example, to convert an accelerometer X value to a speaker volume. -If one of the numbers in the ``to`` parameter is a floating point -(i.e a decimal number like ``10.0``), this function will return a -floating point number. + If one of the numbers in the ``to`` parameter is a floating point + (i.e a decimal number like ``10.0``), this function will return a + floating point number. - temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0)) + temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0)) -:param value: A number to convert. -:param from_: A tuple to define the range to convert from. -:param to: A tuple to define the range to convert to. -:return: The ``value`` converted to the ``to`` range.""" + :param value: A number to convert. + :param from_: A tuple to define the range to convert from. + :param to: A tuple to define the range to convert to. + :return: The ``value`` converted to the ``to`` range. + """ @overload def scale(value: float, from_: Tuple[float, float], to: Tuple[float, float]) -> float: """Converts a value from a range to a floating point range. -Example: ``temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0))`` + Example: ``temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0))`` -For example, to convert temperature from a Celsius scale to Fahrenheit. + For example, to convert temperature from a Celsius scale to Fahrenheit. -If one of the numbers in the ``to`` parameter is a floating point -(i.e a decimal number like ``10.0``), this function will return a -floating point number. -If they are both integers (i.e ``10``), it will return an integer:: + If one of the numbers in the ``to`` parameter is a floating point + (i.e a decimal number like ``10.0``), this function will return a + floating point number. + If they are both integers (i.e ``10``), it will return an integer:: - returns_int = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255)) + returns_int = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255)) -:param value: A number to convert. -:param from_: A tuple to define the range to convert from. -:param to: A tuple to define the range to convert to. -:return: The ``value`` converted to the ``to`` range.""" + :param value: A number to convert. + :param from_: A tuple to define the range to convert from. + :param to: A tuple to define the range to convert to. + :return: The ``value`` converted to the ``to`` range. + """ def sleep(n: float) -> None: - """等待 ``n`` 毫秒。 + """Wait for ``n`` milliseconds. -Example: ``sleep(1000)`` + Example: ``sleep(1000)`` -:param n: 要等待的毫秒數。 + :param n: The number of milliseconds to wait -One second is 1000 milliseconds, so:: + One second is 1000 milliseconds, so:: - microbit.sleep(1000) + microbit.sleep(1000) -will pause the execution for one second.""" + will pause the execution for one second. + """ def running_time() -> int: - """取得開發板的執行時間。 + """Get the running time of the board. -:return: The number of milliseconds since the board was switched on or restarted.""" + :return: The number of milliseconds since the board was switched on or restarted. + """ def temperature() -> int: - """取得 micro:bit 的溫度 (以攝氏為單位)。 (溫度)""" + """Get the temperature of the micro:bit in degrees Celsius.""" def set_volume(v: int) -> None: - """設定音量。 + """Sets the volume. -Example: ``set_volume(127)`` + Example: ``set_volume(127)`` -:param v: 介於 0 (低) 和 255 (高) 之間的值。 + :param v: a value between 0 (low) and 255 (high). -Out of range values will be clamped to 0 or 255. + Out of range values will be clamped to 0 or 255. -**V2** only.""" + **V2** only. + """ ... class Button: - """按鈕 ``button_a`` 和 ``button_b`` 的類別。""" + """The class for the buttons ``button_a`` and ``button_b``.""" def is_pressed(self) -> bool: - """檢查按鈕是否有按下。 + """Check if the button is pressed. -:return: ``True`` if the specified button ``button`` is pressed, and ``False`` otherwise.""" + :return: ``True`` if the specified button ``button`` is pressed, and ``False`` otherwise. + """ ... - def was_pressed(self) -> bool: - """檢查自裝置啟動或上次呼叫此方法以來,是否有按下該按鈕。 + """Check if the button was pressed since the device started or the last time this method was called. -Calling this method will clear the press state so -that the button must be pressed again before this method will return -``True`` again. + Calling this method will clear the press state so + that the button must be pressed again before this method will return + ``True`` again. -:return: ``True`` if the specified button ``button`` was pressed, and ``False`` otherwise""" + :return: ``True`` if the specified button ``button`` was pressed, and ``False`` otherwise + """ ... - def get_presses(self) -> int: - """取得按下按鈕的執行總數,並在傳回前將此總數重設為零。 + """Get the running total of button presses, and resets this total + to zero before returning. -:return: The number of presses since the device started or the last time this method was called""" + :return: The number of presses since the device started or the last time this method was called + """ ... + button_a: Button -"""左側按鈕 ``Button`` 物件。""" +"""The left button ``Button`` object.""" + button_b: Button -"""右側按鈕 ``Button`` 物件。""" +"""The right button ``Button`` object.""" class MicroBitDigitalPin: - """數位引腳。 + """A digital pin. + + Some pins support analog and touch features using the ``MicroBitAnalogDigitalPin`` and ``MicroBitTouchPin`` subclasses. + """ -Some pins support analog and touch features using the ``MicroBitAnalogDigitalPin`` and ``MicroBitTouchPin`` subclasses.""" NO_PULL: int PULL_UP: int PULL_DOWN: int - def read_digital(self) -> int: - """取得引腳的數位值。 + """Get the digital value of the pin. -Example: ``value = pin0.read_digital()`` + Example: ``value = pin0.read_digital()`` -:return: 1 if the pin is high, and 0 if it's low.""" + :return: 1 if the pin is high, and 0 if it's low. + """ ... - def write_digital(self, value: int) -> None: - """設定引腳的數位值。 + """Set the digital value of the pin. -Example: ``pin0.write_digital(1)`` + Example: ``pin0.write_digital(1)`` -:param value: 1 將引腳設為高電平,或 0 將引腳設為低電平""" + :param value: 1 to set the pin high or 0 to set the pin low""" ... - def set_pull(self, value: int) -> None: - """將提取狀態設為三個可能值之一:``PULL_UP``、``PULL_DOWN`` 或 ``NO_PULL``。 + """Set the pull state to one of three possible values: ``PULL_UP``, ``PULL_DOWN`` or ``NO_PULL``. -Example: ``pin0.set_pull(pin0.PULL_UP)`` + Example: ``pin0.set_pull(pin0.PULL_UP)`` -:param value: 相關引腳的提取狀態,例如 ``pin0.PULL_UP``。""" + :param value: The pull state from the relevant pin, e.g. ``pin0.PULL_UP``. + """ ... - def get_pull(self) -> int: - """取得引腳上的提取狀態。 + """Get the pull state on a pin. -Example: ``pin0.get_pull()`` + Example: ``pin0.get_pull()`` -:return: ``NO_PULL``, ``PULL_DOWN``, or ``PULL_UP`` + :return: ``NO_PULL``, ``PULL_DOWN``, or ``PULL_UP`` -These are set using the ``set_pull()`` method or automatically configured -when a pin mode requires it.""" + These are set using the ``set_pull()`` method or automatically configured + when a pin mode requires it. + """ ... - def get_mode(self) -> str: - """傳回引腳模式。 + """Returns the pin mode. -Example: ``pin0.get_mode()`` + Example: ``pin0.get_mode()`` -When a pin is used for a specific function, like -writing a digital value, or reading an analog value, the pin mode -changes. + When a pin is used for a specific function, like + writing a digital value, or reading an analog value, the pin mode + changes. -:return: ``"unused"``, ``"analog"``, ``"read_digital"``, ``"write_digital"``, ``"display"``, ``"button"``, ``"music"``, ``"audio"``, ``"touch"``, ``"i2c"``, or ``"spi"``""" + :return: ``"unused"``, ``"analog"``, ``"read_digital"``, ``"write_digital"``, ``"display"``, ``"button"``, ``"music"``, ``"audio"``, ``"touch"``, ``"i2c"``, or ``"spi"`` + """ ... - def write_analog(self, value: int) -> None: - """在引腳上輸出 PWM 訊號,工作週期與 ``value`` 成正比。 - -Example: ``pin0.write_analog(254)`` + """Output a PWM signal on the pin, with the duty cycle proportional to ``value``. -:param value: 介於 0 (0% 工作週期) 和 1023 (100% 工作週期) 之間的整數或浮點數。""" + Example: ``pin0.write_analog(254)`` + :param value: An integer or a floating point number between 0 (0% duty cycle) and 1023 (100% duty). + """ def set_analog_period(self, period: int) -> None: - """將輸出的 PWM 訊號週期設為 ``period`` (以毫秒為單位)。 + """Set the period of the PWM signal being output to ``period`` in milliseconds. -Example: ``pin0.set_analog_period(10)`` - -:param period: 以毫秒為單位的週期,最小有效值為 1ms。""" + Example: ``pin0.set_analog_period(10)`` + :param period: The period in milliseconds with a minimum valid value of 1ms. + """ def set_analog_period_microseconds(self, period: int) -> None: - """將輸出的 PWM 訊號週期設為 ``period`` (以微秒為單位)。 + """Set the period of the PWM signal being output to ``period`` in microseconds. -Example: ``pin0.set_analog_period_microseconds(512)`` + Example: ``pin0.set_analog_period_microseconds(512)`` -:param period: 以微秒為單位的週期,最小有效值為 256µs。""" + :param period: The period in microseconds with a minimum valid value of 256µs. + """ class MicroBitAnalogDigitalPin(MicroBitDigitalPin): - """具有類比和數位功能的引腳。""" + """A pin with analog and digital features.""" def read_analog(self) -> int: - """讀取施加到引腳的電壓。 + """Read the voltage applied to the pin. -Example: ``pin0.read_analog()`` + Example: ``pin0.read_analog()`` -:return: An integer between 0 (meaning 0V) and 1023 (meaning 3.3V).""" + :return: An integer between 0 (meaning 0V) and 1023 (meaning 3.3V). + """ class MicroBitTouchPin(MicroBitAnalogDigitalPin): - """具有類比、數位和觸控功能的引腳。""" + """A pin with analog, digital and touch features.""" + CAPACITIVE: int RESISTIVE: int - def is_touched(self) -> bool: - """檢查引腳是否受觸控。 + """Check if the pin is being touched. -Example: ``pin0.is_touched()`` + Example: ``pin0.is_touched()`` -The default touch mode for the pins on the edge connector is ``resistive``. -The default for the logo pin **V2** is ``capacitive``. + The default touch mode for the pins on the edge connector is ``resistive``. + The default for the logo pin **V2** is ``capacitive``. -**Resistive touch** -This test is done by measuring how much resistance there is between the -pin and ground. A low resistance gives a reading of ``True``. To get -a reliable reading using a finger you may need to touch the ground pin -with another part of your body, for example your other hand. + **Resistive touch** + This test is done by measuring how much resistance there is between the + pin and ground. A low resistance gives a reading of ``True``. To get + a reliable reading using a finger you may need to touch the ground pin + with another part of your body, for example your other hand. -**Capacitive touch** -This test is done by interacting with the electric field of a capacitor -using a finger as a conductor. `Capacitive touch -`_ -does not require you to make a ground connection as part of a circuit. + **Capacitive touch** + This test is done by interacting with the electric field of a capacitor + using a finger as a conductor. `Capacitive touch + `_ + does not require you to make a ground connection as part of a circuit. -:return: ``True`` if the pin is being touched with a finger, otherwise return ``False``.""" + :return: ``True`` if the pin is being touched with a finger, otherwise return ``False``. + """ ... - def set_touch_mode(self, value: int) -> None: - """設定引腳的觸控模式。 + """Set the touch mode for the pin. -Example: ``pin0.set_touch_mode(pin0.CAPACITIVE)`` + Example: ``pin0.set_touch_mode(pin0.CAPACITIVE)`` -The default touch mode for the pins on the edge connector is -``resistive``. The default for the logo pin **V2** is ``capacitive``. + The default touch mode for the pins on the edge connector is + ``resistive``. The default for the logo pin **V2** is ``capacitive``. -:param value: 相關引腳的 ``CAPACITIVE`` 或 ``RESISTIVE``。""" + :param value: ``CAPACITIVE`` or ``RESISTIVE`` from the relevant pin. + """ ... + pin0: MicroBitTouchPin -"""具有數位、類比和觸控功能的引腳。 (引腳 0)""" +"""Pin with digital, analog and touch features.""" + pin1: MicroBitTouchPin -"""具有數位、類比和觸控功能的引腳。 (引腳 1)""" +"""Pin with digital, analog and touch features.""" + pin2: MicroBitTouchPin -"""具有數位、類比和觸控功能的引腳。 (引腳 2)""" +"""Pin with digital, analog and touch features.""" + pin3: MicroBitAnalogDigitalPin -"""具有數位和類比功能的引腳。 (引腳 3)""" +"""Pin with digital and analog features.""" + pin4: MicroBitAnalogDigitalPin -"""具有數位和類比功能的引腳。 (引腳 4)""" +"""Pin with digital and analog features.""" + pin5: MicroBitDigitalPin -"""具有數位功能的引腳。 (引腳 5)""" +"""Pin with digital features.""" + pin6: MicroBitDigitalPin -"""具有數位功能的引腳。 (引腳 6)""" +"""Pin with digital features.""" + pin7: MicroBitDigitalPin -"""具有數位功能的引腳。 (引腳 7)""" +"""Pin with digital features.""" + pin8: MicroBitDigitalPin -"""具有數位功能的引腳。 (引腳 8)""" +"""Pin with digital features.""" + pin9: MicroBitDigitalPin -"""具有數位功能的引腳。 (引腳 9)""" +"""Pin with digital features.""" + pin10: MicroBitAnalogDigitalPin -"""具有數位和類比功能的引腳。 (引腳 10)""" +"""Pin with digital and analog features.""" + pin11: MicroBitDigitalPin -"""具有數位功能的引腳。 (引腳 11)""" +"""Pin with digital features.""" + pin12: MicroBitDigitalPin -"""具有數位功能的引腳。 (引腳 12)""" +"""Pin with digital features.""" + pin13: MicroBitDigitalPin -"""具有數位功能的引腳。 (引腳 13)""" +"""Pin with digital features.""" + pin14: MicroBitDigitalPin -"""具有數位功能的引腳。 (引腳 14)""" +"""Pin with digital features.""" + pin15: MicroBitDigitalPin -"""具有數位功能的引腳。 (引腳 15)""" +"""Pin with digital features.""" + pin16: MicroBitDigitalPin -"""具有數位功能的引腳。 (引腳 16)""" +"""Pin with digital features.""" + pin19: MicroBitDigitalPin -"""具有數位功能的引腳。 (引腳 19)""" +"""Pin with digital features.""" + pin20: MicroBitDigitalPin -"""具有數位功能的引腳。 (引腳 20)""" +"""Pin with digital features.""" + pin_logo: MicroBitTouchPin -"""micro:bit 正面的觸控感應標誌引腳,預設為電容式觸控模式。""" +"""A touch sensitive logo pin on the front of the micro:bit, which by default is set to capacitive touch mode.""" + pin_speaker: MicroBitAnalogDigitalPin -"""用於定址 micro:bit 揚聲器的引腳。 +"""A pin to address the micro:bit speaker. This API is intended only for use in Pulse-Width Modulation pin operations e.g. pin_speaker.write_analog(128). """ class Image: - """要在 micro:bit LED 顯示器上顯示的圖像。 (圖像) + """An image to show on the micro:bit LED display. -Given an image object it's possible to display it via the ``display`` API:: + Given an image object it's possible to display it via the ``display`` API:: + + display.show(Image.HAPPY) + """ - display.show(Image.HAPPY)""" HEART: Image - """愛心圖像。""" + """Heart image.""" + HEART_SMALL: Image - """小愛心圖像。""" + """Small heart image.""" + HAPPY: Image - """開心的臉圖像。 (開心)""" + """Happy face image.""" + SMILE: Image - """笑臉圖像。 (微笑)""" + """Smiling mouth image.""" + SAD: Image - """傷心的臉圖像。""" + """Sad face image.""" + CONFUSED: Image - """困惑的臉圖像。""" + """Confused face image.""" + ANGRY: Image - """生氣的臉圖像。""" + """Angry face image.""" + ASLEEP: Image - """睡臉圖像。""" + """Sleeping face image.""" + SURPRISED: Image - """驚訝的臉圖像。""" + """Surprised face image.""" + SILLY: Image - """鬼臉圖像。""" + """Silly face image.""" + FABULOUS: Image - """戴太陽眼鏡的臉圖像。""" + """Sunglasses face image.""" + MEH: Image - """冷漠的臉圖像。""" + """Unimpressed face image.""" + YES: Image - """勾號圖像。""" + """Tick image.""" + NO: Image - """叉號圖像。""" + """Cross image.""" + CLOCK12: Image - """指針指向 12 點鐘的圖像。""" + """Image with line pointing to 12 o'clock.""" + CLOCK11: Image - """指針指向 11 點鐘的圖像。""" + """Image with line pointing to 11 o'clock.""" + CLOCK10: Image - """指針指向 10 點鐘的圖像。""" + """Image with line pointing to 10 o'clock.""" + CLOCK9: Image - """指針指向 9 點鐘的圖像。""" + """Image with line pointing to 9 o'clock.""" + CLOCK8: Image - """指針指向 8 點鐘的圖像。""" + """Image with line pointing to 8 o'clock.""" + CLOCK7: Image - """指針指向 7 點鐘的圖像。""" + """Image with line pointing to 7 o'clock.""" + CLOCK6: Image - """指針指向 6 點鐘的圖像。""" + """Image with line pointing to 6 o'clock.""" + CLOCK5: Image - """指針指向 5 點鐘的圖像。""" + """Image with line pointing to 5 o'clock.""" + CLOCK4: Image - """指針指向 4 點鐘的圖像。""" + """Image with line pointing to 4 o'clock.""" + CLOCK3: Image - """指針指向 3 點鐘的圖像。""" + """Image with line pointing to 3 o'clock.""" + CLOCK2: Image - """指針指向 2 點鐘的圖像。""" + """Image with line pointing to 2 o'clock.""" + CLOCK1: Image - """指針指向 1 點鐘的圖像。""" + """Image with line pointing to 1 o'clock.""" + ARROW_N: Image - """指向北方箭頭的圖像。""" + """Image of arrow pointing north.""" + ARROW_NE: Image - """指向東北箭頭的圖像。""" + """Image of arrow pointing north east.""" + ARROW_E: Image - """指向東方箭頭的圖像。""" + """Image of arrow pointing east.""" + ARROW_SE: Image - """指向東南箭頭的圖像。""" + """Image of arrow pointing south east.""" + ARROW_S: Image - """指向南方箭頭的圖像。""" + """Image of arrow pointing south.""" + ARROW_SW: Image - """指向西南箭頭的圖像。""" + """Image of arrow pointing south west.""" + ARROW_W: Image - """指向西方箭頭的圖像。""" + """Image of arrow pointing west.""" + ARROW_NW: Image - """指向西北箭頭的圖像。""" + """Image of arrow pointing north west.""" + TRIANGLE: Image - """三角形朝上的圖像。""" + """Image of a triangle pointing up.""" + TRIANGLE_LEFT: Image - """三角形朝左的圖像。""" + """Image of a triangle in the left corner.""" + CHESSBOARD: Image - """以棋盤圖案交錯發亮的 LED 燈。""" + """Alternate LEDs lit in a chessboard pattern.""" + DIAMOND: Image - """鑽石圖像。""" + """Diamond image.""" + DIAMOND_SMALL: Image - """小鑽石圖像。""" + """Small diamond image.""" + SQUARE: Image - """正方形圖像。""" + """Square image.""" + SQUARE_SMALL: Image - """小正方形圖像。""" + """Small square image.""" + RABBIT: Image - """兔子圖像。""" + """Rabbit image.""" + COW: Image - """乳牛圖像。""" + """Cow image.""" + MUSIC_CROTCHET: Image - """四分音符圖像。""" + """Crotchet note image.""" + MUSIC_QUAVER: Image - """八分音符圖像。""" + """Quaver note image.""" + MUSIC_QUAVERS: Image - """一組八分音符圖像。""" + """Pair of quavers note image.""" + PITCHFORK: Image - """乾草叉圖像。""" + """Pitchfork image.""" + XMAS: Image - """聖誕樹圖像。""" + """Christmas tree image.""" + PACMAN: Image - """小精靈街機角色圖像。""" + """Pac-Man arcade character image.""" + TARGET: Image - """靶子圖像。""" + """Target image.""" + TSHIRT: Image - """T 恤圖像。""" + """T-shirt image.""" + ROLLERSKATE: Image - """輪式溜冰鞋圖像。""" + """Rollerskate image.""" + DUCK: Image - """鴨子圖像。""" + """Duck image.""" + HOUSE: Image - """房子圖像。""" + """House image.""" + TORTOISE: Image - """陸龜圖像。""" + """Tortoise image.""" + BUTTERFLY: Image - """蝴蝶圖像。""" + """Butterfly image.""" + STICKFIGURE: Image - """簡筆畫圖像。""" + """Stick figure image.""" + GHOST: Image - """幽靈圖像。""" + """Ghost image.""" + SWORD: Image - """劍圖像。""" + """Sword image.""" + GIRAFFE: Image - """長頸鹿圖像。""" + """Giraffe image.""" + SKULL: Image - """骷髏頭圖像""" + """Skull image.""" + UMBRELLA: Image - """雨傘圖像。""" + """Umbrella image.""" + SNAKE: Image - """蛇圖像。""" + """Snake image.""" + SCISSORS: Image """Scissors image.""" + ALL_CLOCKS: List[Image] - """按順序包含所有 CLOCK_圖像的列表。""" - ALL_ARROWS: List[Image] - """按順序包含所有 ARROW_圖像的列表。""" + """A list containing all the CLOCK_ images in sequence.""" + ALL_ARROWS: List[Image] + """A list containing all the ARROW_ images in sequence.""" @overload def __init__(self, string: str) -> None: - """從描述點亮哪些 LED 的字串建立圖像。 + """Create an image from a string describing which LEDs are lit. -``string`` has to consist of digits 0-9 arranged into lines, -describing the image, for example:: + ``string`` has to consist of digits 0-9 arranged into lines, + describing the image, for example:: - image = Image("90009:" - "09090:" - "00900:" - "09090:" - "90009") + 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 newlines (\\n) insead of the colons. + 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 newlines (\\n) insead of the colons. -:param string: 描述圖像的字串。""" + :param string: The string describing the image. + """ ... - @overload - def __init__(self, width: int=5, height: int=5, buffer: ReadableBuffer=None) -> None: - """建立一個 ``width`` 行 ``height`` 列的空白圖像。 + def __init__( + self, width: int = 5, height: int = 5, buffer: ReadableBuffer = None + ) -> None: + """Create an empty image with ``width`` columns and ``height`` rows. -:param width: 可選的圖像寬度 -:param height: 可選的圖像高度 -:param buffer: 用可選陣列或在 0-9 範圍內的 ``width``×``height`` 整數位元組,來初始化圖像 + :param width: Optional width of the image + :param height: Optional height of the image + :param buffer: Optional array or bytes of ``width``×``height`` integers in range 0-9 to initialize the image -Examples:: + Examples:: - Image(2, 2, b'\x08\x08\x08\x08') - Image(2, 2, bytearray([9,9,9,9])) + Image(2, 2, b'\x08\x08\x08\x08') + Image(2, 2, bytearray([9,9,9,9])) -These create 2 x 2 pixel images at full brightness.""" + These create 2 x 2 pixel images at full brightness. + """ ... - def width(self) -> int: - """取得行數。 + """Get the number of columns. -:return: The number of columns in the image""" + :return: The number of columns in the image + """ ... - def height(self) -> int: - """取得列數。 + """Get the number of rows. -:return: The number of rows in the image""" + :return: The number of rows in the image + """ ... - def set_pixel(self, x: int, y: int, value: int) -> None: - """設定像素的亮度。 + """Set the brightness of a pixel. -Example: ``my_image.set_pixel(0, 0, 9)`` + Example: ``my_image.set_pixel(0, 0, 9)`` -:param x: 行號 -:param y: 列號 -:param value: 亮度為介於 0 (暗) 和 9 (亮) 之間的整數 + :param x: The column number + :param y: The row number + :param value: The brightness as an integer 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``.""" + 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: - """取得像素的亮度。 + """Get the brightness of a pixel. -Example: ``my_image.get_pixel(0, 0)`` + Example: ``my_image.get_pixel(0, 0)`` -:param x: 行號 -:param y: 列號 -:return: The brightness as an integer between 0 and 9.""" + :param x: The column number + :param y: The row number + :return: The brightness as an integer between 0 and 9. + """ ... - def shift_left(self, n: int) -> Image: - """向左移動圖像,以建立新圖像。 + """Create a new image by shifting the picture left. -Example: ``Image.HEART_SMALL.shift_left(1)`` + Example: ``Image.HEART_SMALL.shift_left(1)`` -:param n: 要移動的行數 -:return: The shifted image""" + :param n: The number of columns to shift by + :return: The shifted image + """ ... - def shift_right(self, n: int) -> Image: - """向右移動圖像,以建立新圖像。 + """Create a new image by shifting the picture right. -Example: ``Image.HEART_SMALL.shift_right(1)`` + Example: ``Image.HEART_SMALL.shift_right(1)`` -:param n: 要移動的行數 -:return: The shifted image""" + :param n: The number of columns to shift by + :return: The shifted image + """ ... - def shift_up(self, n: int) -> Image: - """向上移動圖像,以建立新圖像。 + """Create a new image by shifting the picture up. -Example: ``Image.HEART_SMALL.shift_up(1)`` + Example: ``Image.HEART_SMALL.shift_up(1)`` -:param n: 要移動的列數 -:return: The shifted image""" + :param n: The number of rows to shift by + :return: The shifted image + """ ... - def shift_down(self, n: int) -> Image: - """透過向下移動圖像,以建立一個新圖像。 + """Create a new image by shifting the picture down. -Example: ``Image.HEART_SMALL.shift_down(1)`` + Example: ``Image.HEART_SMALL.shift_down(1)`` -:param n: 要移動的列數 -:return: The shifted image""" + :param n: The number of rows to shift by + :return: The shifted image + """ ... - def crop(self, x: int, y: int, w: int, h: int) -> Image: - """透過裁剪圖像,以建立一個新圖像。 + """Create a new image by cropping the picture. -Example: ``Image.HEART.crop(1, 1, 3, 3)`` + Example: ``Image.HEART.crop(1, 1, 3, 3)`` -:param x: 裁剪位移行 -:param y: 裁剪位移列 -:param w: 剪裁寬度 -:param h: 剪裁高度 -:return: The new image""" + :param x: The crop offset column + :param y: The crop offset row + :param w: The crop width + :param h: The crop height + :return: The new image + """ ... - def copy(self) -> Image: - """建立圖像的精確副本。 + """Create an exact copy of the image. -Example: ``Image.HEART.copy()`` + Example: ``Image.HEART.copy()`` -:return: The new image""" + :return: The new image + """ ... - def invert(self) -> Image: - """透過反轉來源圖像的像素亮度,以建立一個新圖像。 + """Create a new image by inverting the brightness of the pixels in the + source image. -Example: ``Image.SMALL_HEART.invert()`` + Example: ``Image.SMALL_HEART.invert()`` -:return: The new image.""" + :return: The new image. + """ ... - def fill(self, value: int) -> None: - """設定圖像中所有像素的亮度。 + """Set the brightness of all the pixels in the image. -Example: ``my_image.fill(5)`` + Example: ``my_image.fill(5)`` -:param value: 新亮度為 0 (暗) 和 9 (亮) 之間的數字。 + :param value: The new brightness as a number 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``.""" + 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: - """將另一個圖像中的一個區域複製到該圖像中。 - -Example: ``my_image.blit(Image.HEART, 1, 1, 3, 3, 1, 1)`` - -:param src: 來源圖像 -:param x: 來源圖像中的起始行位移 -:param y: 來源圖像中的起始列位移 -:param w: 要複製的行數 -:param h: 要複製的列數 -:param xdest: 此圖像中要修改的行位移 -:param ydest: 此圖像中要修改的列位移 - -Pixels outside the source image are treated as having a brightness 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 blit( + self, + src: Image, + x: int, + y: int, + w: int, + h: int, + xdest: int = 0, + ydest: int = 0, + ) -> None: + """Copy an area from another image into this image. + + Example: ``my_image.blit(Image.HEART, 1, 1, 3, 3, 1, 1)`` + + :param src: The source image + :param x: The starting column offset in the source image + :param y: The starting row offset in the source image + :param w: The number of columns to copy + :param h: The number of rows to copy + :param xdest: The column offset to modify in this image + :param ydest: The row offset to modify in this image + + Pixels outside the source image are treated as having a brightness 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. -Example: ``Image.HEART + Image.HAPPY`` + Example: ``Image.HEART + Image.HAPPY`` -:param other: 要新增的圖像。""" + :param other: The image to add. + """ ... - def __sub__(self, other: Image) -> Image: - """透過從該圖像中減去另一個圖像的亮度值,以建立一個新圖像。 + """Create a new image by subtracting the brightness values of the + other image from this image. -Example: ``Image.HEART - Image.HEART_SMALL`` + Example: ``Image.HEART - Image.HEART_SMALL`` -:param other: 要減去的圖像。""" + :param other: The image to subtract. + """ ... - def __mul__(self, n: float) -> Image: - """將各像素的亮度乘以 ``n``,以建立新圖像。 + """Create a new image by multiplying the brightness of each pixel by + ``n``. -Example: ``Image.HEART * 0.5`` + Example: ``Image.HEART * 0.5`` -:param n: 要乘以的值。""" + :param n: The value to multiply by. + """ ... - def __truediv__(self, n: float) -> Image: - """透過將各像素的亮度除以 ``n``,以建立一個新圖像。 + """Create a new image by dividing the brightness of each pixel by + ``n``. -Example: ``Image.HEART / 2`` + Example: ``Image.HEART / 2`` -:param n: 要除以的值。""" + :param n: The value to divide by. + """ ... class SoundEvent: LOUD: SoundEvent - """表示聲音事件的轉換,從 ``quiet`` 到 ``loud``,如鼓掌或喊叫。""" + """Represents the transition of sound events, from ``quiet`` to ``loud`` like clapping or shouting.""" + QUIET: SoundEvent - """表示聲音事件的轉換,從 ``loud`` 到 ``quiet``。例如,說話或背景音樂。""" + """Represents the transition of sound events, from ``loud`` to ``quiet`` like speaking or background music.""" class Sound: - """可以使用 ``audio.play(Sound.NAME)`` 調用內建聲音。""" + """The built-in sounds can be called using ``audio.play(Sound.NAME)``.""" + GIGGLE: Sound - """咯咯笑的聲音。 (咯咯笑)""" + """Giggling sound.""" + HAPPY: Sound - """開心的聲音。 (開心)""" + """Happy sound.""" + HELLO: Sound - """歡迎的聲音。 (哈囉)""" + """Greeting sound.""" + MYSTERIOUS: Sound - """神祕的聲音。 (神秘)""" + """Mysterious sound.""" + SAD: Sound - """難過的聲音。 (難過)""" + """Sad sound.""" + SLIDE: Sound - """滑動的聲音。""" + """Sliding sound.""" + SOARING: Sound - """高昂的聲音。 (高昂)""" + """Soaring sound.""" + SPRING: Sound - """彈跳的聲音。 (彈跳)""" + """Spring sound.""" + TWINKLE: Sound - """發亮的聲音。 (發亮)""" + """Twinkling sound.""" + YAWN: Sound - """呵欠的聲音。""" \ No newline at end of file + """Yawning sound.""" diff --git a/lang/zh-tw/typeshed/stdlib/microbit/accelerometer.pyi b/lang/zh-tw/typeshed/stdlib/microbit/accelerometer.pyi index bb2e9ad..bac82c0 100644 --- a/lang/zh-tw/typeshed/stdlib/microbit/accelerometer.pyi +++ b/lang/zh-tw/typeshed/stdlib/microbit/accelerometer.pyi @@ -1,103 +1,115 @@ -"""測量 micro:bit 的加速度並識別手勢。""" +"""Measure the acceleration of the micro:bit and recognise gestures. +""" + from typing import Tuple def get_x() -> int: - """取得 ``x`` 軸上的加速度測量值 (以毫克為單位)。 + """Get the acceleration measurement in the ``x`` axis in milli-g. -Example: ``accelerometer.get_x()`` + Example: ``accelerometer.get_x()`` -:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" + :return: A positive or negative integer depending on direction in the range +/- 2000mg. + """ ... def get_y() -> int: - """取得 ``y`` 軸上的加速度測量值 (以毫克為單位)。 + """Get the acceleration measurement in the ``y`` axis in milli-g. -Example: ``accelerometer.get_y()`` + Example: ``accelerometer.get_y()`` -:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" + :return: A positive or negative integer depending on direction in the range +/- 2000mg. + """ ... def get_z() -> int: - """取得 ``z`` 軸上的加速度測量值 (以毫克為單位)。 + """Get the acceleration measurement in the ``z`` axis in milli-g. -Example: ``accelerometer.get_z()`` + Example: ``accelerometer.get_z()`` -:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" + :return: A positive or negative integer depending on direction in the range +/- 2000mg. + """ ... def get_values() -> Tuple[int, int, int]: - """一次取得所有軸上的加速度測量值做為元組。 + """Get the acceleration measurements in all axes at once as a tuple. -Example: ``x, y, z = accelerometer.get_values()`` + Example: ``x, y, z = accelerometer.get_values()`` -:return: a three-element tuple of integers ordered as X, Y, Z, each value a positive or negative integer depending on direction in the range +/- 2000mg""" + :return: a three-element tuple of integers ordered as X, Y, Z, each value a positive or negative integer depending on direction in the range +/- 2000mg + """ ... def get_strength() -> int: """Get the acceleration measurement of all axes combined, as a positive integer. This is the Pythagorean sum of the X, Y and Z axes. -Example: ``accelerometer.get_strength()`` + Example: ``accelerometer.get_strength()`` -:return: The combined acceleration strength of all the axes, in milli-g.""" + :return: The combined acceleration strength of all the axes, in milli-g. + """ ... def current_gesture() -> str: - """取得目前手勢的名稱。 + """Get the name of the current gesture. -Example: ``accelerometer.current_gesture()`` + Example: ``accelerometer.current_gesture()`` -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. + 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. -:return: The current gesture""" + :return: The current gesture + """ ... def is_gesture(name: str) -> bool: - """檢查命名的手勢目前是否處於活動狀態。 + """Check if the named gesture is currently active. -Example: ``accelerometer.is_gesture('shake')`` + Example: ``accelerometer.is_gesture('shake')`` -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. + 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. -:param name: 手勢名稱。 -:return: ``True`` if the gesture is active, ``False`` otherwise.""" + :param name: The gesture name. + :return: ``True`` if the gesture is active, ``False`` otherwise. + """ ... def was_gesture(name: str) -> bool: - """檢查命名手勢自上次呼叫後是否處於活動狀態。 + """Check if the named gesture was active since the last call. -Example: ``accelerometer.was_gesture('shake')`` + Example: ``accelerometer.was_gesture('shake')`` -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. + 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. -:param name: 手勢名稱。 -:return: ``True`` if the gesture was active since the last call, ``False`` otherwise.""" + :param name: The gesture name. + :return: ``True`` if the gesture was active since the last call, ``False`` otherwise. + """ def get_gestures() -> Tuple[str, ...]: - """傳回手勢歷史紀錄的元組。 + """Return a tuple of the gesture history. -Example: ``accelerometer.get_gestures()`` + Example: ``accelerometer.get_gestures()`` -Clears the gesture history before returning. + Clears the gesture history before returning. -Gestures are not updated in the background so there needs to be constant -calls to some accelerometer method to do the gesture detection. Usually -gestures can be detected using a loop with a small :func:`microbit.sleep` delay. + Gestures are not updated in the background so there needs to be constant + calls to some accelerometer method to do the gesture detection. Usually + gestures can be detected using a loop with a small :func:`microbit.sleep` delay. -:return: The history as a tuple, most recent last.""" + :return: The history as a tuple, most recent last. + """ ... def set_range(value: int) -> None: """Set the accelerometer sensitivity range, in g (standard gravity), to the closest values supported by the hardware, so it rounds to either ``2``, ``4``, or ``8`` g. -Example: ``accelerometer.set_range(8)`` + Example: ``accelerometer.set_range(8)`` -:param value: New range for the accelerometer, an integer in ``g``.""" \ No newline at end of file + :param value: New range for the accelerometer, an integer in ``g``. + """ diff --git a/lang/zh-tw/typeshed/stdlib/microbit/audio.pyi b/lang/zh-tw/typeshed/stdlib/microbit/audio.pyi index aa56a2c..3b1e327 100644 --- a/lang/zh-tw/typeshed/stdlib/microbit/audio.pyi +++ b/lang/zh-tw/typeshed/stdlib/microbit/audio.pyi @@ -1,123 +1,160 @@ -"""使用 micro:bit 播放聲音 (匯入 ``audio`` 與 V1 相容)。""" +"""Play sounds using the micro:bit (import ``audio`` for V1 compatibility). +""" + from ..microbit import MicroBitDigitalPin, Sound, pin0 from typing import ClassVar, Iterable, Union -def play(source: Union[Iterable[AudioFrame], Sound, SoundEffect], wait: bool=True, pin: MicroBitDigitalPin=pin0, return_pin: Union[MicroBitDigitalPin, None]=None) -> None: +def play( + source: Union[Iterable[AudioFrame], Sound, SoundEffect], + wait: bool = True, + pin: MicroBitDigitalPin = pin0, + return_pin: Union[MicroBitDigitalPin, None] = None, +) -> None: """Play a built-in sound, sound effect or custom audio frames. -Example: ``audio.play(Sound.GIGGLE)`` + Example: ``audio.play(Sound.GIGGLE)`` -:param source: A built-in ``Sound`` such as ``Sound.GIGGLE``, a ``SoundEffect`` or sample data as an iterable of ``AudioFrame`` objects. -:param wait: 如果 ``wait`` 為 ``True``,此函式將會封鎖,直到聲音完成。 -:param pin: (引腳) 指定輸出引腳的可選引數,可用於覆寫預設值 ``pin0``。如果我們不想播放任何聲音,我們可以使用 ``pin=None``。 -:param return_pin: 指定差分邊緣連接器引腳,以連接到外部揚聲器而不是接地。在 **V2** 修訂版中,這將會被忽略。""" + :param source: A built-in ``Sound`` such as ``Sound.GIGGLE``, a ``SoundEffect`` or sample data as an iterable of ``AudioFrame`` objects. + :param wait: If ``wait`` is ``True``, this function will block until the sound is complete. + :param pin: An optional argument to specify the output pin can be used to override the default of ``pin0``. If we do not want any sound to play we can use ``pin=None``. + :param return_pin: Specifies a differential edge connector pin to connect to an external speaker instead of ground. This is ignored for the **V2** revision. + """ def is_playing() -> bool: - """檢查是否正在播放聲音。 + """Check whether a sound is playing. -Example: ``audio.is_playing()`` + Example: ``audio.is_playing()`` -:return: ``True`` if audio is playing, otherwise ``False``.""" + :return: ``True`` if audio is playing, otherwise ``False``.""" ... def stop() -> None: - """停止所有音訊播放。 + """Stop all audio playback. -Example: ``audio.stop()``""" + Example: ``audio.stop()`` + """ ... class SoundEffect: """A sound effect, composed by a set of parameters configured via the constructor or attributes.""" + WAVEFORM_SINE: ClassVar[int] """Sine wave option used for the ``waveform`` parameter.""" + WAVEFORM_SAWTOOTH: ClassVar[int] """Sawtooth wave option used for the ``waveform`` parameter.""" + WAVEFORM_TRIANGLE: ClassVar[int] """Triangle wave option used for the ``waveform`` parameter.""" + WAVEFORM_SQUARE: ClassVar[int] """Square wave option used for the ``waveform`` parameter.""" + WAVEFORM_NOISE: ClassVar[int] """Noise option used for the ``waveform`` parameter.""" + SHAPE_LINEAR: ClassVar[int] """Linear interpolation option used for the ``shape`` parameter.""" + SHAPE_CURVE: ClassVar[int] """Curve interpolation option used for the ``shape`` parameter.""" + SHAPE_LOG: ClassVar[int] """Logarithmic interpolation option used for the ``shape`` parameter.""" + FX_NONE: ClassVar[int] """No effect option used for the ``fx`` parameter.""" + FX_TREMOLO: ClassVar[int] """Tremolo effect option used for the ``fx`` parameter.""" + FX_VIBRATO: ClassVar[int] """Vibrato effect option used for the ``fx`` parameter.""" + FX_WARBLE: ClassVar[int] """Warble effect option used for the ``fx`` parameter.""" + freq_start: int """Start frequency in Hertz (Hz), a number between ``0`` and ``9999``""" + freq_end: int """End frequency in Hertz (Hz), a number between ``0`` and ``9999``""" + duration: int """Duration of the sound in milliseconds, a number between ``0`` and ``9999``""" + vol_start: int """Start volume value, a number between ``0`` and ``255``""" + vol_end: int """End volume value, a number between ``0`` and ``255``""" + waveform: int """Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise)""" + fx: int """Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``""" + shape: int """The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``""" - def __init__(self, freq_start: int=500, freq_end: int=2500, duration: int=500, vol_start: int=255, vol_end: int=0, waveform: int=WAVEFORM_SQUARE, fx: int=FX_NONE, shape: int=SHAPE_LOG): + def __init__( + self, + freq_start: int = 500, + freq_end: int = 2500, + duration: int = 500, + vol_start: int = 255, + vol_end: int = 0, + waveform: int = WAVEFORM_SQUARE, + fx: int = FX_NONE, + shape: int = SHAPE_LOG, + ): """Create a new sound effect. -Example: ``my_effect = SoundEffect(duration=1000)`` - -All the parameters are optional, with default values as shown above, and -they can all be modified via attributes of the same name. For example, we -can first create an effect ``my_effect = SoundEffect(duration=1000)``, -and then change its attributes ``my_effect.duration = 500``. - -:param freq_start: Start frequency in Hertz (Hz), a number between ``0`` and ``9999``. -:param freq_end: End frequency in Hertz (Hz), a number between ``0`` and ``9999``. -:param duration: Duration of the sound in milliseconds, a number between ``0`` and ``9999``. -:param vol_start: Start volume value, a number between ``0`` and ``255``. -:param vol_end: End volume value, a number between ``0`` and ``255``. -:param waveform: Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise). -:param fx: Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``. -:param shape: The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``.""" - + Example: ``my_effect = SoundEffect(duration=1000)`` + + All the parameters are optional, with default values as shown above, and + they can all be modified via attributes of the same name. For example, we + can first create an effect ``my_effect = SoundEffect(duration=1000)``, + and then change its attributes ``my_effect.duration = 500``. + + :param freq_start: Start frequency in Hertz (Hz), a number between ``0`` and ``9999``. + :param freq_end: End frequency in Hertz (Hz), a number between ``0`` and ``9999``. + :param duration: Duration of the sound in milliseconds, a number between ``0`` and ``9999``. + :param vol_start: Start volume value, a number between ``0`` and ``255``. + :param vol_end: End volume value, a number between ``0`` and ``255``. + :param waveform: Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise). + :param fx: Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``. + :param shape: The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``. + """ def copy(self) -> SoundEffect: """Create a copy of this ``SoundEffect``. -Example: ``sound_2 = sound_1.copy()`` + Example: ``sound_2 = sound_1.copy()`` -:return: A copy of the SoundEffect.""" + :return: A copy of the SoundEffect. + """ class AudioFrame: - """``AudioFrame`` 物件是 32 個樣本的列表,每個樣本都是一個無符號位元組 (0 到 255 之間的整數)。 + """An ``AudioFrame`` object is a list of 32 samples each of which is a unsigned byte + (whole number between 0 and 255). -It takes just over 4 ms to play a single frame. + It takes just over 4 ms to play a single frame. -Example:: + Example:: - frame = AudioFrame() - for i in range(len(frame)): - frame[i] = 252 - i * 8""" + frame = AudioFrame() + for i in range(len(frame)): + frame[i] = 252 - i * 8 + """ def copyfrom(self, other: AudioFrame) -> None: """Overwrite the data in this ``AudioFrame`` with the data from another ``AudioFrame`` instance. -Example: ``my_frame.copyfrom(source_frame)`` - -:param other: ``AudioFrame`` instance from which to copy the data.""" - - def __len__(self) -> int: - ... - - def __setitem__(self, key: int, value: int) -> None: - ... + Example: ``my_frame.copyfrom(source_frame)`` - def __getitem__(self, key: int) -> int: - ... \ No newline at end of file + :param other: ``AudioFrame`` instance from which to copy the data. + """ + def __len__(self) -> int: ... + def __setitem__(self, key: int, value: int) -> None: ... + def __getitem__(self, key: int) -> int: ... diff --git a/lang/zh-tw/typeshed/stdlib/microbit/compass.pyi b/lang/zh-tw/typeshed/stdlib/microbit/compass.pyi index 74681f3..c74a47b 100644 --- a/lang/zh-tw/typeshed/stdlib/microbit/compass.pyi +++ b/lang/zh-tw/typeshed/stdlib/microbit/compass.pyi @@ -1,70 +1,78 @@ -"""使用內建指南針。 (指南針)""" +"""Use the built-in compass. +""" def calibrate() -> None: - """開始校準程序。 + """Starts the calibration process. -Example: ``compass.calibrate()`` + Example: ``compass.calibrate()`` -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.""" + 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: - """檢查指南針是否已校準。 + """Check is the compass is calibrated. -Example: ``compass.is_calibrated()`` + Example: ``compass.is_calibrated()`` -:return: ``True`` if the compass has been successfully calibrated, ``False`` otherwise.""" + :return: ``True`` if the compass has been successfully calibrated, ``False`` otherwise. + """ ... def clear_calibration() -> None: - """復原校準,使指南針再次未校準。 + """Undoes the calibration, making the compass uncalibrated again. -Example: ``compass.clear_calibration()``""" + Example: ``compass.clear_calibration()`` + """ ... def get_x() -> int: - """取得 ``x`` 軸上的磁場強度。 + """Get the magnetic field strength on the ``x`` axis. -Example: ``compass.get_x()`` + Example: ``compass.get_x()`` -Call ``calibrate`` first or the results will be inaccurate. + Call ``calibrate`` first or the results will be inaccurate. -:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" + :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. + """ ... def get_y() -> int: - """取得 ``y`` 軸上的磁場強度。 + """Get the magnetic field strength on the ``y`` axis. -Example: ``compass.get_y()`` + Example: ``compass.get_y()`` -Call ``calibrate`` first or the results will be inaccurate. + Call ``calibrate`` first or the results will be inaccurate. -:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" + :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. + """ ... def get_z() -> int: - """取得 ``z`` 軸上的磁場強度。 + """Get the magnetic field strength on the ``z`` axis. -Example: ``compass.get_z()`` + Example: ``compass.get_z()`` -Call ``calibrate`` first or the results will be inaccurate. + Call ``calibrate`` first or the results will be inaccurate. -:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" + :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. + """ ... def heading() -> int: - """取得指南針方向。 + """Get the compass heading. -Example: ``compass.heading()`` + Example: ``compass.heading()`` -:return: An integer in the range from 0 to 360, representing the angle in degrees, clockwise, with north as 0.""" + :return: An integer in the range from 0 to 360, representing the angle in degrees, clockwise, with north as 0. + """ ... def get_field_strength() -> int: - """取得裝置周圍磁場的強度。 + """Get the magnitude of the magnetic field around the device. -Example: ``compass.get_field_strength()`` + Example: ``compass.get_field_strength()`` -:return: An integer indication of the magnitude of the magnetic field in nano tesla.""" - ... \ No newline at end of file + :return: An integer indication of the magnitude of the magnetic field in nano tesla.""" + ... diff --git a/lang/zh-tw/typeshed/stdlib/microbit/display.pyi b/lang/zh-tw/typeshed/stdlib/microbit/display.pyi index 5b2a57e..aa4013e 100644 --- a/lang/zh-tw/typeshed/stdlib/microbit/display.pyi +++ b/lang/zh-tw/typeshed/stdlib/microbit/display.pyi @@ -1,92 +1,115 @@ -"""在 5×5 LED 顯示器上顯示文字、圖像和動畫。""" +"""Show text, images and animations on the 5×5 LED display. +""" + from ..microbit import Image from typing import Union, overload, Iterable def get_pixel(x: int, y: int) -> int: - """取得行 ``x`` 和列 ``y`` 的 LED 亮度。 + """Get the brightness of the LED at column ``x`` and row ``y``. -Example: ``display.get_pixel(0, 0)`` + Example: ``display.get_pixel(0, 0)`` -:param x: 顯示行 (0..4) -:param y: 顯示列 (0..4) -:return: A number between 0 (off) and 9 (bright)""" + :param x: The display column (0..4) + :param y: The display row (0..4) + :return: A number between 0 (off) and 9 (bright) + """ ... def set_pixel(x: int, y: int, value: int) -> None: - """在行 ``x`` 和列 ``y`` 設定 LED 亮度。 + """Set the brightness of the LED at column ``x`` and row ``y``. -Example: ``display.set_pixel(0, 0, 9)`` + Example: ``display.set_pixel(0, 0, 9)`` -:param x: 顯示行 (0..4) -:param y: 顯示列 (0..4) -:param value: 0 (關閉) 和 9 (最亮) 之間的亮度""" + :param x: The display column (0..4) + :param y: The display row (0..4) + :param value: The brightness between 0 (off) and 9 (bright) + """ ... def clear() -> None: - """將所有 LED 的亮度設定為 0 (關閉)。 + """Set the brightness of all LEDs to 0 (off). -Example: ``display.clear()``""" + Example: ``display.clear()`` + """ ... -def show(image: Union[str, float, int, Image, Iterable[Image]], delay: int=400, wait: bool=True, loop: bool=False, clear: bool=False) -> None: - """在 LED 顯示器上顯示圖像、字母或數字。 +def show( + image: Union[str, float, int, Image, Iterable[Image]], + delay: int = 400, + wait: bool = True, + loop: bool = False, + clear: bool = False, +) -> None: + """Shows images, letters or digits on the LED display. -Example: ``display.show(Image.HEART)`` + Example: ``display.show(Image.HEART)`` -When ``image`` is an image or a list of images then each image is displayed in turn. -If ``image`` is a string or number, each letter or digit is displayed in turn. + When ``image`` is an image or a list of images then each image is displayed in turn. + If ``image`` is a string or number, each letter or digit is displayed in turn. -:param image: 要顯示的字串、數字、圖像或圖像列表。 -:param delay: 每個字母、數字或圖像之間的顯示時間為 ``delay`` 毫秒。 -:param wait: 如果 ``wait`` 為 ``True``,此函式將封鎖直到動畫完成,否則動畫將在背景發生。 -:param loop: 如果 ``loop`` 為 ``True``,動畫將永遠重複。 -:param clear: 如果 ``clear`` 為 ``True``,則顯示將在序列完成後被清除。 + :param image: A string, number, image or list of images to show. + :param delay: Each letter, digit or image is shown with ``delay`` milliseconds between them. + :param wait: If ``wait`` is ``True``, this function will block until the animation is finished, otherwise the animation will happen in the background. + :param loop: If ``loop`` is ``True``, the animation will repeat forever. + :param clear: If ``clear`` is ``True``, the display will be cleared after the sequence has finished. -The ``wait``, ``loop`` and ``clear`` arguments must be specified using their keyword.""" + The ``wait``, ``loop`` and ``clear`` arguments must be specified using their keyword. + """ ... -def scroll(text: Union[str, float, int], delay: int=150, wait: bool=True, loop: bool=False, monospace: bool=False) -> None: - """捲動 LED 顯示器上的數字或文字。 - -Example: ``display.scroll('micro:bit')`` - -:param text: 要捲動的字串。如果 ``text`` 是整數或浮點數,則先使用 ``str()`` 將其轉換為字串。 -:param delay: ``delay`` 參數可控制文字捲動的速度。 -:param wait: 如果 ``wait`` 為 ``True``,此函式將封鎖直到動畫完成,否則動畫將在背景發生。 -:param loop: 如果 ``loop`` 為 ``True``,動畫將永遠重複。 -:param monospace: 如果 ``monospace`` 為 ``True``,字元寬度將全部佔用 5 個像素行。否則,捲動時每個字元之間將恰好有 1 個空白像素行。 - -The ``wait``, ``loop`` and ``monospace`` arguments must be specified -using their keyword.""" +def scroll( + text: Union[str, float, int], + delay: int = 150, + wait: bool = True, + loop: bool = False, + monospace: bool = False, +) -> None: + """Scrolls a number or text on the LED display. + + Example: ``display.scroll('micro:bit')`` + + :param text: The string to scroll. If ``text`` is an integer or float it is first converted to a string using ``str()``. + :param delay: The ``delay`` parameter controls how fast the text is scrolling. + :param wait: If ``wait`` is ``True``, this function will block until the animation is finished, otherwise the animation will happen in the background. + :param loop: If ``loop`` is ``True``, the animation will repeat forever. + :param monospace: 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. + + The ``wait``, ``loop`` and ``monospace`` arguments must be specified + using their keyword. + """ ... def on() -> None: - """開啟 LED 顯示器。 + """Turn on the LED display. -Example: ``display.on()``""" + Example: ``display.on()`` + """ ... def off() -> None: - """關閉 LED 顯示器 (停用顯示器,可讓您將 GPIO 引腳重新用於其他目的)。 + """Turn off the LED display (disabling the display allows you to re-use the GPIO pins for other purposes). -Example: ``display.off()``""" + Example: ``display.off()`` + """ ... def is_on() -> bool: - """檢查 LED 顯示器是否有啟用。 + """Check whether the LED display is enabled. -Example: ``display.is_on()`` + Example: ``display.is_on()`` -:return: ``True`` if the display is on, otherwise returns ``False``.""" + :return: ``True`` if the display is on, otherwise returns ``False``. + """ ... def read_light_level() -> int: - """讀取光度。 + """Read the light level. -Example: ``display.read_light_level()`` + Example: ``display.read_light_level()`` -Uses the display's LEDs in reverse-bias mode to sense the amount of light -falling on the display. + Uses the display's LEDs in reverse-bias mode to sense the amount of light + falling on the display. -:return: An integer between 0 and 255 representing the light level, with larger meaning more light.""" - ... \ No newline at end of file + :return: An integer between 0 and 255 representing the light level, with larger meaning more light. + """ + ... diff --git a/lang/zh-tw/typeshed/stdlib/microbit/i2c.pyi b/lang/zh-tw/typeshed/stdlib/microbit/i2c.pyi index 1ba931c..df26efa 100644 --- a/lang/zh-tw/typeshed/stdlib/microbit/i2c.pyi +++ b/lang/zh-tw/typeshed/stdlib/microbit/i2c.pyi @@ -1,49 +1,57 @@ -"""使用 I²C 匯流排通訊協定與裝置通訊。""" +"""Communicate with devices using the I²C bus protocol. +""" + from _typeshed import ReadableBuffer from ..microbit import MicroBitDigitalPin, pin19, pin20 from typing import List -def init(freq: int=100000, sda: MicroBitDigitalPin=pin20, scl: MicroBitDigitalPin=pin19) -> None: - """重新初始化周邊設備。 +def init( + freq: int = 100000, sda: MicroBitDigitalPin = pin20, scl: MicroBitDigitalPin = pin19 +) -> None: + """Re-initialize a peripheral. -Example: ``i2c.init()`` + Example: ``i2c.init()`` -:param freq: (頻率) 時脈頻率 -:param sda: ``sda`` 引腳 (預設 20) -:param scl: ``scl`` 引腳 (預設 19) + :param freq: clock frequency + :param sda: ``sda`` pin (default 20) + :param scl: ``scl`` pin (default 19) -On a micro:bit V1 board, changing the I²C pins from defaults will make -the accelerometer and compass stop working, as they are connected -internally to those pins. This warning does not apply to the **V2** -revision of the micro:bit as this has `separate I²C lines `_ -for the motion sensors and the edge connector.""" + On a micro:bit V1 board, changing the I²C pins from defaults will make + the accelerometer and compass stop working, as they are connected + internally to those pins. This warning does not apply to the **V2** + revision of the micro:bit as this has `separate I²C lines `_ + for the motion sensors and the edge connector. + """ ... def scan() -> List[int]: - """掃描匯流排以尋找裝置。 + """Scan the bus for devices. -Example: ``i2c.scan()`` + Example: ``i2c.scan()`` -:return: A list of 7-bit addresses corresponding to those devices that responded to the scan.""" + :return: A list of 7-bit addresses corresponding to those devices that responded to the scan. + """ ... -def read(addr: int, n: int, repeat: bool=False) -> bytes: - """從裝置讀取位元組。 +def read(addr: int, n: int, repeat: bool = False) -> bytes: + """Read bytes from a device. -Example: ``i2c.read(0x50, 64)`` + Example: ``i2c.read(0x50, 64)`` -:param addr: 裝置的 7 位元地址 -:param n: 要讀取的位元組數 -:param repeat: 如果 ``True``,則不會傳送停止位元 -:return: The bytes read""" + :param addr: The 7-bit address of the device + :param n: The number of bytes to read + :param repeat: If ``True``, no stop bit will be sent + :return: The bytes read + """ ... -def write(addr: int, buf: ReadableBuffer, repeat: bool=False) -> None: - """將位元組寫入裝置。 +def write(addr: int, buf: ReadableBuffer, repeat: bool = False) -> None: + """Write bytes to a device. -Example: ``i2c.write(0x50, bytes([1, 2, 3]))`` + Example: ``i2c.write(0x50, bytes([1, 2, 3]))`` -:param addr: 裝置的 7 位元位址 -:param buf: 包含要寫入位元組的緩衝區 -:param repeat: 如果 ``True``,則不會傳送停止位元""" - ... \ No newline at end of file + :param addr: The 7-bit address of the device + :param buf: A buffer containing the bytes to write + :param repeat: If ``True``, no stop bit will be sent + """ + ... diff --git a/lang/zh-tw/typeshed/stdlib/microbit/microphone.pyi b/lang/zh-tw/typeshed/stdlib/microbit/microphone.pyi index 894fa45..68e8f3a 100644 --- a/lang/zh-tw/typeshed/stdlib/microbit/microphone.pyi +++ b/lang/zh-tw/typeshed/stdlib/microbit/microphone.pyi @@ -1,62 +1,70 @@ -"""使用內建麥克風回應聲音 (僅限 V2)。""" +"""Respond to sound using the built-in microphone (V2 only). +""" + from typing import Optional, Tuple from ..microbit import SoundEvent def current_event() -> Optional[SoundEvent]: - """取得最後錄製的聲音事件 + """Get the last recorded sound event -Example: ``microphone.current_event()`` + Example: ``microphone.current_event()`` -:return: The event, ``SoundEvent('loud')`` or ``SoundEvent('quiet')``.""" + :return: The event, ``SoundEvent('loud')`` or ``SoundEvent('quiet')``. + """ ... def was_event(event: SoundEvent) -> bool: - """檢查自上次呼叫後,是否至少有聽到一次聲音。 + """Check if a sound was heard at least once since the last call. -Example: ``microphone.was_event(SoundEvent.LOUD)`` + Example: ``microphone.was_event(SoundEvent.LOUD)`` -This call clears the sound history before returning. + This call clears the sound history before returning. -:param event: 要檢查的事件,例如 ``SoundEvent.LOUD`` 或 ``SoundEvent.QUIET`` -:return: ``True`` if sound was heard at least once since the last call, otherwise ``False``.""" + :param event: The event to check for, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET`` + :return: ``True`` if sound was heard at least once since the last call, otherwise ``False``. + """ ... def is_event(event: SoundEvent) -> bool: - """檢查偵測到的最新聲音事件。 + """Check the most recent sound event detected. -Example: ``microphone.is_event(SoundEvent.LOUD)`` + Example: ``microphone.is_event(SoundEvent.LOUD)`` -This call does not clear the sound event history. + This call does not clear the sound event history. -:param event: 要檢查的事件,例如 ``SoundEvent.LOUD`` 或 ``SoundEvent.QUIET`` -:return: ``True`` if sound was the most recent heard, ``False`` otherwise.""" + :param event: The event to check for, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET`` + :return: ``True`` if sound was the most recent heard, ``False`` otherwise. + """ ... def get_events() -> Tuple[SoundEvent, ...]: - """以元組的形式取得聲音事件歷史。 + """Get the sound event history as a tuple. -Example: ``microphone.get_events()`` + Example: ``microphone.get_events()`` -This call clears the sound history before returning. + This call clears the sound history before returning. -:return: A tuple of the event history with the most recent event last.""" + :return: A tuple of the event history with the most recent event last. + """ ... def set_threshold(event: SoundEvent, value: int) -> None: - """設定聲音事件的閾值。 + """Set the threshold for a sound event. -Example: ``microphone.set_threshold(SoundEvent.LOUD, 250)`` + Example: ``microphone.set_threshold(SoundEvent.LOUD, 250)`` -A high threshold means the event will only trigger if the sound is very loud (>= 250 in the example). + A high threshold means the event will only trigger if the sound is very loud (>= 250 in the example). -:param event: 聲音事件,例如 ``SoundEvent.LOUD`` 或 ``SoundEvent.QUIET``。 -:param value: 0-255 範圍內的閾值等級。""" + :param event: A sound event, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET``. + :param value: The threshold level in the range 0-255. + """ ... def sound_level() -> int: - """取得聲壓位準。 + """Get the sound pressure level. -Example: ``microphone.sound_level()`` + Example: ``microphone.sound_level()`` -:return: A representation of the sound pressure level in the range 0 to 255.""" - ... \ No newline at end of file + :return: A representation of the sound pressure level in the range 0 to 255. + """ + ... diff --git a/lang/zh-tw/typeshed/stdlib/microbit/speaker.pyi b/lang/zh-tw/typeshed/stdlib/microbit/speaker.pyi index 879118f..5a74a4d 100644 --- a/lang/zh-tw/typeshed/stdlib/microbit/speaker.pyi +++ b/lang/zh-tw/typeshed/stdlib/microbit/speaker.pyi @@ -1,15 +1,18 @@ -"""控制內建揚聲器 (僅限 V2)。""" +"""Control the built-in speaker (V2 only). +""" def off() -> None: - """關閉揚聲器。 + """Turn the speaker off. -Example: ``speaker.off()`` + Example: ``speaker.off()`` -This does not disable sound output to an edge connector pin.""" + This does not disable sound output to an edge connector pin. + """ ... def on() -> None: - """開啟揚聲器。 + """Turn the speaker on. -Example: ``speaker.on()``""" - ... \ No newline at end of file + Example: ``speaker.on()`` + """ + ... diff --git a/lang/zh-tw/typeshed/stdlib/microbit/spi.pyi b/lang/zh-tw/typeshed/stdlib/microbit/spi.pyi index 34e5f08..09c4046 100644 --- a/lang/zh-tw/typeshed/stdlib/microbit/spi.pyi +++ b/lang/zh-tw/typeshed/stdlib/microbit/spi.pyi @@ -1,47 +1,60 @@ -"""使用周邊設備介面 (SPI) 匯流排與裝置進行通訊。""" +"""Communicate with devices using the serial peripheral interface (SPI) bus. +""" + from _typeshed import ReadableBuffer, WriteableBuffer from ..microbit import pin13, pin14, pin15, MicroBitDigitalPin -def init(baudrate: int=1000000, bits: int=8, mode: int=0, sclk: MicroBitDigitalPin=pin13, mosi: MicroBitDigitalPin=pin15, miso: MicroBitDigitalPin=pin14) -> None: - """初始化 SPI 通訊。 - -Example: ``spi.init()`` - -For correct communication, the parameters have to be the same on both communicating devices. - -:param baudrate: 通訊速度。 -:param bits: 每次傳輸的位元寬度。目前僅支援 ``bits=8``。然而,這種情況在未來可能會改變。 -:param mode: 確定時脈極性和相位的組合 - 請見線上表格 `_。 -:param sclk: sclk 引腳 (預設 13) -:param mosi: mosi 引腳 (預設 15) -:param miso: miso 引腳 (預設 14)""" +def init( + baudrate: int = 1000000, + bits: int = 8, + mode: int = 0, + sclk: MicroBitDigitalPin = pin13, + mosi: MicroBitDigitalPin = pin15, + miso: MicroBitDigitalPin = pin14, +) -> None: + """Initialize SPI communication. + + Example: ``spi.init()`` + + For correct communication, the parameters have to be the same on both communicating devices. + + :param baudrate: The speed of communication. + :param bits: The width in bits of each transfer. Currently only ``bits=8`` is supported. However, this may change in the future. + :param mode: Determines the combination of clock polarity and phase - `see online table `_. + :param sclk: sclk pin (default 13) + :param mosi: mosi pin (default 15) + :param miso: miso pin (default 14) + """ ... -def read(nbytes: int, out: int=0) -> bytes: - """讀取位元組。 +def read(nbytes: int, out: int = 0) -> bytes: + """Read at most ``nbytes`` while continuously writing the single byte given by ``out``. -Example: ``spi.read(64)`` + Example: ``spi.read(64)`` -:param nbytes: 要讀取的最大位元組數。 -:param out: The byte value to write (default 0). -:return: The bytes read.""" + :param nbytes: Maximum number of bytes to read. + :param out: The byte value to write (default 0). + :return: The bytes read. + """ ... def write(buffer: ReadableBuffer) -> None: - """將位元組寫入匯流排。 + """Write bytes to the bus. -Example: ``spi.write(bytes([1, 2, 3]))`` + Example: ``spi.write(bytes([1, 2, 3]))`` -:param buffer: 讀取資料的來源緩衝區。""" + :param buffer: A buffer to read data from. + """ ... def write_readinto(out: WriteableBuffer, in_: ReadableBuffer) -> None: - """將 ``out`` 緩衝區寫入匯流排,並將任何回應寫入 ``in_`` 緩衝區。 + """Write the ``out`` buffer to the bus and read any response into the ``in_`` buffer. -Example: ``spi.write_readinto(out_buffer, in_buffer)`` + Example: ``spi.write_readinto(out_buffer, in_buffer)`` -The length of the buffers should be the same. The buffers can be the same object. + The length of the buffers should be the same. The buffers can be the same object. -:param out: 要寫入任何回應的緩衝區。 -:param in_: 要從中讀取資料的緩衝區。""" - ... \ No newline at end of file + :param out: The buffer to write any response to. + :param in_: The buffer to read data from. + """ + ... diff --git a/lang/zh-tw/typeshed/stdlib/microbit/uart.pyi b/lang/zh-tw/typeshed/stdlib/microbit/uart.pyi index f5e15ff..2ab650f 100644 --- a/lang/zh-tw/typeshed/stdlib/microbit/uart.pyi +++ b/lang/zh-tw/typeshed/stdlib/microbit/uart.pyi @@ -1,79 +1,96 @@ -"""使用序列介面與裝置通訊。""" +"""Communicate with a device using a serial interface. +""" + from _typeshed import WriteableBuffer from ..microbit import MicroBitDigitalPin from typing import Optional, Union -ODD: int -"""奇數同位檢查""" -EVEN: int -"""偶數同位檢查""" - -def init(baudrate: int=9600, bits: int=8, parity: Optional[int]=None, stop: int=1, tx: Optional[MicroBitDigitalPin]=None, rx: Optional[MicroBitDigitalPin]=None) -> None: - """初始化序列通訊。 - -Example: ``uart.init(115200, tx=pin0, rx=pin1)`` -:param baudrate: 通訊速度。 -:param bits: 正在傳輸的位元組大小,micro:bit 只支援 8。 -:param parity: 如何檢查奇偶性,``None``、``uart.ODD`` 或 ``uart.EVEN``。 -:param stop: 停止位元的數量,micro:bit 必須為 1。 -:param tx: 傳輸引腳。 -:param rx: 正在接收引腳。 - -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. +ODD: int +"""Odd parity""" -For more details see `the online documentation `_.""" +EVEN: int +"""Even parity""" + +def init( + baudrate: int = 9600, + bits: int = 8, + parity: Optional[int] = None, + stop: int = 1, + tx: Optional[MicroBitDigitalPin] = None, + rx: Optional[MicroBitDigitalPin] = None, +) -> None: + """Initialize serial communication. + + Example: ``uart.init(115200, tx=pin0, rx=pin1)`` + + :param baudrate: The speed of communication. + :param bits: The size of bytes being transmitted. micro:bit only supports 8. + :param parity: How parity is checked, ``None``, ``uart.ODD`` or ``uart.EVEN``. + :param stop: The number of stop bits, has to be 1 for micro:bit. + :param tx: Transmitting pin. + :param rx: Receiving pin. + + 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. + + For more details see `the online documentation `_. + """ ... def any() -> bool: - """檢查是否有任何資料正在等待。 + """Check if any data is waiting. -Example: ``uart.any()`` + Example: ``uart.any()`` -:return: ``True`` if any data is waiting, else ``False``.""" + :return: ``True`` if any data is waiting, else ``False``. + """ ... -def read(nbytes: Optional[int]=None) -> Optional[bytes]: - """讀取位元組。 +def read(nbytes: Optional[int] = None) -> Optional[bytes]: + """Read bytes. -Example: ``uart.read()`` + Example: ``uart.read()`` -:param nbytes: 如果指定了 ``nbytes``,則最多讀取那麼多位元組,否則讀取盡可能多的位元組 -:return: A bytes object or ``None`` on timeout""" + :param nbytes: If ``nbytes`` is specified then read at most that many bytes, otherwise read as many bytes as possible + :return: A bytes object or ``None`` on timeout + """ ... -def readinto(buf: WriteableBuffer, nbytes: Optional[int]=None) -> Optional[int]: - """將位元組讀入 ``buf``。 +def readinto(buf: WriteableBuffer, nbytes: Optional[int] = None) -> Optional[int]: + """Read bytes into the ``buf``. -Example: ``uart.readinto(input_buffer)`` + Example: ``uart.readinto(input_buffer)`` -:param buf: 要寫入的緩衝區。 -:param nbytes: 如果指定了 ``nbytes``,則最多讀取那麼多位元組,否則讀取 ``len(buf)`` 個位元組。 -:return: number of bytes read and stored into ``buf`` or ``None`` on timeout.""" + :param buf: The buffer to write to. + :param nbytes: If ``nbytes`` is specified then read at most that many bytes, otherwise read ``len(buf)`` bytes. + :return: number of bytes read and stored into ``buf`` or ``None`` on timeout. + """ ... def readline() -> Optional[bytes]: - """讀取一行,以新行字元結尾。 + """Read a line, ending in a newline character. -Example: ``uart.readline()`` + Example: ``uart.readline()`` -:return: The line read or ``None`` on timeout. The newline character is included in the returned bytes.""" + :return: The line read or ``None`` on timeout. The newline character is included in the returned bytes. + """ ... def write(buf: Union[bytes, str]) -> Optional[int]: - """將緩衝區寫入匯流排。 + """Write a buffer to the bus. -Example: ``uart.write('hello world')`` + Example: ``uart.write('hello world')`` -:param buf: 一個位元組物件或一個字串。 -:return: The number of bytes written, or ``None`` on timeout. + :param buf: A bytes object or a string. + :return: The number of bytes written, or ``None`` on timeout. -Examples:: + Examples:: - uart.write('hello world') - uart.write(b'hello world') - uart.write(bytes([1, 2, 3]))""" - ... \ No newline at end of file + uart.write('hello world') + uart.write(b'hello world') + uart.write(bytes([1, 2, 3])) + """ + ... diff --git a/lang/zh-tw/typeshed/stdlib/micropython.pyi b/lang/zh-tw/typeshed/stdlib/micropython.pyi index 3b2ad82..7a6079f 100644 --- a/lang/zh-tw/typeshed/stdlib/micropython.pyi +++ b/lang/zh-tw/typeshed/stdlib/micropython.pyi @@ -1,131 +1,144 @@ -"""MicroPython 內部。""" +"""MicroPython internals.""" + from typing import Any, TypeVar, overload -_T = TypeVar('_T') + +_T = TypeVar("_T") def const(expr: _T) -> _T: - """用於宣告運算式為常數,以便編譯器對其進行最佳化。 + """Used to declare that the expression is a constant so that the compiler can + optimise it. -The use of this function should be as follows:: + The use of this function should be as follows:: - from micropython import const - CONST_X = const(123) - CONST_Y = const(2 * CONST_X + 1) + from micropython import const + CONST_X = const(123) + CONST_Y = const(2 * CONST_X + 1) -Constants declared this way are still accessible as global variables from -outside the module they are declared in. On the other hand, if a constant -begins with an underscore then it is hidden, it is not available as a -global variable, and does not take up any memory during execution. + Constants declared this way are still accessible as global variables from + outside the module they are declared in. On the other hand, if a constant + begins with an underscore then it is hidden, it is not available as a + global variable, and does not take up any memory during execution. -:param expr: 一個常數運算式。""" + :param expr: A constant expression. + """ ... @overload def opt_level() -> int: - """取得指令碼編譯的目前最佳化等級。 + """Get the current optimisation level for the compilation of scripts. -Example: ``micropython.opt_level()`` + Example: ``micropython.opt_level()`` -The optimisation level controls the following compilation features: + The optimisation level controls the following compilation features: -- Assertions: at level 0 assertion statements are enabled and compiled - into the bytecode; at levels 1 and higher assertions are not compiled. + - Assertions: at level 0 assertion statements are enabled and compiled + into the bytecode; at levels 1 and higher assertions are not compiled. -- Built-in ``__debug__`` variable: at level 0 this variable expands to - True; at levels 1 and higher it expands to False. + - Built-in ``__debug__`` variable: at level 0 this variable expands to + True; at levels 1 and higher it expands to False. -- Source-code line numbers: at levels 0, 1 and 2 source-code line number - are stored along with the bytecode so that exceptions can report the - line number they occurred at; at levels 3 and higher line numbers are - not stored. + - Source-code line numbers: at levels 0, 1 and 2 source-code line number + are stored along with the bytecode so that exceptions can report the + line number they occurred at; at levels 3 and higher line numbers are + not stored. -:return: An integer representing the current level.""" + :return: An integer representing the current level. + """ ... @overload def opt_level(level: int) -> None: - """設定指令碼後續編譯的最佳化等級。 + """Sets the optimisation level for subsequent compilation of scripts. -Example: ``micropython.opt_level(1)`` + Example: ``micropython.opt_level(1)`` -The optimisation level controls the following compilation features: + The optimisation level controls the following compilation features: -- Assertions: at level 0 assertion statements are enabled and compiled - into the bytecode; at levels 1 and higher assertions are not compiled. + - Assertions: at level 0 assertion statements are enabled and compiled + into the bytecode; at levels 1 and higher assertions are not compiled. -- Built-in ``__debug__`` variable: at level 0 this variable expands to - True; at levels 1 and higher it expands to False. + - Built-in ``__debug__`` variable: at level 0 this variable expands to + True; at levels 1 and higher it expands to False. -- Source-code line numbers: at levels 0, 1 and 2 source-code line number - are stored along with the bytecode so that exceptions can report the - line number they occurred at; at levels 3 and higher line numbers are - not stored. + - Source-code line numbers: at levels 0, 1 and 2 source-code line number + are stored along with the bytecode so that exceptions can report the + line number they occurred at; at levels 3 and higher line numbers are + not stored. -The default optimisation level is usually level 0. + The default optimisation level is usually level 0. -:param level: 整數最佳化等級。""" + :param level: An integer optimisation level. + """ ... -def mem_info(verbose: Any=None) -> None: - """輸出關於目前使用的記憶體資訊。 +def mem_info(verbose: Any = None) -> None: + """Print information about currently used memory. -Example: ``micropython.mem_info()`` + Example: ``micropython.mem_info()`` -:param verbose: 如果給出 ``verbose`` 引數,則會輸出額外資訊。""" + :param verbose: If the ``verbose`` argument is given then extra information is printed. + """ ... -def qstr_info(verbose: Any=None) -> None: - """輸出關於目前駐留字串的資訊。 +def qstr_info(verbose: Any = None) -> None: + """Print information about currently interned strings. -Example: ``micropython.qstr_info()`` + Example: ``micropython.qstr_info()`` -:param verbose: 如果指定 ``verbose`` 引數,則會輸出額外資訊。 + :param verbose: If the ``verbose`` argument is given then extra information is printed. -The information that is printed is implementation dependent, but currently -includes the number of interned strings and the amount of RAM they use. In -verbose mode it prints out the names of all RAM-interned strings.""" + The information that is printed is implementation dependent, but currently + includes the number of interned strings and the amount of RAM they use. In + verbose mode it prints out the names of all RAM-interned strings. + """ ... def stack_use() -> int: - """傳回整數,表示目前正在使用的堆疊數量。 + """Return an integer representing the current amount of stack that is being + used. -Example: ``micropython.stack_use()`` + Example: ``micropython.stack_use()`` -The absolute value of this is not particularly useful, rather it -should be used to compute differences in stack usage at different points. + The absolute value of this is not particularly useful, rather it + should be used to compute differences in stack usage at different points. -:return: An integer representing current stack use.""" + :return: An integer representing current stack use. + """ ... def heap_lock() -> None: - """鎖定堆積。 + """Lock the heap. -Example: ``micropython.heap_lock()`` + Example: ``micropython.heap_lock()`` -When locked no memory allocation can occur and a ``MemoryError`` will be -raised if any heap allocation is attempted.""" + When locked no memory allocation can occur and a ``MemoryError`` will be + raised if any heap allocation is attempted. + """ ... def heap_unlock() -> None: - """解鎖堆積。 + """Unlock the heap. -Example: ``micropython.heap_unlock()`` + Example: ``micropython.heap_unlock()`` -When locked no memory allocation can occur and a ``MemoryError`` will be -raised if any heap allocation is attempted.""" + When locked no memory allocation can occur and a ``MemoryError`` will be + raised if any heap allocation is attempted. + """ ... def kbd_intr(chr: int) -> None: - """設定將觸發 ``KeyboardInterrupt`` 例外狀況的字元。 + """Set the character that will raise a ``KeyboardInterrupt`` exception. -Example: ``micropython.kbd_intr(-1)`` + Example: ``micropython.kbd_intr(-1)`` -:param chr: 用於引發中斷的字元程式碼或 -1,以停用 Ctrl-C 的擷取。 + :param chr: Character code to raise the interrupt or -1 to disable capture of Ctrl-C. -By default this is set to 3 during script execution, corresponding to Ctrl-C. -Passing -1 to this function will disable capture of Ctrl-C, and passing 3 -will restore it. + By default this is set to 3 during script execution, corresponding to Ctrl-C. + Passing -1 to this function will disable capture of Ctrl-C, and passing 3 + will restore it. -This function can be used to prevent the capturing of Ctrl-C on the -incoming stream of characters that is usually used for the REPL, in case -that stream is used for other purposes.""" - ... \ No newline at end of file + This function can be used to prevent the capturing of Ctrl-C on the + incoming stream of characters that is usually used for the REPL, in case + that stream is used for other purposes. + """ + ... diff --git a/lang/zh-tw/typeshed/stdlib/music.pyi b/lang/zh-tw/typeshed/stdlib/music.pyi index 7f81664..5f4778b 100644 --- a/lang/zh-tw/typeshed/stdlib/music.pyi +++ b/lang/zh-tw/typeshed/stdlib/music.pyi @@ -1,128 +1,167 @@ -"""創作和播放旋律。""" +"""Create and play melodies. +""" from typing import Optional, Tuple, Union, List + from .microbit import MicroBitDigitalPin, pin0 + DADADADUM: Tuple[str, ...] -"""旋律:貝多芬 C 小調第五交響曲的開場。""" +"""Melody: the opening to Beethoven’s 5th Symphony in C minor.""" + ENTERTAINER: Tuple[str, ...] -"""旋律:史考特喬普林的名曲《演藝人》開場。""" +"""Melody: the opening fragment of Scott Joplin’s Ragtime classic “The Entertainer”.""" + PRELUDE: Tuple[str, ...] -"""旋律:巴哈 48 首前奏曲與賦格曲 C 大調第一前奏曲的開場。""" +"""Melody: the opening of the first Prelude in C Major of J.S.Bach’s 48 Preludes and Fugues.""" + ODE: Tuple[str, ...] -"""旋律:貝多芬 D 小調第九交響曲中的「歡樂頌」主題。""" +"""Melody: the “Ode to Joy” theme from Beethoven’s 9th Symphony in D minor.""" + NYAN: Tuple[str, ...] -"""旋律:Nyan Cat 主題 (http://www.nyan.cat/)。 +"""Melody: the Nyan Cat theme (http://www.nyan.cat/). The composer is unknown. This is fair use for educational porpoises (as they say in New York).""" + RINGTONE: Tuple[str, ...] -"""旋律:聽起來像手機鈴聲的東西。 +"""Melody: something that sounds like a mobile phone ringtone. To be used to indicate an incoming message. """ + FUNK: Tuple[str, ...] -"""旋律:為特務和犯罪首腦準備的放克貝斯。""" +"""Melody: a funky bass line for secret agents and criminal masterminds.""" + BLUES: Tuple[str, ...] -"""旋律:布基烏基 12 小節藍調走路貝斯。""" +"""Melody: a boogie-woogie 12-bar blues walking bass.""" + BIRTHDAY: Tuple[str, ...] -"""旋律:「祝你生日快樂……」 +"""Melody: “Happy Birthday to You…” For copyright status see: http://www.bbc.co.uk/news/world-us-canada-34332853 """ + WEDDING: Tuple[str, ...] -"""旋律:華格納歌劇《羅恩格林》中的新娘合唱。""" +"""Melody: the bridal chorus from Wagner’s opera “Lohengrin”.""" + FUNERAL: Tuple[str, ...] -"""旋律:《葬禮進行曲》,亦稱為蕭邦的「降 b 小調第二號鋼琴奏鳴曲」。""" +"""Melody: the “funeral march” otherwise known as Frédéric Chopin’s Piano Sonata No. 2 in B♭ minor, Op. 35.""" + PUNCHLINE: Tuple[str, ...] -"""旋律:一段有趣的音樂,表示說了一個笑話。""" +"""Melody: a fun fragment that signifies a joke has been made.""" + PYTHON: Tuple[str, ...] -"""旋律:約翰菲利普蘇薩的進行曲《自由鐘》,又名《蒙提派森的飛行馬戲團》的主題曲 (Python 程式語言以此命名)。""" +"""Melody: John Philip Sousa’s march “Liberty Bell” aka, the theme for “Monty Python’s Flying Circus” (after which the Python programming language is named).""" + BADDY: Tuple[str, ...] -"""旋律:無聲電影時代的惡人登場。""" +"""Melody: silent movie era entrance of a baddy.""" + CHASE: Tuple[str, ...] -"""旋律:無聲電影時代的追逐場景。""" +"""Melody: silent movie era chase scene.""" + BA_DING: Tuple[str, ...] -"""旋律:表示某事發生的短訊號。""" +"""Melody: a short signal to indicate something has happened.""" + WAWAWAWAA: Tuple[str, ...] -"""旋律:非常悲傷的長號。""" +"""Melody: a very sad trombone.""" + JUMP_UP: Tuple[str, ...] -"""旋律:用於遊戲中,代表向上移動。""" +"""Melody: for use in a game, indicating upward movement.""" + JUMP_DOWN: Tuple[str, ...] -"""旋律:用於遊戲中,表示向下移動。""" +"""Melody: for use in a game, indicating downward movement.""" + POWER_UP: Tuple[str, ...] -"""旋律:表示已解鎖成就的號角齊鳴。""" +"""Melody: a fanfare to indicate an achievement unlocked.""" + POWER_DOWN: Tuple[str, ...] -"""旋律:表示失去成就的悲傷號角聲。""" +"""Melody: a sad fanfare to indicate an achievement lost.""" -def set_tempo(ticks: int=4, bpm: int=120) -> None: - """設定播放的大致節奏。 +def set_tempo(ticks: int = 4, bpm: int = 120) -> None: + """Sets the approximate tempo for playback. -Example: ``music.set_tempo(bpm=120)`` + Example: ``music.set_tempo(bpm=120)`` -:param ticks: 構成節拍的滴答聲數。 -:param bpm: 一個整數,決定每分鐘有多少次節拍。 + :param ticks: The number of ticks constituting a beat. + :param bpm: An integer determining how many beats per minute. -Suggested default values allow the following useful behaviour: + Suggested default values allow the following useful behaviour: -- music.set_tempo() – reset the tempo to default of ticks = 4, bpm = 120 -- music.set_tempo(ticks=8) – change the “definition” of a beat -- music.set_tempo(bpm=180) – just change the tempo + - music.set_tempo() – reset the tempo to default of ticks = 4, bpm = 120 + - music.set_tempo(ticks=8) – change the “definition” of a beat + - music.set_tempo(bpm=180) – just change the tempo -To work out the length of a tick in milliseconds is very simple arithmetic: -60000/bpm/ticks_per_beat. For the default values that’s -60000/120/4 = 125 milliseconds or 1 beat = 500 milliseconds.""" + To work out the length of a tick in milliseconds is very simple arithmetic: + 60000/bpm/ticks_per_beat. For the default values that’s + 60000/120/4 = 125 milliseconds or 1 beat = 500 milliseconds. + """ ... def get_tempo() -> Tuple[int, int]: - """以整數元組的形式取得當前節奏:``(ticks, bpm)``。 + """Gets the current tempo as a tuple of integers: ``(ticks, bpm)``. -Example: ``ticks, beats = music.get_tempo()`` + Example: ``ticks, beats = music.get_tempo()`` -:return: The temp as a tuple with two integer values, the ticks then the beats per minute.""" + :return: The temp as a tuple with two integer values, the ticks then the beats per minute. + """ ... -def play(music: Union[str, List[str], Tuple[str, ...]], pin: Optional[MicroBitDigitalPin]=pin0, wait: bool=True, loop: bool=False) -> None: - """播放音樂。 +def play( + music: Union[str, List[str], Tuple[str, ...]], + pin: Optional[MicroBitDigitalPin] = pin0, + wait: bool = True, + loop: bool = False, +) -> None: + """Plays music. -Example: ``music.play(music.NYAN)`` + Example: ``music.play(music.NYAN)`` -:param music: 特殊音符中指定的音樂 `_ -:param pin: (引腳) 用於外接揚聲器的輸出引腳 (預設為 ``pin0``),``None`` 表示無聲音。 -:param wait: 如果 ``wait`` 設定為 ``True``,則此函式會封鎖。 -:param loop: 如果 ``loop`` 設定為 ``True``,樂曲會重複直到呼叫 ``stop`` 或封鎖呼叫被中斷。 + :param music: music specified in `a special notation `_ + :param pin: the output pin for use with an external speaker (default ``pin0``), ``None`` for no sound. + :param wait: If ``wait`` is set to ``True``, this function is blocking. + :param loop: If ``loop`` is set to ``True``, the tune repeats until ``stop`` is called or the blocking call is interrupted. -Many built-in melodies are defined in this module.""" + Many built-in melodies are defined in this module. + """ ... -def pitch(frequency: int, duration: int=-1, pin: Optional[MicroBitDigitalPin]=pin0, wait: bool=True) -> None: - """彈奏一個音符。 (間距) +def pitch( + frequency: int, + duration: int = -1, + pin: Optional[MicroBitDigitalPin] = pin0, + wait: bool = True, +) -> None: + """Play a note. -Example: ``music.pitch(185, 1000)`` + Example: ``music.pitch(185, 1000)`` -:param frequency: (頻率) 整數頻率 -:param duration: 毫秒的持續時間。如果是否定的,則聲音將持續到下一次呼叫或對 ``stop`` 的呼叫。 -:param pin: (引腳) 可選輸出引腳 (預設值 ``pin0``)。 -:param wait: 如果 ``wait`` 設定為 ``True``,則此函式為封鎖。 + :param frequency: An integer frequency + :param duration: A millisecond duration. If negative then sound is continuous until the next call or a call to ``stop``. + :param pin: Optional output pin (default ``pin0``). + :param wait: If ``wait`` is set to ``True``, this function is blocking. -For example, if the frequency is set to 440 and the length to -1000 then we hear a standard concert A for one second. + For example, if the frequency is set to 440 and the length to + 1000 then we hear a standard concert A for one second. -You can only play one pitch on one pin at any one time.""" + You can only play one pitch on one pin at any one time. + """ ... -def stop(pin: Optional[MicroBitDigitalPin]=pin0) -> None: - """停止內建揚聲器上的所有音樂播放和任何引腳輸出聲音。 +def stop(pin: Optional[MicroBitDigitalPin] = pin0) -> None: + """Stops all music playback on the built-in speaker and any pin outputting sound. -Example: ``music.stop()`` + Example: ``music.stop()`` -:param pin: (引腳) 可以提供一個可選引數來指定一個引腳,例如 ``music.stop(pin1)``。""" + :param pin: An optional argument can be provided to specify a pin, e.g. ``music.stop(pin1)``. + """ def reset() -> None: - """將 ticks、bpm、duration 和 octave 重設為其預設值。 + """Resets ticks, bpm, duration and octave to their default values. -Example: ``music.reset()`` + Example: ``music.reset()`` -Values: -- ``ticks = 4`` -- ``bpm = 120`` -- ``duration = 4`` -- ``octave = 4``""" - ... \ No newline at end of file + Values: + - ``ticks = 4`` + - ``bpm = 120`` + - ``duration = 4`` + - ``octave = 4`` + """ + ... diff --git a/lang/zh-tw/typeshed/stdlib/neopixel.pyi b/lang/zh-tw/typeshed/stdlib/neopixel.pyi index 45b5b35..2d5a749 100644 --- a/lang/zh-tw/typeshed/stdlib/neopixel.pyi +++ b/lang/zh-tw/typeshed/stdlib/neopixel.pyi @@ -1,81 +1,82 @@ -"""可獨立尋址的 RGB 和 RGBW LED 燈條。""" +"""Individually addressable RGB and RGBW LED strips. +""" from .microbit import MicroBitDigitalPin from typing import Tuple class NeoPixel: + def __init__(self, pin: MicroBitDigitalPin, n: int, bpp: int = 3) -> None: + """Initialise a new strip of neopixel LEDs controlled via a pin. - def __init__(self, pin: MicroBitDigitalPin, n: int, bpp: int=3) -> None: - """初始化透過引腳控制的 NeoPixel LED 燈條。 + Example: ``np = neopixel.NeoPixel(pin0, 8)`` -Example: ``np = neopixel.NeoPixel(pin0, 8)`` + To support RGBW neopixels, a third argument can be passed to + ``NeoPixel`` to indicate the number of bytes per pixel (``bpp``). + For RGBW, this is is 4 rather than the default of 3 for RGB and GRB. -To support RGBW neopixels, a third argument can be passed to -``NeoPixel`` to indicate the number of bytes per pixel (``bpp``). -For RGBW, this is is 4 rather than the default of 3 for RGB and GRB. + Each pixel is addressed by a position (starting from 0). Neopixels are + given RGB (red, green, blue) / RGBW (red, green, blue, white) values + between 0-255 as a tuple. For example, in RGB, ``(255,255,255)`` is + white. In RGBW, ``(255,255,255,0)`` or ``(0,0,0,255)`` is white. -Each pixel is addressed by a position (starting from 0). Neopixels are -given RGB (red, green, blue) / RGBW (red, green, blue, white) values -between 0-255 as a tuple. For example, in RGB, ``(255,255,255)`` is -white. In RGBW, ``(255,255,255,0)`` or ``(0,0,0,255)`` is white. + See `the online docs `_ for warnings and other advice. -See `the online docs `_ for warnings and other advice. - -:param pin: (引腳) 控制 NeoPixel 燈條的引腳。 -:param n: 燈條中的 NeoPixel 數。 -:param bpp: 各像素位元組數。對於 RGBW neopixel 支援,傳遞 4 而不是 RGB 和 GRB 的預設值 3。""" + :param pin: The pin controlling the neopixel strip. + :param n: The number of neopixels in the strip. + :param bpp: Bytes per pixel. For RGBW neopixel support, pass 4 rather than the default of 3 for RGB and GRB. + """ ... - def clear(self) -> None: - """清除所有像素。 + """Clear all the pixels. -Example: ``np.clear()``""" + Example: ``np.clear()`` + """ ... - def show(self) -> None: - """顯示像素。 + """Show the pixels. -Example: ``np.show()`` + Example: ``np.show()`` -Must be called for any updates to become visible.""" + Must be called for any updates to become visible. + """ ... - def write(self) -> None: - """顯示像素 (僅限 micro:bit V2)。 + """Show the pixels (micro:bit V2 only). -Example: ``np.write()`` + Example: ``np.write()`` -Must be called for any updates to become visible. + Must be called for any updates to become visible. -Equivalent to ``show``.""" + Equivalent to ``show``. + """ ... - def fill(self, colour: Tuple[int, ...]) -> None: - """用特定 RGB/RGBW 值為所有像素著色 (僅限 micro:bit V2)。 + """Colour all pixels a given RGB/RGBW value (micro:bit V2 only). -Example: ``np.fill((0, 0, 255))`` + Example: ``np.fill((0, 0, 255))`` -:param colour: 長度與每像素位元組數 (bpp) 相同的元組。 + :param colour: A tuple of the same length as the number of bytes per pixel (bpp). -Use in conjunction with ``show()`` to update the neopixels.""" + Use in conjunction with ``show()`` to update the neopixels. + """ ... - def __setitem__(self, key: int, value: Tuple[int, ...]) -> None: - """設定像素顏色。 + """Set a pixel colour. -Example: ``np[0] = (255, 0, 0)`` - -:param key: 像素編號。 -:param value: 顏色。""" + Example: ``np[0] = (255, 0, 0)`` + :param key: The pixel number. + :param value: The colour. + """ def __getitem__(self, key: int) -> Tuple[int, ...]: - """取得像素顏色。 - -Example: ``r, g, b = np[0]`` + """Get a pixel colour. -:param key: 像素編號。 -:return: The colour tuple.""" + Example: ``r, g, b = np[0]`` + :param key: The pixel number. + :return: The colour tuple. + """ def __len__(self) -> int: - """取得此像素燈條的長度。 + """Get length of this pixel strip. -Example: ``len(np)``""" \ No newline at end of file + Example: ``len(np)`` + """ diff --git a/lang/zh-tw/typeshed/stdlib/os.pyi b/lang/zh-tw/typeshed/stdlib/os.pyi index cf8c724..2f2db77 100644 --- a/lang/zh-tw/typeshed/stdlib/os.pyi +++ b/lang/zh-tw/typeshed/stdlib/os.pyi @@ -1,63 +1,73 @@ -"""存取檔案系統。""" +"""Access the file system. +""" + from typing import Tuple from typing import List def listdir() -> List[str]: - """列出檔案。 + """List files. -Example: ``os.listdir()`` + Example: ``os.listdir()`` -:return: A list of the names of all the files contained within the local -persistent on-device file system.""" + :return: A list of the names of all the files contained within the local + persistent on-device file system. + """ ... def remove(filename: str) -> None: - """移除 (刪除) 一個檔案。 + """Remove (delete) a file. -Example: ``os.remove('data.txt')`` + Example: ``os.remove('data.txt')`` -:param filename: 要刪除的檔案。 + :param filename: The file to delete. -If the file does not exist an ``OSError`` exception will occur.""" + If the file does not exist an ``OSError`` exception will occur. + """ ... def size(filename: str) -> int: - """傳回檔案的大小。 + """Returns the size of a file. -Example: ``os.size('data.txt')`` + Example: ``os.size('data.txt')`` -:param filename: 檔案 -:return: The size in bytes. + :param filename: The file + :return: The size in bytes. -If the file does not exist an ``OSError`` exception will occur.""" + If the file does not exist an ``OSError`` exception will occur. + """ class uname_result(Tuple[str, str, str, str, str]): - """``os.uname()`` 的結果""" + """Result of ``os.uname()``""" sysname: str - """作業系統名稱。""" + """Operating system name.""" + nodename: str - """網路上的機器名稱 (執行定義)。""" + """Name of machine on network (implementation-defined).""" + release: str - """作業系統發佈。""" + """Operating system release.""" + version: str - """作業系統版本。""" + """Operating system version.""" + machine: str - """硬體識別碼。""" + """Hardware identifier.""" def uname() -> uname_result: - """傳回識別目前作業系統的資訊。 + """Returns information identifying the current operating system. -Example: ``os.uname()`` + Example: ``os.uname()`` -The return value is an object with five attributes: + The return value is an object with five attributes: -- ``sysname`` - operating system name -- ``nodename`` - name of machine on network (implementation-defined) -- ``release`` - operating system release -- ``version`` - operating system version -- ``machine`` - hardware identifier + - ``sysname`` - operating system name + - ``nodename`` - name of machine on network (implementation-defined) + - ``release`` - operating system release + - ``version`` - operating system version + - ``machine`` - hardware identifier -There is no underlying operating system in MicroPython. As a result the -information returned by the ``uname`` function is mostly useful for -versioning details.""" - ... \ No newline at end of file + There is no underlying operating system in MicroPython. As a result the + information returned by the ``uname`` function is mostly useful for + versioning details. + """ + ... diff --git a/lang/zh-tw/typeshed/stdlib/radio.pyi b/lang/zh-tw/typeshed/stdlib/radio.pyi index 94a4b6d..8dd0267 100644 --- a/lang/zh-tw/typeshed/stdlib/radio.pyi +++ b/lang/zh-tw/typeshed/stdlib/radio.pyi @@ -1,131 +1,152 @@ -"""使用內建無線電在 micro:bits 之間進行通訊。 (無線電)""" +"""Communicate between micro:bits with the built-in radio. +""" + from _typeshed import WriteableBuffer from typing import Optional, Tuple + RATE_1MBIT: int -"""常數用於指示每秒 1 MBit 的輸送量。""" +"""Constant used to indicate a throughput of 1 MBit a second.""" + RATE_2MBIT: int -"""常數用於指示每秒 2 MBit 的輸送量。""" +"""Constant used to indicate a throughput of 2 MBit a second.""" def on() -> None: - """開啟無線電。 + """Turns the radio on. -Example: ``radio.on()`` + Example: ``radio.on()`` -This needs to be explicitly called since the radio draws power and takes -up memory that you may otherwise need.""" + This needs to be explicitly called since the radio draws power and takes + up memory that you may otherwise need. + """ ... def off() -> None: - """關閉無線電,節省電量和記憶體。 + """Turns off the radio, saving power and memory. -Example: ``radio.off()``""" + Example: ``radio.off()`` + """ ... -def config(length: int=32, queue: int=3, channel: int=7, power: int=6, address: int=1969383796, group: int=0, data_rate: int=RATE_1MBIT) -> None: - """設定無線電。 - -Example: ``radio.config(group=42)`` - -The default configuration is suitable for most use. - -:param length: (default=32) 定義透過無線電傳送的訊息的最大長度 (以位元組為單位)。 -最長可達 251 個位元組 (S0、LENGTH 和 S1 前序編碼為 254 - 3 個位元組)。 -:param queue: (default=3) 指定可以存儲在傳入訊息佇列中的訊息數。 -如果佇列中沒有空間可留給傳入訊息,則捨棄傳入訊息。 -:param channel: (default=7) 一個從 0 到 83 (包含) 的整數值,定義無線電調整到的任意 "channel"。 -訊息將透過此頻道傳送,只有透過此頻道接收的訊息,才會放入傳入訊息佇列。 -每一步都是 1MHz 寬,以 2400MHz 為基礎。 -:param power: (default=6) 是一個從 0 到 7 (包含) 的整數值,表示無線電訊息時使用的訊號功率。 -數值越高,訊號越強,但裝置消耗的功率越多。編號轉換為下列 dBm (分貝毫瓦) 數值列表中的位置:-30、-20、-16、-12、-8、-4、0、4。 -:param address: (default=0x75626974) 任意名稱,表示為 32 位元位址,用於在硬體等級篩選傳入的資料套件,僅保留與您設定的位址相符的那些。 -其他 micro:bit 相關平台使用的預設設定,則是此處使用的預設設定。 -:param group: (default=0) 篩選訊息時與 ``address`` 一起使用的 8 位元值 (0-255)。 -從概念上講,"address" 就像一個家庭/辦公室地址,而 "group" 就像您要向該地址傳送訊息的人。 -:param data_rate: (default=``radio.RATE_1MBIT``) 表示資料輸送量發生的速度。 -可以是 ``radio`` 模組中定義的下列常數之一:``RATE_250KBIT``、``RATE_1MBIT`` 或 ``RATE_2MBIT``。 - -If ``config`` is not called then the defaults described above are assumed.""" +def config( + length: int = 32, + queue: int = 3, + channel: int = 7, + power: int = 6, + address: int = 0x75626974, + group: int = 0, + data_rate: int = RATE_1MBIT, +) -> None: + """Configures the radio. + + Example: ``radio.config(group=42)`` + + The default configuration is suitable for most use. + + :param length: (default=32) defines the maximum length, in bytes, of a message sent via the radio. + It can be up to 251 bytes long (254 - 3 bytes for S0, LENGTH and S1 preamble). + :param queue: (default=3) specifies the number of messages that can be stored on the incoming message queue. + If there are no spaces left on the queue for incoming messages, then the incoming message is dropped. + :param channel: (default=7) an integer value from 0 to 83 (inclusive) that defines an arbitrary "channel" to which the radio is tuned. + Messages will be sent via this channel and only messages received via this channel will be put onto the incoming message queue. Each step is 1MHz wide, based at 2400MHz. + :param power: (default=6) is an integer value from 0 to 7 (inclusive) to indicate the strength of signal used when broadcasting a message. + The higher the value the stronger the signal, but the more power is consumed by the device. The numbering translates to positions in the following list of dBm (decibel milliwatt) values: -30, -20, -16, -12, -8, -4, 0, 4. + :param address: (default=0x75626974) an arbitrary name, expressed as a 32-bit address, that's used to filter incoming packets at the hardware level, keeping only those that match the address you set. + The default used by other micro:bit related platforms is the default setting used here. + :param group: (default=0) an 8-bit value (0-255) used with the ``address`` when filtering messages. + Conceptually, "address" is like a house/office address and "group" is like the person at that address to which you want to send your message. + :param data_rate: (default=``radio.RATE_1MBIT``) indicates the speed at which data throughput takes place. + Can be one of the following constants defined in the ``radio`` module: ``RATE_250KBIT``, ``RATE_1MBIT`` or ``RATE_2MBIT``. + + If ``config`` is not called then the defaults described above are assumed. + """ ... def reset() -> None: - """將設定重設為其預設值。 + """Reset the settings to their default values. -Example: ``radio.reset()`` + Example: ``radio.reset()`` -The defaults as as per the ``config`` function above.""" + The defaults as as per the ``config`` function above. + """ ... def send_bytes(message: bytes) -> None: - """傳送包含位元組的訊息。 + """Sends a message containing bytes. -Example: ``radio.send_bytes(b'hello')`` + Example: ``radio.send_bytes(b'hello')`` -:param message: 要傳送的位元組。""" + :param message: The bytes to send. + """ ... def receive_bytes() -> Optional[bytes]: - """接收訊息佇列中的下一則傳入訊息。 + """Receive the next incoming message on the message queue. -Example: ``radio.receive_bytes()`` + Example: ``radio.receive_bytes()`` -:return: The message bytes if any, otherwise ``None``.""" + :return: The message bytes if any, otherwise ``None``. + """ ... def receive_bytes_into(buffer: WriteableBuffer) -> Optional[int]: - """將訊息佇列中的下一則傳入訊息複製到緩衝區。 + """Copy the next incoming message on the message queue into a buffer. -Example: ``radio.receive_bytes_info(buffer)`` + Example: ``radio.receive_bytes_info(buffer)`` -:param buffer: 目標緩衝區。如果訊息大小大於緩衝區,則訊息會被截斷。 -:return: ``None`` if there are no pending messages, otherwise it returns the length of the message (which might be more than the length of the buffer).""" + :param buffer: The target buffer. The message is truncated if larger than the buffer. + :return: ``None`` if there are no pending messages, otherwise it returns the length of the message (which might be more than the length of the buffer). + """ ... def send(message: str) -> None: - """傳送訊息字串。 + """Sends a message string. -Example: ``radio.send('hello')`` + Example: ``radio.send('hello')`` -This is the equivalent of ``radio.send_bytes(bytes(message, 'utf8'))`` but with ``b'\x01\x00\x01'`` -prepended to the front (to make it compatible with other platforms that target the micro:bit). + This is the equivalent of ``radio.send_bytes(bytes(message, 'utf8'))`` but with ``b'\x01\x00\x01'`` + prepended to the front (to make it compatible with other platforms that target the micro:bit). -:param message: 要傳送的字串。""" + :param message: The string to send. + """ ... def receive() -> Optional[str]: - """工作方式與 ``receive_bytes`` 完全相同,但會傳回傳送的任何內容。 + """Works in exactly the same way as ``receive_bytes`` but returns whatever was sent. -Example: ``radio.receive()`` + Example: ``radio.receive()`` -Equivalent to ``str(receive_bytes(), 'utf8')`` but with a check that the the first -three bytes are ``b'\x01\x00\x01'`` (to make it compatible with other platforms that -may target the micro:bit). + Equivalent to ``str(receive_bytes(), 'utf8')`` but with a check that the the first + three bytes are ``b'\x01\x00\x01'`` (to make it compatible with other platforms that + may target the micro:bit). -:return: The message with the prepended bytes stripped and converted to a string. + :return: The message with the prepended bytes stripped and converted to a string. -A ``ValueError`` exception is raised if conversion to string fails.""" + A ``ValueError`` exception is raised if conversion to string fails. + """ ... def receive_full() -> Optional[Tuple[bytes, int, int]]: - """傳回一個包含三個數值的元組,用來代表訊息佇列中的下一則傳入訊息。 + """Returns a tuple containing three values representing the next incoming message on the message queue. -Example: ``radio.receive_full()`` + Example: ``radio.receive_full()`` -If there are no pending messages then ``None`` is returned. + If there are no pending messages then ``None`` is returned. -The three values in the tuple represent: + The three values in the tuple represent: -- the next incoming message on the message queue as bytes. -- the RSSI (signal strength): a value between 0 (strongest) and -255 (weakest) as measured in dBm. -- a microsecond timestamp: the value returned by ``time.ticks_us()`` when the message was received. + - the next incoming message on the message queue as bytes. + - the RSSI (signal strength): a value between 0 (strongest) and -255 (weakest) as measured in dBm. + - a microsecond timestamp: the value returned by ``time.ticks_us()`` when the message was received. -For example:: + For example:: - details = radio.receive_full() - if details: - msg, rssi, timestamp = details + details = radio.receive_full() + if details: + msg, rssi, timestamp = details -This function is useful for providing information needed for triangulation -and/or trilateration with other micro:bit devices. + This function is useful for providing information needed for triangulation + and/or trilateration with other micro:bit devices. -:return: ``None`` if there is no message, otherwise a tuple of length three with the bytes, strength and timestamp values.""" - ... \ No newline at end of file + :return: ``None`` if there is no message, otherwise a tuple of length three with the bytes, strength and timestamp values. + """ + ... diff --git a/lang/zh-tw/typeshed/stdlib/random.pyi b/lang/zh-tw/typeshed/stdlib/random.pyi index e606e08..a2c2ef3 100644 --- a/lang/zh-tw/typeshed/stdlib/random.pyi +++ b/lang/zh-tw/typeshed/stdlib/random.pyi @@ -1,80 +1,93 @@ -"""生成隨機數。""" +"""Generate random numbers. +""" from typing import TypeVar, Sequence, Union, overload def getrandbits(n: int) -> int: - """生成具有 ``n`` 個隨機位元的整數。 + """Generate an integer with ``n`` random bits. -Example: ``random.getrandbits(1)`` + Example: ``random.getrandbits(1)`` -:param n: 介於 1-30 (包含) 之間的值。""" + :param n: A value between 1-30 (inclusive). + """ ... def seed(n: int) -> None: - """初始化隨機數生成器。 + """Initialize the random number generator. -Example: ``random.seed(0)`` + Example: ``random.seed(0)`` -:param n: 整數種子 + :param n: The integer seed -This will give you reproducibly deterministic randomness from a given starting -state (``n``).""" + This will give you reproducibly deterministic randomness from a given starting + state (``n``). + """ ... def randint(a: int, b: int) -> int: - """在 ``a`` 和 ``b`` (包含) 之間選擇一個隨機整數。 + """Choose a random integer between ``a`` and ``b`` inclusive. -Example: ``random.randint(0, 9)`` + Example: ``random.randint(0, 9)`` -:param a: 範圍的起始值 (包含) -:param b: 範圍的結束值 (包含) + :param a: Start value for the range (inclusive) + :param b: End value for the range (inclusive) -Alias for ``randrange(a, b + 1)``.""" + Alias for ``randrange(a, b + 1)``. + """ ... @overload def randrange(stop: int) -> int: - """在零到 (但不包括) ``stop`` 之間隨機選擇一個整數。 + """Choose a randomly selected integer between zero and up to (but not + including) ``stop``. -Example: ``random.randrange(10)`` + Example: ``random.randrange(10)`` -:param stop: 範圍的結束值 (排除)""" + :param stop: End value for the range (exclusive) + """ ... @overload -def randrange(start: int, stop: int, step: int=1) -> int: - """從 ``range(start, stop, step)`` 中選擇一個隨機選擇的元素。 +def randrange(start: int, stop: int, step: int = 1) -> int: + """ + Choose a randomly selected element from ``range(start, stop, step)``. -Example: ``random.randrange(0, 10)`` + Example: ``random.randrange(0, 10)`` -:param start: 範圍的開始 (包含) -:param stop: 範圍結束 (排除) -:param step: 步驟。""" + :param start: The start of the range (inclusive) + :param stop: The end of the range (exclusive) + :param step: The step. + """ ... -_T = TypeVar('_T') + +_T = TypeVar("_T") def choice(seq: Sequence[_T]) -> _T: - """從非空序列 ``seq`` 中選擇一個隨機元素。 + """Choose a random element from the non-empty sequence ``seq``. -Example: ``random.choice([Image.HAPPY, Image.SAD])`` + Example: ``random.choice([Image.HAPPY, Image.SAD])`` -:param seq: 序列。 + :param seq: A sequence. -If ``seq`` is empty, raises ``IndexError``.""" + If ``seq`` is empty, raises ``IndexError``. + """ ... def random() -> float: - """在 [0.0, 1.0) 範圍內生成一個隨機浮點數。 + """Generate a random floating point number in the range [0.0, 1.0). -Example: ``random.random()`` + Example: ``random.random()`` -:return: The random floating point number""" + :return: The random floating point number + """ ... def uniform(a: float, b: float) -> float: - """傳回一個介於 ``a`` 和 ``b`` 之間的隨機浮點數。 + """ + Return a random floating point number between ``a`` and ``b`` inclusive. -Example: ``random.uniform(0, 9)`` + Example: ``random.uniform(0, 9)`` -:param a: 範圍的起始值 (包括) -:param b: 範圍的結束值 (包含)""" - ... \ No newline at end of file + :param a: Start value for the range (inclusive) + :param b: End value for the range (inclusive) + """ + ... diff --git a/lang/zh-tw/typeshed/stdlib/speech.pyi b/lang/zh-tw/typeshed/stdlib/speech.pyi index 01137a7..349d188 100644 --- a/lang/zh-tw/typeshed/stdlib/speech.pyi +++ b/lang/zh-tw/typeshed/stdlib/speech.pyi @@ -1,79 +1,106 @@ -"""讓 micro:bit 說話、唱歌和發出類似聲音的其他語音。""" +"""Make the micro:bit talk, sing and make other speech like sounds. +""" + from typing import Optional from .microbit import MicroBitDigitalPin, pin0 def translate(words: str) -> str: - """將英語單字翻譯成音素。 + """Translate English words to phonemes. -Example: ``speech.translate('hello world')`` + Example: ``speech.translate('hello world')`` -:param words: 英文單字字串。 -:return: A string containing a best guess at the appropriate phonemes to pronounce. -The output is generated from this `text to phoneme translation table `_. + :param words: A string of English words. + :return: A string containing a best guess at the appropriate phonemes to pronounce. + The output is generated from this `text to phoneme translation table `_. -This function should be used to generate a first approximation of phonemes -that can be further hand-edited to improve accuracy, inflection and -emphasis. + This function should be used to generate a first approximation of phonemes + that can be further hand-edited to improve accuracy, inflection and + emphasis. -See `the online documentation `_ for detailed information.""" + See `the online documentation `_ for detailed information. + """ ... -def pronounce(phonemes: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: Optional[MicroBitDigitalPin]=pin0) -> None: - """發出音素的聲音。 - -Example: ``speech.pronounce(' /HEHLOW WERLD')`` - -:param phonemes: 發音的音素字串 -:param pitch: (間距) 一個代表聲音音高的數字 -:param speed: 一個代表聲音速度的數字 -:param mouth: 一個代表聲音口型的數字 -:param throat: 一個代表聲音喉型的數字 -:param pin: (引腳) 指定輸出引腳的可選引數,可用於覆寫預設值 ``pin0``。 -如果我們不想從引腳上播放任何聲音,可以使用 ``pin=None``。僅限 micro:bit。 - -Override the optional pitch, speed, mouth and throat settings to change the -timbre (quality) of the voice. - -See `the online documentation `_ for detailed information.""" +def pronounce( + phonemes: str, + pitch: int = 64, + speed: int = 72, + mouth: int = 128, + throat: int = 128, + pin: Optional[MicroBitDigitalPin] = pin0, +) -> None: + """Pronounce phonemes. + + Example: ``speech.pronounce(' /HEHLOW WERLD')`` + + :param phonemes: The string of phonemes to pronounce + :param pitch: A number representing the pitch of the voice + :param speed: A number representing the speed of the voice + :param mouth: A number representing the mouth of the voice + :param throat: A number representing the throat of the voice + :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. + If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. + + Override the optional pitch, speed, mouth and throat settings to change the + timbre (quality) of the voice. + + See `the online documentation `_ for detailed information. + """ ... -def say(words: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: MicroBitDigitalPin=pin0) -> None: - """說英語單字。 - -Example: ``speech.say('hello world')`` - -:param words: 要說的一串詞。 -:param pitch: (間距) 一個代表聲音音高的數字 -:param speed: 一個代表聲音速度的數字 -:param mouth: 一個代表聲音口型的數字 -:param throat: 一個代表聲音喉型的數字 -:param pin: (引腳) 指定輸出引腳的可選引數可用於覆寫預設值 ``pin0``。 -如果我們無意從引腳上播放任何聲音,可以使用 ``pin=None``。僅限 micro:bit。 - -The result is semi-accurate for English. Override the optional pitch, speed, -mouth and throat settings to change the timbre (quality) of the voice. - -This is a short-hand equivalent of: -``speech.pronounce(speech.translate(words))`` - -See `the online documentation `_ for detailed information.""" +def say( + words: str, + pitch: int = 64, + speed: int = 72, + mouth: int = 128, + throat: int = 128, + pin: MicroBitDigitalPin = pin0, +) -> None: + """Say English words. + + Example: ``speech.say('hello world')`` + + :param words: The string of words to say. + :param pitch: A number representing the pitch of the voice + :param speed: A number representing the speed of the voice + :param mouth: A number representing the mouth of the voice + :param throat: A number representing the throat of the voice + :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. + If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. + + The result is semi-accurate for English. Override the optional pitch, speed, + mouth and throat settings to change the timbre (quality) of the voice. + + This is a short-hand equivalent of: + ``speech.pronounce(speech.translate(words))`` + + See `the online documentation `_ for detailed information. + """ ... -def sing(phonemes: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: MicroBitDigitalPin=pin0) -> None: - """唱出音素。 - -Example: ``speech.sing(' /HEHLOW WERLD')`` - -:param phonemes: 要唱的一串詞。 -:param pitch: (間距) 一個代表聲音音高的數字 -:param speed: 一個代表聲音速度的數字 -:param mouth: 一個代表聲音口型的數字 -:param throat: 一個代表聲音喉型的數字 -:param pin: (引腳) 指定輸出引腳的可選引數,可用於覆寫預設值 ``pin0``。 -如果我們不想從引腳上播放任何聲音,可以使用 ``pin=None``。僅限 micro:bit。 - -Override the optional pitch, speed, mouth and throat settings to change -the timbre (quality) of the voice. - -See `the online documentation `_ for detailed information.""" - ... \ No newline at end of file +def sing( + phonemes: str, + pitch: int = 64, + speed: int = 72, + mouth: int = 128, + throat: int = 128, + pin: MicroBitDigitalPin = pin0, +) -> None: + """Sing phonemes. + + Example: ``speech.sing(' /HEHLOW WERLD')`` + + :param phonemes: The string of words to sing. + :param pitch: A number representing the pitch of the voice + :param speed: A number representing the speed of the voice + :param mouth: A number representing the mouth of the voice + :param throat: A number representing the throat of the voice + :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. + If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. + + Override the optional pitch, speed, mouth and throat settings to change + the timbre (quality) of the voice. + + See `the online documentation `_ for detailed information. + """ + ... diff --git a/lang/zh-tw/typeshed/stdlib/struct.pyi b/lang/zh-tw/typeshed/stdlib/struct.pyi index fbe57da..53b3e0b 100644 --- a/lang/zh-tw/typeshed/stdlib/struct.pyi +++ b/lang/zh-tw/typeshed/stdlib/struct.pyi @@ -1,56 +1,65 @@ -"""壓縮和解壓縮原始資料類型。""" +"""Pack and unpack primitive data types. +""" + from _typeshed import ReadableBuffer, WriteableBuffer from typing import Any, Tuple, Union def calcsize(fmt: str) -> int: - """取得存儲特定 ``fmt`` 所需的位元組數。 + """Get the number of bytes needed to store the given ``fmt``. -Example: ``struct.calcsize('hf')`` + Example: ``struct.calcsize('hf')`` -:param fmt: 格式字串。 -:return The number of bytes needed to store such a value.""" + :param fmt: A format string. + :return The number of bytes needed to store such a value. + """ ... def pack(fmt: str, v1: Any, *vn: Any) -> bytes: - """根據格式字串,壓縮數值。 + """Pack values according to a format string. -Example: ``struct.pack('hf', 1, 3.1415)`` + Example: ``struct.pack('hf', 1, 3.1415)`` -:param fmt: 格式字串。 -:param v1: 首位數值。 -:param *vn: 剩餘數值。 -:return A bytes object encoding the values.""" + :param fmt: The format string. + :param v1: The first value. + :param *vn: The remaining values. + :return A bytes object encoding the values. + """ ... -def pack_into(fmt: str, buffer: WriteableBuffer, offset: int, v1: Any, *vn: Any) -> None: - """根據格式字串,壓縮數值。 +def pack_into( + fmt: str, buffer: WriteableBuffer, offset: int, v1: Any, *vn: Any +) -> None: + """Pack values according to a format string. -Example: ``struct.pack_info('hf', buffer, 1, 3.1415)`` + Example: ``struct.pack_info('hf', buffer, 1, 3.1415)`` -:param fmt: 格式字串。 -:param buffer: 要寫入的緩衝區。 -:param offset: 緩衝區內的位移。從緩衝區結尾開始計數,該位移可能為負數。 -:param v1: 首位數值。 -:param *vn: 剩餘數值。""" + :param fmt: The format string. + :param buffer: The target buffer to write into. + :param offset: The offset into the buffer. May be negative to count from the end of the buffer. + :param v1: The first value. + :param *vn: The remaining values. + """ ... def unpack(fmt: str, data: ReadableBuffer) -> Tuple[Any, ...]: - """根據格式字串,解壓縮數值。 + """Unpack data according to a format string. -Example: ``v1, v2 = struct.unpack('hf', buffer)`` + Example: ``v1, v2 = struct.unpack('hf', buffer)`` -:param fmt: 格式字串。 -:param data: 資料。 -:return: A tuple of the unpacked values.""" + :param fmt: The format string. + :param data: The data. + :return: A tuple of the unpacked values. + """ ... -def unpack_from(fmt: str, buffer: ReadableBuffer, offset: int=0) -> Tuple: - """根據格式字串,從緩衝區解壓縮資料。 +def unpack_from(fmt: str, buffer: ReadableBuffer, offset: int = 0) -> Tuple: + """Unpack data from a buffer according to a format string. -Example: ``v1, v2 = struct.unpack_from('hf', buffer)`` + Example: ``v1, v2 = struct.unpack_from('hf', buffer)`` -:param fmt: 格式字串。 -:param buffer: 要讀取的來源緩衝區。 -:param offset: 緩衝區內的位移。從緩衝區結尾開始計數,該位移可能為負數。 -:return: A tuple of the unpacked values.""" - ... \ No newline at end of file + :param fmt: The format string. + :param buffer: The source buffer to read from. + :param offset: The offset into the buffer. May be negative to count from the end of the buffer. + :return: A tuple of the unpacked values. + """ + ... diff --git a/lang/zh-tw/typeshed/stdlib/sys.pyi b/lang/zh-tw/typeshed/stdlib/sys.pyi index 3342ae5..320bac9 100644 --- a/lang/zh-tw/typeshed/stdlib/sys.pyi +++ b/lang/zh-tw/typeshed/stdlib/sys.pyi @@ -1,36 +1,43 @@ -"""系統特定函式""" +"""System specific functions""" + from typing import Any, Dict, List, NoReturn, TextIO, Tuple -def exit(retval: object=...) -> NoReturn: - """使用指定的退出代碼來終止當前程式。 +def exit(retval: object = ...) -> NoReturn: + """Terminate current program with a given exit code. -Example: ``sys.exit(1)`` + Example: ``sys.exit(1)`` -This function raises a ``SystemExit`` exception. If an argument is given, its -value given as an argument to ``SystemExit``. + This function raises a ``SystemExit`` exception. If an argument is given, its + value given as an argument to ``SystemExit``. -:param retval: 退出代碼或訊息。""" + :param retval: The exit code or message. + """ ... def print_exception(exc: Exception) -> None: - """輸出帶有回溯的例外狀況。 + """ + Print an exception with a traceback. + + Example: ``sys.print_exception(e)`` -Example: ``sys.print_exception(e)`` + :param exc: The exception to print -:param exc: 輸出例外狀況 + This is simplified version of a function which appears in the + ``traceback`` module in CPython. + """ -This is simplified version of a function which appears in the -``traceback`` module in CPython.""" argv: List[str] -"""目前程式啟動時,所使用的可變引數列表。""" +"""A mutable list of arguments the current program was started with.""" + byteorder: str -"""系統的位元組順序 (``"little"`` 或 ``"big"``)。""" +"""The byte order of the system (``"little"`` or ``"big"``).""" class _implementation: name: str version: Tuple[int, int, int] + implementation: _implementation -"""包含關於目前 Python 執行資訊的物件。 +"""Object with information about the current Python implementation. For MicroPython, it has following attributes: @@ -44,9 +51,13 @@ minimal ports). CPython mandates more attributes for this object, but the actual useful bare minimum is implemented in MicroPython. """ + maxsize: int """ -本機整數類型在當前平台上可以保存的最大值,或 MicroPython 整數類型可表示的最大值,如果它小於平台最大值 (對於沒有 long int 支援的 MicroPython 連接埠,就是這種情況)。 +Maximum value which a native integer type can hold on the current platform, +or maximum value representable by MicroPython integer type, if it's smaller +than platform max value (that is the case for MicroPython ports without +long int support). This attribute is useful for detecting "bitness" of a platform (32-bit vs 64-bit, etc.). It's recommended to not compare this attribute to some @@ -66,14 +77,17 @@ value directly, but instead count number of bits in it:: # (e.g. 31) due to peculiarities described above, so use "> 16", # "> 32", "> 64" style of comparisons. """ + modules: Dict[str, Any] -"""已載入模組的字典。 +"""Dictionary of loaded modules. On some ports, it may not include builtin modules.""" + path: List[str] -"""用於搜尋匯入模組的可變字典列表。""" +"""A mutable list of directories to search for imported modules.""" + platform: str -"""正在執行 MicroPython 的平台。 +"""The platform that MicroPython is running on. For OS/RTOS ports, this is usually an identifier of the OS, e.g. ``"linux"``. For baremetal ports it is an identifier of a board, e.g. ``"pyboard"`` for @@ -83,11 +97,13 @@ distinguish one board from another. If you need to check whether your program runs on MicroPython (vs other Python implementation), use ``sys.implementation`` instead. """ + version: str -"""此執行符合的 Python 語言版本,做為字串。""" +"""Python language version that this implementation conforms to, as a string.""" + version_info: Tuple[int, int, int] -"""此執行符合的 Python 語言版本,做為整數元組。 +"""Python language version that this implementation conforms to, as a tuple of ints. Only the first three version numbers (major, minor, micro) are supported and they can be referenced only by index, not by name. -""" \ No newline at end of file +""" diff --git a/lang/zh-tw/typeshed/stdlib/time.pyi b/lang/zh-tw/typeshed/stdlib/time.pyi index 2a7d325..598c483 100644 --- a/lang/zh-tw/typeshed/stdlib/time.pyi +++ b/lang/zh-tw/typeshed/stdlib/time.pyi @@ -1,112 +1,132 @@ -"""測量時間並為程式增加延遲。""" +"""Measure time and add delays to programs. +""" + from typing import Union def sleep(seconds: Union[int, float]) -> None: - """延遲秒數。 + """ + Delay a number of seconds. -Example: ``time.sleep(1)`` + Example: ``time.sleep(1)`` -:param seconds: 睡眠的秒數。 -使用浮點數代表睡眠秒數的小數。""" + :param seconds: The number of seconds to sleep for. + Use a floating-point number to sleep for a fractional number of seconds. + """ ... def sleep_ms(ms: int) -> None: - """延遲指定的毫秒數。 + """ + Delay for given number of milliseconds. -Example: ``time.sleep_ms(1_000_000)`` + Example: ``time.sleep_ms(1_000_000)`` -:param ms: 延遲的毫秒數 (>= 0)。""" + :param ms: The number of milliseconds delay (>= 0). + """ ... def sleep_us(us: int) -> None: - """延遲指定的微秒數。 + """ + Delay for given number of microseconds. -Example: ``time.sleep_us(1000)`` + Example: ``time.sleep_us(1000)`` -:param us: 延遲的微秒數 (>= 0)。""" + :param us: The number of microseconds delay (>= 0). + """ ... def ticks_ms() -> int: - """取得具有任意參考點的遞增毫秒計數器,該計數器會在某個值之後繞回。 + """ + Get an increasing, millisecond counter with an arbitrary reference point, + that wraps around after some value. -Example: ``time.ticks_ms()`` + Example: ``time.ticks_ms()`` -:return: The counter value in milliseconds.""" + :return: The counter value in milliseconds. + """ ... def ticks_us() -> int: - """取得具有任意參考點的遞增微秒計數器,該計數器會在某個值之後繞回。 + """ + Get an increasing, microsecond counter with an arbitrary reference point, + that wraps around after some value. -Example: ``time.ticks_us()`` + Example: ``time.ticks_us()`` -:return: The counter value in microseconds.""" + :return: The counter value in microseconds. + """ ... def ticks_add(ticks: int, delta: int) -> int: - """特定數字的位移滴答聲值,可以是正數或負數。 + """ + Offset ticks value by a given number, which can be either positive or + negative. -Example: ``time.ticks_add(time.ticks_ms(), 200)`` + Example: ``time.ticks_add(time.ticks_ms(), 200)`` -Given a ticks value, this function allows to calculate ticks -value delta ticks before or after it, following modular-arithmetic -definition of tick values. + Given a ticks value, this function allows to calculate ticks + value delta ticks before or after it, following modular-arithmetic + definition of tick values. -:param ticks: 滴答聲值 -:param delta: 整數位移 + :param ticks: A ticks value + :param delta: An integer offset -Example:: + Example:: - # Find out what ticks value there was 100ms ago - print(ticks_add(time.ticks_ms(), -100)) + # Find out what ticks value there was 100ms ago + print(ticks_add(time.ticks_ms(), -100)) - # Calculate deadline for operation and test for it - deadline = ticks_add(time.ticks_ms(), 200) - while ticks_diff(deadline, time.ticks_ms()) > 0: - do_a_little_of_something() + # Calculate deadline for operation and test for it + deadline = ticks_add(time.ticks_ms(), 200) + while ticks_diff(deadline, time.ticks_ms()) > 0: + do_a_little_of_something() - # Find out TICKS_MAX used by this port - print(ticks_add(0, -1))""" + # Find out TICKS_MAX used by this port + print(ticks_add(0, -1)) + """ ... def ticks_diff(ticks1: int, ticks2: int) -> int: - """測量從 -``time.ticks_ms()`` 或 ``ticks_us()`` 傳回值之間的滴答聲差異。此參數是一個可能會繞回的帶符號值。 (tick diff) - -Example: ``time.ticks_diff(scheduled_time, now)`` - -:param ticks1: (tick 1) 要被減的值 -:param ticks2: (tick 2) 要減去的值 - -The argument order is the same as for subtraction operator, -``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. - -``ticks_diff()`` is designed to accommodate various usage -patterns, among them: - -Polling with timeout. In this case, the order of events is known, and you -will deal only with positive results of :func:`time.ticks_diff()`:: - - # Wait for GPIO pin to be asserted, but at most 500us - start = time.ticks_us() - while pin.value() == 0: - if time.ticks_diff(time.ticks_us(), start) > 500: - raise TimeoutError - - -Scheduling events. In this case, :func:`time.ticks_diff()` result may be -negative if an event is overdue:: - - # This code snippet is not optimized - now = time.ticks_ms() - scheduled_time = task.scheduled_time() - if ticks_diff(scheduled_time, now) > 0: - print("Too early, let's nap") - sleep_ms(ticks_diff(scheduled_time, now)) - task.run() - elif ticks_diff(scheduled_time, now) == 0: - print("Right at time!") - task.run() - elif ticks_diff(scheduled_time, now) < 0: - print("Oops, running late, tell task to run faster!") - task.run(run_faster=True)""" - ... \ No newline at end of file + """ + Measure ticks difference between values returned from + ``time.ticks_ms()`` or ``ticks_us()``, as a signed value + which may wrap around. + + Example: ``time.ticks_diff(scheduled_time, now)`` + + :param ticks1: The value to subtract from + :param ticks2: The value to subtract + + The argument order is the same as for subtraction operator, + ``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. + + ``ticks_diff()`` is designed to accommodate various usage + patterns, among them: + + Polling with timeout. In this case, the order of events is known, and you + will deal only with positive results of :func:`time.ticks_diff()`:: + + # Wait for GPIO pin to be asserted, but at most 500us + start = time.ticks_us() + while pin.value() == 0: + if time.ticks_diff(time.ticks_us(), start) > 500: + raise TimeoutError + + + Scheduling events. In this case, :func:`time.ticks_diff()` result may be + negative if an event is overdue:: + + # This code snippet is not optimized + now = time.ticks_ms() + scheduled_time = task.scheduled_time() + if ticks_diff(scheduled_time, now) > 0: + print("Too early, let's nap") + sleep_ms(ticks_diff(scheduled_time, now)) + task.run() + elif ticks_diff(scheduled_time, now) == 0: + print("Right at time!") + task.run() + elif ticks_diff(scheduled_time, now) < 0: + print("Oops, running late, tell task to run faster!") + task.run(run_faster=True) + """ + ... From f4204f162d9f5b14e953225484e66f1548e78f08 Mon Sep 17 00:00:00 2001 From: Robert Knight Date: Mon, 16 Dec 2024 15:42:31 +0000 Subject: [PATCH 2/2] Use the right node version --- lang/ca/typeshed/stdlib/gc.pyi | 83 +- lang/ca/typeshed/stdlib/log.pyi | 111 +-- lang/ca/typeshed/stdlib/machine.pyi | 93 +- lang/ca/typeshed/stdlib/math.pyi | 257 +++-- lang/ca/typeshed/stdlib/microbit/__init__.pyi | 899 ++++++++---------- .../stdlib/microbit/accelerometer.pyi | 110 +-- lang/ca/typeshed/stdlib/microbit/audio.pyi | 188 ++-- lang/ca/typeshed/stdlib/microbit/compass.pyi | 66 +- lang/ca/typeshed/stdlib/microbit/display.pyi | 123 +-- lang/ca/typeshed/stdlib/microbit/i2c.pyi | 66 +- .../typeshed/stdlib/microbit/microphone.pyi | 62 +- lang/ca/typeshed/stdlib/microbit/speaker.pyi | 17 +- lang/ca/typeshed/stdlib/microbit/spi.pyi | 71 +- lang/ca/typeshed/stdlib/microbit/uart.pyi | 115 +-- lang/ca/typeshed/stdlib/micropython.pyi | 157 ++- lang/ca/typeshed/stdlib/music.pyi | 173 ++-- lang/ca/typeshed/stdlib/neopixel.pyi | 93 +- lang/ca/typeshed/stdlib/os.pyi | 74 +- lang/ca/typeshed/stdlib/radio.pyi | 166 ++-- lang/ca/typeshed/stdlib/random.pyi | 86 +- lang/ca/typeshed/stdlib/speech.pyi | 157 ++- lang/ca/typeshed/stdlib/struct.pyi | 73 +- lang/ca/typeshed/stdlib/sys.pyi | 63 +- lang/ca/typeshed/stdlib/time.pyi | 172 ++-- lang/de/typeshed/stdlib/gc.pyi | 83 +- lang/de/typeshed/stdlib/log.pyi | 111 +-- lang/de/typeshed/stdlib/machine.pyi | 93 +- lang/de/typeshed/stdlib/math.pyi | 257 +++-- lang/de/typeshed/stdlib/microbit/__init__.pyi | 894 ++++++++--------- .../stdlib/microbit/accelerometer.pyi | 110 +-- lang/de/typeshed/stdlib/microbit/audio.pyi | 188 ++-- lang/de/typeshed/stdlib/microbit/compass.pyi | 66 +- lang/de/typeshed/stdlib/microbit/display.pyi | 123 +-- lang/de/typeshed/stdlib/microbit/i2c.pyi | 66 +- .../typeshed/stdlib/microbit/microphone.pyi | 62 +- lang/de/typeshed/stdlib/microbit/speaker.pyi | 17 +- lang/de/typeshed/stdlib/microbit/spi.pyi | 71 +- lang/de/typeshed/stdlib/microbit/uart.pyi | 115 +-- lang/de/typeshed/stdlib/micropython.pyi | 155 ++- lang/de/typeshed/stdlib/music.pyi | 173 ++-- lang/de/typeshed/stdlib/neopixel.pyi | 93 +- lang/de/typeshed/stdlib/os.pyi | 74 +- lang/de/typeshed/stdlib/radio.pyi | 162 ++-- lang/de/typeshed/stdlib/random.pyi | 85 +- lang/de/typeshed/stdlib/speech.pyi | 154 ++- lang/de/typeshed/stdlib/struct.pyi | 73 +- lang/de/typeshed/stdlib/sys.pyi | 60 +- lang/de/typeshed/stdlib/time.pyi | 167 ++-- lang/es-es/typeshed/stdlib/gc.pyi | 83 +- lang/es-es/typeshed/stdlib/log.pyi | 111 +-- lang/es-es/typeshed/stdlib/machine.pyi | 93 +- lang/es-es/typeshed/stdlib/math.pyi | 257 +++-- .../typeshed/stdlib/microbit/__init__.pyi | 897 ++++++++--------- .../stdlib/microbit/accelerometer.pyi | 110 +-- lang/es-es/typeshed/stdlib/microbit/audio.pyi | 188 ++-- .../typeshed/stdlib/microbit/compass.pyi | 66 +- .../typeshed/stdlib/microbit/display.pyi | 123 +-- lang/es-es/typeshed/stdlib/microbit/i2c.pyi | 66 +- .../typeshed/stdlib/microbit/microphone.pyi | 62 +- .../typeshed/stdlib/microbit/speaker.pyi | 17 +- lang/es-es/typeshed/stdlib/microbit/spi.pyi | 71 +- lang/es-es/typeshed/stdlib/microbit/uart.pyi | 115 +-- lang/es-es/typeshed/stdlib/micropython.pyi | 156 ++- lang/es-es/typeshed/stdlib/music.pyi | 173 ++-- lang/es-es/typeshed/stdlib/neopixel.pyi | 93 +- lang/es-es/typeshed/stdlib/os.pyi | 74 +- lang/es-es/typeshed/stdlib/radio.pyi | 166 ++-- lang/es-es/typeshed/stdlib/random.pyi | 85 +- lang/es-es/typeshed/stdlib/speech.pyi | 157 ++- lang/es-es/typeshed/stdlib/struct.pyi | 73 +- lang/es-es/typeshed/stdlib/sys.pyi | 63 +- lang/es-es/typeshed/stdlib/time.pyi | 168 ++-- lang/fr/typeshed/stdlib/gc.pyi | 83 +- lang/fr/typeshed/stdlib/log.pyi | 111 +-- lang/fr/typeshed/stdlib/machine.pyi | 93 +- lang/fr/typeshed/stdlib/math.pyi | 257 +++-- lang/fr/typeshed/stdlib/microbit/__init__.pyi | 898 ++++++++--------- .../stdlib/microbit/accelerometer.pyi | 110 +-- lang/fr/typeshed/stdlib/microbit/audio.pyi | 188 ++-- lang/fr/typeshed/stdlib/microbit/compass.pyi | 66 +- lang/fr/typeshed/stdlib/microbit/display.pyi | 123 +-- lang/fr/typeshed/stdlib/microbit/i2c.pyi | 66 +- .../typeshed/stdlib/microbit/microphone.pyi | 62 +- lang/fr/typeshed/stdlib/microbit/speaker.pyi | 17 +- lang/fr/typeshed/stdlib/microbit/spi.pyi | 71 +- lang/fr/typeshed/stdlib/microbit/uart.pyi | 115 +-- lang/fr/typeshed/stdlib/micropython.pyi | 156 ++- lang/fr/typeshed/stdlib/music.pyi | 173 ++-- lang/fr/typeshed/stdlib/neopixel.pyi | 93 +- lang/fr/typeshed/stdlib/os.pyi | 74 +- lang/fr/typeshed/stdlib/radio.pyi | 166 ++-- lang/fr/typeshed/stdlib/random.pyi | 85 +- lang/fr/typeshed/stdlib/speech.pyi | 157 ++- lang/fr/typeshed/stdlib/struct.pyi | 73 +- lang/fr/typeshed/stdlib/sys.pyi | 63 +- lang/fr/typeshed/stdlib/time.pyi | 171 ++-- lang/ja/typeshed/stdlib/gc.pyi | 83 +- lang/ja/typeshed/stdlib/log.pyi | 111 +-- lang/ja/typeshed/stdlib/machine.pyi | 93 +- lang/ja/typeshed/stdlib/math.pyi | 257 +++-- lang/ja/typeshed/stdlib/microbit/__init__.pyi | 894 ++++++++--------- .../stdlib/microbit/accelerometer.pyi | 110 +-- lang/ja/typeshed/stdlib/microbit/audio.pyi | 188 ++-- lang/ja/typeshed/stdlib/microbit/compass.pyi | 66 +- lang/ja/typeshed/stdlib/microbit/display.pyi | 123 +-- lang/ja/typeshed/stdlib/microbit/i2c.pyi | 66 +- .../typeshed/stdlib/microbit/microphone.pyi | 62 +- lang/ja/typeshed/stdlib/microbit/speaker.pyi | 17 +- lang/ja/typeshed/stdlib/microbit/spi.pyi | 71 +- lang/ja/typeshed/stdlib/microbit/uart.pyi | 115 +-- lang/ja/typeshed/stdlib/micropython.pyi | 155 ++- lang/ja/typeshed/stdlib/music.pyi | 173 ++-- lang/ja/typeshed/stdlib/neopixel.pyi | 93 +- lang/ja/typeshed/stdlib/os.pyi | 74 +- lang/ja/typeshed/stdlib/radio.pyi | 165 ++-- lang/ja/typeshed/stdlib/random.pyi | 85 +- lang/ja/typeshed/stdlib/speech.pyi | 157 ++- lang/ja/typeshed/stdlib/struct.pyi | 73 +- lang/ja/typeshed/stdlib/sys.pyi | 60 +- lang/ja/typeshed/stdlib/time.pyi | 167 ++-- lang/ko/typeshed/stdlib/gc.pyi | 83 +- lang/ko/typeshed/stdlib/log.pyi | 111 +-- lang/ko/typeshed/stdlib/machine.pyi | 93 +- lang/ko/typeshed/stdlib/math.pyi | 257 +++-- lang/ko/typeshed/stdlib/microbit/__init__.pyi | 888 ++++++++--------- .../stdlib/microbit/accelerometer.pyi | 106 +-- lang/ko/typeshed/stdlib/microbit/audio.pyi | 137 +-- lang/ko/typeshed/stdlib/microbit/compass.pyi | 66 +- lang/ko/typeshed/stdlib/microbit/display.pyi | 123 +-- lang/ko/typeshed/stdlib/microbit/i2c.pyi | 66 +- .../typeshed/stdlib/microbit/microphone.pyi | 62 +- lang/ko/typeshed/stdlib/microbit/speaker.pyi | 17 +- lang/ko/typeshed/stdlib/microbit/spi.pyi | 71 +- lang/ko/typeshed/stdlib/microbit/uart.pyi | 115 +-- lang/ko/typeshed/stdlib/micropython.pyi | 155 ++- lang/ko/typeshed/stdlib/music.pyi | 173 ++-- lang/ko/typeshed/stdlib/neopixel.pyi | 93 +- lang/ko/typeshed/stdlib/os.pyi | 74 +- lang/ko/typeshed/stdlib/radio.pyi | 161 ++-- lang/ko/typeshed/stdlib/random.pyi | 85 +- lang/ko/typeshed/stdlib/speech.pyi | 157 ++- lang/ko/typeshed/stdlib/struct.pyi | 73 +- lang/ko/typeshed/stdlib/sys.pyi | 60 +- lang/ko/typeshed/stdlib/time.pyi | 167 ++-- lang/lol/typeshed/stdlib/gc.pyi | 83 +- lang/lol/typeshed/stdlib/log.pyi | 111 +-- lang/lol/typeshed/stdlib/machine.pyi | 93 +- lang/lol/typeshed/stdlib/math.pyi | 257 +++-- .../lol/typeshed/stdlib/microbit/__init__.pyi | 894 ++++++++--------- .../stdlib/microbit/accelerometer.pyi | 110 +-- lang/lol/typeshed/stdlib/microbit/audio.pyi | 187 ++-- lang/lol/typeshed/stdlib/microbit/compass.pyi | 66 +- lang/lol/typeshed/stdlib/microbit/display.pyi | 123 +-- lang/lol/typeshed/stdlib/microbit/i2c.pyi | 66 +- .../typeshed/stdlib/microbit/microphone.pyi | 62 +- lang/lol/typeshed/stdlib/microbit/speaker.pyi | 17 +- lang/lol/typeshed/stdlib/microbit/spi.pyi | 71 +- lang/lol/typeshed/stdlib/microbit/uart.pyi | 115 +-- lang/lol/typeshed/stdlib/micropython.pyi | 155 ++- lang/lol/typeshed/stdlib/music.pyi | 173 ++-- lang/lol/typeshed/stdlib/neopixel.pyi | 93 +- lang/lol/typeshed/stdlib/os.pyi | 74 +- lang/lol/typeshed/stdlib/radio.pyi | 159 ++-- lang/lol/typeshed/stdlib/random.pyi | 85 +- lang/lol/typeshed/stdlib/speech.pyi | 154 ++- lang/lol/typeshed/stdlib/struct.pyi | 73 +- lang/lol/typeshed/stdlib/sys.pyi | 60 +- lang/lol/typeshed/stdlib/time.pyi | 166 ++-- lang/nl/typeshed/stdlib/gc.pyi | 83 +- lang/nl/typeshed/stdlib/log.pyi | 111 +-- lang/nl/typeshed/stdlib/machine.pyi | 93 +- lang/nl/typeshed/stdlib/math.pyi | 257 +++-- lang/nl/typeshed/stdlib/microbit/__init__.pyi | 899 ++++++++---------- .../stdlib/microbit/accelerometer.pyi | 110 +-- lang/nl/typeshed/stdlib/microbit/audio.pyi | 188 ++-- lang/nl/typeshed/stdlib/microbit/compass.pyi | 66 +- lang/nl/typeshed/stdlib/microbit/display.pyi | 123 +-- lang/nl/typeshed/stdlib/microbit/i2c.pyi | 66 +- .../typeshed/stdlib/microbit/microphone.pyi | 62 +- lang/nl/typeshed/stdlib/microbit/speaker.pyi | 17 +- lang/nl/typeshed/stdlib/microbit/spi.pyi | 71 +- lang/nl/typeshed/stdlib/microbit/uart.pyi | 115 +-- lang/nl/typeshed/stdlib/micropython.pyi | 154 ++- lang/nl/typeshed/stdlib/music.pyi | 173 ++-- lang/nl/typeshed/stdlib/neopixel.pyi | 93 +- lang/nl/typeshed/stdlib/os.pyi | 74 +- lang/nl/typeshed/stdlib/radio.pyi | 166 ++-- lang/nl/typeshed/stdlib/random.pyi | 86 +- lang/nl/typeshed/stdlib/speech.pyi | 154 ++- lang/nl/typeshed/stdlib/struct.pyi | 73 +- lang/nl/typeshed/stdlib/sys.pyi | 61 +- lang/nl/typeshed/stdlib/time.pyi | 168 ++-- lang/pl/typeshed/stdlib/gc.pyi | 83 +- lang/pl/typeshed/stdlib/log.pyi | 111 +-- lang/pl/typeshed/stdlib/machine.pyi | 93 +- lang/pl/typeshed/stdlib/math.pyi | 257 +++-- lang/pl/typeshed/stdlib/microbit/__init__.pyi | 899 ++++++++---------- .../stdlib/microbit/accelerometer.pyi | 110 +-- lang/pl/typeshed/stdlib/microbit/audio.pyi | 187 ++-- lang/pl/typeshed/stdlib/microbit/compass.pyi | 66 +- lang/pl/typeshed/stdlib/microbit/display.pyi | 123 +-- lang/pl/typeshed/stdlib/microbit/i2c.pyi | 66 +- .../typeshed/stdlib/microbit/microphone.pyi | 62 +- lang/pl/typeshed/stdlib/microbit/speaker.pyi | 17 +- lang/pl/typeshed/stdlib/microbit/spi.pyi | 71 +- lang/pl/typeshed/stdlib/microbit/uart.pyi | 115 +-- lang/pl/typeshed/stdlib/micropython.pyi | 156 ++- lang/pl/typeshed/stdlib/music.pyi | 173 ++-- lang/pl/typeshed/stdlib/neopixel.pyi | 93 +- lang/pl/typeshed/stdlib/os.pyi | 74 +- lang/pl/typeshed/stdlib/radio.pyi | 166 ++-- lang/pl/typeshed/stdlib/random.pyi | 86 +- lang/pl/typeshed/stdlib/speech.pyi | 157 ++- lang/pl/typeshed/stdlib/struct.pyi | 73 +- lang/pl/typeshed/stdlib/sys.pyi | 63 +- lang/pl/typeshed/stdlib/time.pyi | 173 ++-- lang/zh-cn/typeshed/stdlib/gc.pyi | 83 +- lang/zh-cn/typeshed/stdlib/log.pyi | 111 +-- lang/zh-cn/typeshed/stdlib/machine.pyi | 93 +- lang/zh-cn/typeshed/stdlib/math.pyi | 257 +++-- .../typeshed/stdlib/microbit/__init__.pyi | 894 ++++++++--------- .../stdlib/microbit/accelerometer.pyi | 110 +-- lang/zh-cn/typeshed/stdlib/microbit/audio.pyi | 188 ++-- .../typeshed/stdlib/microbit/compass.pyi | 66 +- .../typeshed/stdlib/microbit/display.pyi | 123 +-- lang/zh-cn/typeshed/stdlib/microbit/i2c.pyi | 66 +- .../typeshed/stdlib/microbit/microphone.pyi | 62 +- .../typeshed/stdlib/microbit/speaker.pyi | 17 +- lang/zh-cn/typeshed/stdlib/microbit/spi.pyi | 71 +- lang/zh-cn/typeshed/stdlib/microbit/uart.pyi | 115 +-- lang/zh-cn/typeshed/stdlib/micropython.pyi | 155 ++- lang/zh-cn/typeshed/stdlib/music.pyi | 173 ++-- lang/zh-cn/typeshed/stdlib/neopixel.pyi | 93 +- lang/zh-cn/typeshed/stdlib/os.pyi | 74 +- lang/zh-cn/typeshed/stdlib/radio.pyi | 165 ++-- lang/zh-cn/typeshed/stdlib/random.pyi | 85 +- lang/zh-cn/typeshed/stdlib/speech.pyi | 157 ++- lang/zh-cn/typeshed/stdlib/struct.pyi | 73 +- lang/zh-cn/typeshed/stdlib/sys.pyi | 62 +- lang/zh-cn/typeshed/stdlib/time.pyi | 167 ++-- lang/zh-tw/typeshed/stdlib/gc.pyi | 83 +- lang/zh-tw/typeshed/stdlib/log.pyi | 109 +-- lang/zh-tw/typeshed/stdlib/machine.pyi | 93 +- lang/zh-tw/typeshed/stdlib/math.pyi | 257 +++-- .../typeshed/stdlib/microbit/__init__.pyi | 886 ++++++++--------- .../stdlib/microbit/accelerometer.pyi | 106 +-- lang/zh-tw/typeshed/stdlib/microbit/audio.pyi | 133 +-- .../typeshed/stdlib/microbit/compass.pyi | 66 +- .../typeshed/stdlib/microbit/display.pyi | 123 +-- lang/zh-tw/typeshed/stdlib/microbit/i2c.pyi | 66 +- .../typeshed/stdlib/microbit/microphone.pyi | 62 +- .../typeshed/stdlib/microbit/speaker.pyi | 17 +- lang/zh-tw/typeshed/stdlib/microbit/spi.pyi | 71 +- lang/zh-tw/typeshed/stdlib/microbit/uart.pyi | 115 +-- lang/zh-tw/typeshed/stdlib/micropython.pyi | 155 ++- lang/zh-tw/typeshed/stdlib/music.pyi | 173 ++-- lang/zh-tw/typeshed/stdlib/neopixel.pyi | 93 +- lang/zh-tw/typeshed/stdlib/os.pyi | 74 +- lang/zh-tw/typeshed/stdlib/radio.pyi | 167 ++-- lang/zh-tw/typeshed/stdlib/random.pyi | 85 +- lang/zh-tw/typeshed/stdlib/speech.pyi | 157 ++- lang/zh-tw/typeshed/stdlib/struct.pyi | 73 +- lang/zh-tw/typeshed/stdlib/sys.pyi | 60 +- lang/zh-tw/typeshed/stdlib/time.pyi | 168 ++-- 264 files changed, 16248 insertions(+), 21704 deletions(-) diff --git a/lang/ca/typeshed/stdlib/gc.pyi b/lang/ca/typeshed/stdlib/gc.pyi index 1370abf..e12aaf9 100644 --- a/lang/ca/typeshed/stdlib/gc.pyi +++ b/lang/ca/typeshed/stdlib/gc.pyi @@ -1,73 +1,68 @@ -"""Control the garbage collector""" - +"""Controla el recol·lector de memòria brossa""" from typing import overload def enable() -> None: - """Enable automatic garbage collection.""" + """Habilita la recol·lecció automàtica de la memòria brossa (habilita)""" ... def disable() -> None: - """Disable automatic garbage collection. + """Inhabilita la recol·lecció automàtica de la memòria brossa (desactiva) - Heap memory can still be allocated, - and garbage collection can still be initiated manually using ``gc.collect``.""" +Heap memory can still be allocated, +and garbage collection can still be initiated manually using ``gc.collect``.""" def collect() -> None: - """Run a garbage collection.""" + """Executa la recol·lecció automàtica de la memòria brossa (Recull)""" ... def mem_alloc() -> int: - """Get the number of bytes of heap RAM that are allocated. + """Obté el nombre de bytes assignats a la memòria dinàmica. (espai de memòria) - :return: The number of bytes allocated. +:return: The number of bytes allocated. - This function is MicroPython extension. - """ +This function is MicroPython extension.""" ... def mem_free() -> int: - """Get the number of bytes of available heap RAM, or -1 if this amount is not known. + """Obté el nombre disponible de bytes de la memòria dinàmica, o -1 si no es coneix la quantitat. (memòria lliure) - :return: The number of bytes free. +:return: The number of bytes free. - This function is MicroPython extension. - """ +This function is MicroPython extension.""" ... @overload def threshold() -> int: - """Query the additional GC allocation threshold. + """Consulta l'assignació del llindar del col·lector d'escombraries. (llindar) - :return: The GC allocation threshold. +:return: The GC allocation threshold. - This function is a MicroPython extension. CPython has a similar - function - ``set_threshold()``, but due to different GC - implementations, its signature and semantics are different. - """ +This function is a MicroPython extension. CPython has a similar +function - ``set_threshold()``, but due to different GC +implementations, its signature and semantics are different.""" ... @overload def threshold(amount: int) -> None: - """Set the additional GC allocation threshold. - - Normally, a collection is triggered only when a new allocation - cannot be satisfied, i.e. on an out-of-memory (OOM) condition. - If this function is called, in addition to OOM, a collection - will be triggered each time after ``amount`` bytes have been - allocated (in total, since the previous time such an amount of bytes - have been allocated). ``amount`` is usually specified as less than the - full heap size, with the intention to trigger a collection earlier than when the - heap becomes exhausted, and in the hope that an early collection will prevent - excessive memory fragmentation. This is a heuristic measure, the effect - of which will vary from application to application, as well as - the optimal value of the ``amount`` parameter. - - A value of -1 means a disabled allocation threshold. - - This function is a MicroPython extension. CPython has a similar - function - ``set_threshold()``, but due to different GC - implementations, its signature and semantics are different. - - :param amount: The number of bytes after which a garbage collection should be triggered. - """ - ... + """Assigna un espai adicional al llindar del col·lector d'escombraries. (llindar) + +Normally, a collection is triggered only when a new allocation +cannot be satisfied, i.e. on an out-of-memory (OOM) condition. +If this function is called, in addition to OOM, a collection +will be triggered each time after ``amount`` bytes have been +allocated (in total, since the previous time such an amount of bytes +have been allocated). ``amount`` is usually specified as less than the +full heap size, with the intention to trigger a collection earlier than when the +heap becomes exhausted, and in the hope that an early collection will prevent +excessive memory fragmentation. This is a heuristic measure, the effect +of which will vary from application to application, as well as +the optimal value of the ``amount`` parameter. + +A value of -1 means a disabled allocation threshold. + +This function is a MicroPython extension. CPython has a similar +function - ``set_threshold()``, but due to different GC +implementations, its signature and semantics are different. + +:param amount: (quantitat) El nombre de bytes després del qual s'activarà la recol·lecció de la memòria brossa.""" + ... \ No newline at end of file diff --git a/lang/ca/typeshed/stdlib/log.pyi b/lang/ca/typeshed/stdlib/log.pyi index c9870fa..50e425d 100644 --- a/lang/ca/typeshed/stdlib/log.pyi +++ b/lang/ca/typeshed/stdlib/log.pyi @@ -1,104 +1,89 @@ -"""Log data to your micro:bit V2.""" - +"""Registre dades en la micro:bit V2 (registre)""" from typing import Literal, Mapping, Optional, Union, overload - MILLISECONDS = 1 -"""Milliseconds timestamp format.""" - +"""Format de marca de temps de mil·lisegons. (mil·lisegons)""" SECONDS = 10 -"""Seconds timestamp format.""" - +"""Format de marca de temps de segons. (segons)""" MINUTES = 600 -"""Minutes timestamp format.""" - +"""Format de marca de temps de minuts. (minuts)""" HOURS = 36000 -"""Hours timestamp format.""" - +"""Format de marca de temps d'hores. (hores)""" DAYS = 864000 -"""Days timestamp format.""" +"""Format de marca de temps de dies. (dies)""" -def set_labels( - *labels: str, timestamp: Optional[Literal[1, 10, 36000, 864000]] = SECONDS -) -> None: - """Set up the log file header. +def set_labels(*labels: str, timestamp: Optional[Literal[1, 10, 36000, 864000]]=SECONDS) -> None: + """Defineix la capçalera del fitxer de registre. (Defineix l'etiqueta) - Example: ``log.set_labels('X', 'Y', 'Z', timestamp=log.MINUTES)`` +Example: ``log.set_labels('X', 'Y', 'Z', timestamp=log.MINUTES)`` - Ideally this function should be called a single time, before any data is - logged, to configure the data table header once. +Ideally this function should be called a single time, before any data is +logged, to configure the data table header once. - If a log file already exists when the program starts, or if this function - is called multiple times, it will check the labels already defined in the - log file. If this function call contains any new labels not already - present, it will generate a new header row with the additional columns. +If a log file already exists when the program starts, or if this function +is called multiple times, it will check the labels already defined in the +log file. If this function call contains any new labels not already +present, it will generate a new header row with the additional columns. - By default the first column contains a timestamp for each row. The time - unit can be selected via the timestamp argument. +By default the first column contains a timestamp for each row. The time +unit can be selected via the timestamp argument. - :param *labels: Any number of positional arguments, each corresponding to an entry in the log header. - :param timestamp: Select the timestamp unit that will be automatically added as the first column in every row. Timestamp values can be one of ``log.MILLISECONDS``, ``log.SECONDS``, ``log.MINUTES``, ``log.HOURS``, ``log.DAYS`` or ``None`` to disable the timestamp. The default value is ``log.SECONDS``. - """ +:param *labels: Qualsevol nombre d'arguments posicionals, corresponent cadascun a una entrada en la capçalera del registre. +:param timestamp: (marca horària) Selecciona la unitat de la marca del temps que serà automaticament afegida com a primera columna de cada fila. Els valors de la marca del temps pot ser un de ``log.MILLISECONDS``, ``log.SECONDS``, ``log.MINUTES``, ``log.HOURS``, ``log.DAYS`` o ``None`` per desactivar la marca del temps. El valor per defecte es ``log.SECONDS``.""" ... @overload -def add( - data_dictionary: Optional[Mapping[str, Union[str, int, float]]], -) -> None: - """Add a data row to the log by passing a dictionary of headers and values. +def add(data_dictionary: Optional[Mapping[str, Union[str, int, float]]]) -> None: + """Afegeix una fila de dades al registre passant un diccionari de capçaleres i valors. (afegeix) - Example: ``log.add({ 'temp': temperature() })`` +Example: ``log.add({ 'temp': temperature() })`` - Each call to this function adds a row to the log. +Each call to this function adds a row to the log. - New labels not previously specified via the set_labels function, or by a - previous call to this function, will trigger a new header entry to be added - to the log with the extra labels. +New labels not previously specified via the set_labels function, or by a +previous call to this function, will trigger a new header entry to be added +to the log with the extra labels. - Labels previously specified and not present in a call to this function will - be skipped with an empty value in the log row. +Labels previously specified and not present in a call to this function will +be skipped with an empty value in the log row. - :param data_dictionary: The data to log as a dictionary with a key for each header. - """ +:param data_dictionary: (diccionari de dades) Les dades a ser registrades com un diccionari amb una clau per cada capçalera.""" ... @overload def add(**kwargs: Union[str, int, float]) -> None: - """Add a data row to the log using keyword arguments. + """Afegeix una fila de dades al registre fent servir arguments de paraula clau. (afegeix) - Example: ``log.add(temp=temperature())`` +Example: ``log.add(temp=temperature())`` - Each call to this function adds a row to the log. +Each call to this function adds a row to the log. - New labels not previously specified via the set_labels function, or by a - previous call to this function, will trigger a new header entry to be added - to the log with the extra labels. +New labels not previously specified via the set_labels function, or by a +previous call to this function, will trigger a new header entry to be added +to the log with the extra labels. - Labels previously specified and not present in a call to this function will - be skipped with an empty value in the log row. - """ +Labels previously specified and not present in a call to this function will +be skipped with an empty value in the log row.""" ... def delete(full=False): - """Deletes the contents of the log, including headers. + """Suprimeix el contingut del registre, incloses les capçaleres. (suprimeix) - Example: ``log.delete()`` +Example: ``log.delete()`` - To add the log headers again the ``set_labels`` function should to be called after this function. +To add the log headers again the ``set_labels`` function should to be called after this function. - There are two erase modes; “full” completely removes the data from the physical storage, - and “fast” invalidates the data without removing it. +There are two erase modes; “full” completely removes the data from the physical storage, +and “fast” invalidates the data without removing it. - :param full: ``True`` selects a “full” erase and ``False`` selects the “fast” erase method. - """ +:param full: (ple) ``True`` selecciona un esborrat "total" ``False`` selecciona un mètode d'esborrat "ràpid".""" ... def set_mirroring(serial: bool): - """Configure mirroring of the data logging activity to the serial output. + """Configura la duplicació de l'activitat de registre de dades a la sortida en sèrie. (estableix mirall) - Example: ``log.set_mirroring(True)`` +Example: ``log.set_mirroring(True)`` - Serial mirroring is disabled by default. When enabled, it will print to serial each row logged into the log file. +Serial mirroring is disabled by default. When enabled, it will print to serial each row logged into the log file. - :param serial: ``True`` enables mirroring data to the serial output. - """ - ... +:param serial: ``True`` permet la duplicació de les dades a la sortida sèrie.""" + ... \ No newline at end of file diff --git a/lang/ca/typeshed/stdlib/machine.pyi b/lang/ca/typeshed/stdlib/machine.pyi index 2e82f5b..d40f465 100644 --- a/lang/ca/typeshed/stdlib/machine.pyi +++ b/lang/ca/typeshed/stdlib/machine.pyi @@ -1,97 +1,84 @@ -"""Low-level utilities. -""" +"""Utilitats de baix nivell. (màquina)""" from typing import Any from .microbit import MicroBitDigitalPin def unique_id() -> bytes: - """Get a byte string with a unique identifier of a board. + """Obté una cadena de bytes amb un identificador únic d'una placa. - Example: ``machine.unique_id()`` +Example: ``machine.unique_id()`` - :return: An identifier that varies from one board instance to another. - """ +:return: An identifier that varies from one board instance to another.""" ... def reset() -> None: - """Reset the device in a manner similar to pushing the external RESET button. + """Reinicia el dispositiu d'una manera semblant a la de prémer el botó extern de REINICI. (reiniciar) - Example: ``machine.reset()`` - """ +Example: ``machine.reset()``""" ... def freq() -> int: - """Get the CPU frequency in hertz. + """Obté la freqüència en Hertz de la CPU - Example: ``machine.freq()`` +Example: ``machine.freq()`` - :return: The CPU frequency. - """ +:return: The CPU frequency.""" ... def disable_irq() -> Any: - """Disable interrupt requests. + """Desactiva les sol·licituds d'interrupció. (desabilita irq) - Example: ``interrupt_state = machine.disable_irq()`` +Example: ``interrupt_state = machine.disable_irq()`` - :return: the previous IRQ state which should be considered an opaque value +:return: the previous IRQ state which should be considered an opaque value - The return value should be passed to the ``enable_irq`` function to restore - interrupts to their original state. - """ +The return value should be passed to the ``enable_irq`` function to restore +interrupts to their original state.""" ... def enable_irq(state: Any) -> None: - """Re-enable interrupt requests. + """Torna a habilitar les sol·licituds d'interrupció. (habilita irq) - Example: ``machine.enable_irq(interrupt_state)`` +Example: ``machine.enable_irq(interrupt_state)`` - :param state: The value that was returned from the most recent call to the ``disable_irq`` function. - """ +:param state: (estat) El valor retornat per la crida més recent a la funció ``disable_irq``.""" ... -def time_pulse_us( - pin: MicroBitDigitalPin, pulse_level: int, timeout_us: int = 1000000 -) -> int: - """Time a pulse on a pin. +def time_pulse_us(pin: MicroBitDigitalPin, pulse_level: int, timeout_us: int=1000000) -> int: + """Cronometra una pulsació en un pin. (mesura la durada d'una pulsació en un pin) - Example: ``time_pulse_us(pin0, 1)`` +Example: ``time_pulse_us(pin0, 1)`` - If the current input value of the pin is different to ``pulse_level``, the - function first waits until the pin input becomes equal to - ``pulse_level``, then times the duration that the pin is equal to - ``pulse_level``. If the pin is already equal to ``pulse_level`` then timing - starts straight away. +If the current input value of the pin is different to ``pulse_level``, the +function first waits until the pin input becomes equal to +``pulse_level``, then times the duration that the pin is equal to +``pulse_level``. If the pin is already equal to ``pulse_level`` then timing +starts straight away. - :param pin: The pin to use - :param pulse_level: 0 to time a low pulse or 1 to time a high pulse - :param timeout_us: A microsecond timeout - :return: The duration of the pulse in microseconds, or -1 for a timeout waiting for the level to match ``pulse_level``, or -2 on timeout waiting for the pulse to end - """ +:param pin: El pin a utilitzar +:param pulse_level: (nivell de pulsació) 0 per cronometrar la durada de l'estat baix o 1 per cronometrar la durada de l'estat alt +:param timeout_us: (temps d'espera a la resposta excedit en microsegons) Temps d'espera d'un microsegon +:return: The duration of the pulse in microseconds, or -1 for a timeout waiting for the level to match ``pulse_level``, or -2 on timeout waiting for the pulse to end""" ... class mem: - """The class for the ``mem8``, ``mem16`` and ``mem32`` memory views.""" + """La classe per a les vistes de la memòria ``mem8``, ``mem16`` i ``mem32``.""" def __getitem__(self, address: int) -> int: - """Access a value from memory. + """Accedeix a un valor de la memòria - :param address: The memory address. - :return: The value at that address as an integer. - """ +:param address: (adreça) L'adreça de la memòria +:return: The value at that address as an integer.""" ... + def __setitem__(self, address: int, value: int) -> None: - """Set a value at the given address. + """Assigna un valor a l'adreça donada - :param address: The memory address. - :param value: The integer value to set. - """ +:param address: (adreça) L'adreça de la memòria +:param value: (valor) El valor enter que cal assignar.""" ... - mem8: mem -"""8-bit (byte) view of memory.""" - +"""vista de la memòria 8-bit (byte)""" mem16: mem -"""16-bit view of memory.""" - +"""vista de la memòria 16-bit""" mem32: mem -"""32-bit view of memory.""" +"""vista de la memòria 32-bit""" \ No newline at end of file diff --git a/lang/ca/typeshed/stdlib/math.pyi b/lang/ca/typeshed/stdlib/math.pyi index f82d4de..0ec2a6a 100644 --- a/lang/ca/typeshed/stdlib/math.pyi +++ b/lang/ca/typeshed/stdlib/math.pyi @@ -1,273 +1,246 @@ -"""Mathematical functions. -""" - +"""Funcions matemàtiques (matemàtiques)""" from typing import Tuple def acos(x: float) -> float: - """Calculate the inverse cosine. + """Calcula l'invers del cosinus (arc cosinus) - Example: ``math.acos(1)`` +Example: ``math.acos(1)`` - :param x: A number - :return: The inverse cosine of ``x`` - """ +:param x: Un nombre +:return: The inverse cosine of ``x``""" ... def asin(x: float) -> float: - """Calculate the inverse sine. + """Calcula l'invers del sinus (arc sinus) - Example: ``math.asin(0)`` +Example: ``math.asin(0)`` - :param x: A number - :return: The inverse sine of ``x`` - """ +:param x: Un nombre +:return: The inverse sine of ``x``""" ... def atan(x: float) -> float: - """Calculate the inverse tangent. + """Calcula l'invers de la tangent (arc tangent) - Example: ``math.atan(0)`` +Example: ``math.atan(0)`` - :param x: A number - :return: The inverse tangent of ``x`` - """ +:param x: Un nombre +:return: The inverse tangent of ``x``""" ... def atan2(y: float, x: float) -> float: - """Calculate the principal value of the inverse tangent of ``y/x``. + """Calcula el valor principal de l'invers de la tangent de ``y/x``. (arc tangent 2) - Example: ``math.atan2(0, -1)`` +Example: ``math.atan2(0, -1)`` - :param y: A number - :param x: A number - :return: The principal value of the inverse tangent of ``y/x`` - """ +:param y: Un nombre +:param x: Un nombre +:return: The principal value of the inverse tangent of ``y/x``""" ... def ceil(x: float) -> float: - """Round a number towards positive infinity. + """Arrodoneix un nombre cap a l'infinit positiu. (arrodoniment per excés) - Example: ``math.ceil(0.1)`` +Example: ``math.ceil(0.1)`` - :param x: A number - :return: ``x`` rounded towards positive infinity. - """ +:param x: Un nombre +:return: ``x`` rounded towards positive infinity.""" ... def copysign(x: float, y: float) -> float: - """Calculate ``x`` with the sign of ``y``. + """Calcula ``x`` amb el signe de ``y``. - Example: ``math.copysign(1, -1)`` +Example: ``math.copysign(1, -1)`` - :param x: A number - :param y: The source of the sign for the return value - :return: ``x`` with the sign of ``y`` - """ +:param x: Un nombre +:param y: L'origen del signe pel valor retornat. +:return: ``x`` with the sign of ``y``""" ... def cos(x: float) -> float: - """Calculate the cosine of ``x``. + """Calcula el cosinus de ``x``. (cosinus) - Example: ``math.cos(0)`` +Example: ``math.cos(0)`` - :param x: A number - :return: The cosine of ``x`` - """ +:param x: Un nombre +:return: The cosine of ``x``""" ... def degrees(x: float) -> float: - """Convert radians to degrees. + """Convertir radiants a graus (graus) - Example: ``math.degrees(2 * math.pi)`` +Example: ``math.degrees(2 * math.pi)`` - :param x: A value in radians - :return: The value converted to degrees""" +:param x: Un valor en radians +:return: The value converted to degrees""" ... def exp(x: float) -> float: - """Calculate the exponential of ``x``. + """Calcula l'exponencial de ``x``. - Example: ``math.exp(1)`` +Example: ``math.exp(1)`` - :param x: A number - :return: The exponential of ``x``. - """ +:param x: Un nombre +:return: The exponential of ``x``.""" ... def fabs(x: float) -> float: - """Return the absolute value of ``x``. + """Retorna el valor absolut de ``x``. - Example: ``math.fabs(-0.1)`` +Example: ``math.fabs(-0.1)`` - :param x: A number - :return: The absolute value of ``x`` - """ +:param x: Un nombre +:return: The absolute value of ``x``""" ... def floor(x: float) -> int: - """Round a number towards negative infinity. + """Arrodoneix un nombre cap a l'infinit negatiu. (arrodoniment per defecte) - Example: ``math.floor(0.9)`` +Example: ``math.floor(0.9)`` - :param x: A number - :return: ``x`` rounded towards negative infinity. - """ +:param x: Un nombre +:return: ``x`` rounded towards negative infinity.""" ... def fmod(x: float, y: float) -> float: - """Calculate the remainder of ``x/y``. + """Calcula el residu de ``x/y``. - Example: ``math.fmod(10, 3)`` +Example: ``math.fmod(10, 3)`` - :param x: The numerator - :param y: The denominator - """ +:param x: El numerador +:param y: El denominador""" ... def frexp(x: float) -> Tuple[float, int]: - """Decomposes a floating-point number into its mantissa and exponent. + """Descompon un nombre de coma flotant en la seva mantissa i el seu exponent. - Example: ``mantissa, exponent = math.frexp(2)`` +Example: ``mantissa, exponent = math.frexp(2)`` - The returned value is the tuple ``(m, e)`` such that ``x == m * 2**e`` - exactly. If ``x == 0`` then the function returns ``(0.0, 0)``, otherwise - the relation ``0.5 <= abs(m) < 1`` holds. +The returned value is the tuple ``(m, e)`` such that ``x == m * 2**e`` +exactly. If ``x == 0`` then the function returns ``(0.0, 0)``, otherwise +the relation ``0.5 <= abs(m) < 1`` holds. - :param x: A floating-point number - :return: A tuple of length two containing its mantissa then exponent - """ +:param x: Un nombre de coma flotant +:return: A tuple of length two containing its mantissa then exponent""" ... def isfinite(x: float) -> bool: - """Check if a value is finite. + """Verifica si un valor és finit. - Example: ``math.isfinite(float('inf'))`` +Example: ``math.isfinite(float('inf'))`` - :param x: A number. - :return: ``True`` if ``x`` is finite, ``False`` otherwise. - """ +:param x: Un nombre. +:return: ``True`` if ``x`` is finite, ``False`` otherwise.""" ... def isinf(x: float) -> bool: - """Check if a value is infinite. + """Verifica si un valor és infinit. - Example: ``math.isinf(float('-inf'))`` +Example: ``math.isinf(float('-inf'))`` - :param x: A number. - :return: ``True`` if ``x`` is infinite, ``False`` otherwise. - """ +:param x: Un nombre. +:return: ``True`` if ``x`` is infinite, ``False`` otherwise.""" ... def isnan(x: float) -> bool: - """Check if a value is not-a-number (NaN). + """Verifica si un valor és un "no nombre" (NaN) - Example: ``math.isnan(float('nan'))`` +Example: ``math.isnan(float('nan'))`` - :param x: A number - :return: ``True`` if ``x`` is not-a-number (NaN), ``False`` otherwise.""" +:param x: Un nombre +:return: ``True`` if ``x`` is not-a-number (NaN), ``False`` otherwise.""" ... def ldexp(x: float, exp: int) -> float: - """Calculate ``x * (2**exp)``. + """Calcula ``x * (2**exp)``. (ldexp (Calcula ``x * (2**exp)``)) - Example: ``math.ldexp(0.5, 2)`` +Example: ``math.ldexp(0.5, 2)`` - :param x: A number - :param exp: Integer exponent - :return: ``x * (2**exp)`` - """ +:param x: Un nombre +:param exp: Exponent enter +:return: ``x * (2**exp)``""" ... -def log(x: float, base: float = e) -> float: - """Calculate the logarithm of ``x`` to the given base (defaults to natural logorithm). +def log(x: float, base: float=e) -> float: + """Calcula el logaritme ``x`` d'una base donada (per defecte al logaritme natural). (registre) - Example: ``math.log(math.e)`` +Example: ``math.log(math.e)`` - With one argument, return the natural logarithm of x (to base e). +With one argument, return the natural logarithm of x (to base e). - With two arguments, return the logarithm of x to the given base, calculated as ``log(x)/log(base)``. +With two arguments, return the logarithm of x to the given base, calculated as ``log(x)/log(base)``. - :param x: A number - :param base: The base to use - :return: The natural logarithm of ``x`` - """ +:param x: Un nombre +:param base: La base a utilitzar +:return: The natural logarithm of ``x``""" ... def modf(x: float) -> Tuple[float, float]: - """Calculate the fractional and integral parts of ``x``. + """Calcula les parts fraccionàries i integrals de ``x``. - Example: ``fractional, integral = math.modf(1.5)`` +Example: ``fractional, integral = math.modf(1.5)`` - :param x: A number - :return: A tuple of two floats representing the fractional then integral parts of ``x``. +:param x: Un nombre +:return: A tuple of two floats representing the fractional then integral parts of ``x``. - Both the fractional and integral values have the same sign as ``x``. - """ +Both the fractional and integral values have the same sign as ``x``.""" ... def pow(x: float, y: float) -> float: - """Returns ``x`` to the power of ``y``. + """Retorna ``x`` a la potència de ``y``. - Example: ``math.pow(4, 0.5)`` +Example: ``math.pow(4, 0.5)`` - :param x: A number - :param y: The exponent - :return: ``x`` to the power of ``y`` - """ +:param x: Un nombre +:param y: L'exponent +:return: ``x`` to the power of ``y``""" ... def radians(x: float) -> float: - """Convert a degrees to radians. + """Converteix graus a radians - Example: ``math.radians(360)`` +Example: ``math.radians(360)`` - :param x: A value in degrees - :return: The value converted to radians - """ +:param x: Un valor en graus +:return: The value converted to radians""" ... def sin(x: float) -> float: - """Calculate the sine of ``x``. + """Calcula el sinus de ``x``. (sinus) - Example: ``math.sin(math.pi/2)`` +Example: ``math.sin(math.pi/2)`` - :param x: A number - :return: The sine of ``x`` - """ +:param x: Un nombre +:return: The sine of ``x``""" ... def sqrt(x: float) -> float: - """Calculate the square root of ``x``. + """Calcula l'arrel quadrada de ``x``. - Example: ``math.sqrt(4)`` +Example: ``math.sqrt(4)`` - :param x: A number - :return: The square root of ``x`` - """ +:param x: Un nombre +:return: The square root of ``x``""" ... def tan(x: float) -> float: - """Calculate the tangent of ``x``. + """Calcula la tangent de ``x``. - Example: ``math.tan(0)`` +Example: ``math.tan(0)`` - :param x: A number - :return: The tangent of ``x``. - """ +:param x: Un nombre +:return: The tangent of ``x``.""" ... def trunc(x: float) -> int: - """Round a number towards 0. + """Arrodoneix un nombre cap al 0. (trunca) - Example: ``math.trunc(-0.9)`` +Example: ``math.trunc(-0.9)`` - :param x: A number - :return: ``x`` rounded towards zero. - """ +:param x: Un nombre +:return: ``x`` rounded towards zero.""" ... - e: float -"""Base of the natural logarithm""" - +"""Base del logaritme natural""" pi: float -"""The ratio of a circle's circumference to its diameter""" +"""La relació entre la circumferència d'un cercle i el seu diàmetre""" \ No newline at end of file diff --git a/lang/ca/typeshed/stdlib/microbit/__init__.pyi b/lang/ca/typeshed/stdlib/microbit/__init__.pyi index f12158f..cff2992 100644 --- a/lang/ca/typeshed/stdlib/microbit/__init__.pyi +++ b/lang/ca/typeshed/stdlib/microbit/__init__.pyi @@ -1,11 +1,6 @@ -"""Pins, images, sounds, temperature and volume. -""" - +"""Pins, imatges, sons, temperatura i volum.""" from typing import Any, Callable, List, Optional, Tuple, Union, overload - from _typeshed import ReadableBuffer - -# V2 only from . import accelerometer as accelerometer from . import audio as audio from . import compass as compass @@ -16,831 +11,701 @@ from . import speaker as speaker from . import spi as spi from . import uart as uart -def run_every( - callback: Optional[Callable[[], None]] = None, - days: int = 0, - h: int = 0, - min: int = 0, - s: int = 0, - ms: int = 0, -) -> Callable[[Callable[[], None]], Callable[[], None]]: - """Schedule to run a function at the interval specified by the time arguments **V2 only**. +def run_every(callback: Optional[Callable[[], None]]=None, days: int=0, h: int=0, min: int=0, s: int=0, ms: int=0) -> Callable[[Callable[[], None]], Callable[[], None]]: + """Programa l'execució d'una funció a cada interval especificat pels arguments de temps **només V2**. - Example: ``run_every(my_logging, min=5)`` +Example: ``run_every(my_logging, min=5)`` - ``run_every`` can be used in two ways: +``run_every`` can be used in two ways: - As a Decorator - placed on top of the function to schedule. For example:: +As a Decorator - placed on top of the function to schedule. For example:: - @run_every(h=1, min=20, s=30, ms=50) - def my_function(): - # Do something here + @run_every(h=1, min=20, s=30, ms=50) + def my_function(): + # Do something here - As a Function - passing the callback as a positional argument. For example:: +As a Function - passing the callback as a positional argument. For example:: - def my_function(): - # Do something here - run_every(my_function, s=30) + def my_function(): + # Do something here + run_every(my_function, s=30) - Each argument corresponds to a different time unit and they are additive. - So ``run_every(min=1, s=30)`` schedules the callback every minute and a half. +Each argument corresponds to a different time unit and they are additive. +So ``run_every(min=1, s=30)`` schedules the callback every minute and a half. - When an exception is thrown inside the callback function it deschedules the - function. To avoid this you can catch exceptions with ``try/except``. +When an exception is thrown inside the callback function it deschedules the +function. To avoid this you can catch exceptions with ``try/except``. - :param callback: Function to call at the provided interval. Omit when using as a decorator. - :param days: Sets the day mark for the scheduling. - :param h: Sets the hour mark for the scheduling. - :param min: Sets the minute mark for the scheduling. - :param s: Sets the second mark for the scheduling. - :param ms: Sets the millisecond mark for the scheduling. - """ +:param callback: Funció a cridar a l'interval previst. Omet quan el fas servir com decorador. +:param days: (dies) Estableix la marca del dia per la programació +:param h: Estableix la marca de l'hora per la programació +:param min: Estableix la marca del minut per la programació +:param s: Estableix la marca del segon per la programació +:param ms: Estableix la marca del mil·lisegon per la programació""" def panic(n: int) -> None: - """Enter a panic mode. + """Entrar en mode pànic. (pànic) - Example: ``panic(127)`` +Example: ``panic(127)`` - :param n: An arbitrary integer <= 255 to indicate a status. +:param n: Un nombre enter arbitrari <= 255 per indicar un estat. - Requires restart. - """ +Requires restart.""" def reset() -> None: - """Restart the board.""" - + """Reinicialitza la placa. (reiniciar)""" @overload def scale(value: float, from_: Tuple[float, float], to: Tuple[int, int]) -> int: - """Converts a value from a range to an integer range. + """Converteix un valor d'un interval a un interval de nombre enter. (escala) - Example: ``volume = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255))`` +Example: ``volume = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255))`` - For example, to convert an accelerometer X value to a speaker volume. +For example, to convert an accelerometer X value to a speaker volume. - If one of the numbers in the ``to`` parameter is a floating point - (i.e a decimal number like ``10.0``), this function will return a - floating point number. +If one of the numbers in the ``to`` parameter is a floating point +(i.e a decimal number like ``10.0``), this function will return a +floating point number. - temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0)) + temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0)) - :param value: A number to convert. - :param from_: A tuple to define the range to convert from. - :param to: A tuple to define the range to convert to. - :return: The ``value`` converted to the ``to`` range. - """ +:param value: (valor) Un nombre a convertir. +:param from_: (des de) Una tupla des d'on definir l'interval a convertir +:param to: (a) Una tupla que defineix l'interval d'arribada +:return: The ``value`` converted to the ``to`` range.""" @overload def scale(value: float, from_: Tuple[float, float], to: Tuple[float, float]) -> float: - """Converts a value from a range to a floating point range. + """Converteix un valor d'un interval a un altre interval de coma flotant. (escala) - Example: ``temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0))`` +Example: ``temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0))`` - For example, to convert temperature from a Celsius scale to Fahrenheit. +For example, to convert temperature from a Celsius scale to Fahrenheit. - If one of the numbers in the ``to`` parameter is a floating point - (i.e a decimal number like ``10.0``), this function will return a - floating point number. - If they are both integers (i.e ``10``), it will return an integer:: +If one of the numbers in the ``to`` parameter is a floating point +(i.e a decimal number like ``10.0``), this function will return a +floating point number. +If they are both integers (i.e ``10``), it will return an integer:: - returns_int = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255)) + returns_int = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255)) - :param value: A number to convert. - :param from_: A tuple to define the range to convert from. - :param to: A tuple to define the range to convert to. - :return: The ``value`` converted to the ``to`` range. - """ +:param value: (valor) Un nombre a convertir. +:param from_: (des de) Una tupla des d'on definir l'interval a convertir +:param to: (a) Una tupla que defineix l'interval d'arribada de la conversió. +:return: The ``value`` converted to the ``to`` range.""" def sleep(n: float) -> None: - """Wait for ``n`` milliseconds. + """Espera per ``n`` mil·lisegons. (dormir) - Example: ``sleep(1000)`` +Example: ``sleep(1000)`` - :param n: The number of milliseconds to wait +:param n: El nombre de mil·lisegons a esperar - One second is 1000 milliseconds, so:: +One second is 1000 milliseconds, so:: - microbit.sleep(1000) + microbit.sleep(1000) - will pause the execution for one second. - """ +will pause the execution for one second.""" def running_time() -> int: - """Get the running time of the board. + """Obté el temps d'execució de la placa. (temps d'execució) - :return: The number of milliseconds since the board was switched on or restarted. - """ +:return: The number of milliseconds since the board was switched on or restarted.""" def temperature() -> int: - """Get the temperature of the micro:bit in degrees Celsius.""" + """Obté la temperatura de la micro:bit en graus Celsius. (temperatura)""" def set_volume(v: int) -> None: - """Sets the volume. + """Configura el volum (assigna volum) - Example: ``set_volume(127)`` +Example: ``set_volume(127)`` - :param v: a value between 0 (low) and 255 (high). +:param v: un valor entre 0 (baix) i 255 (alt). - Out of range values will be clamped to 0 or 255. +Out of range values will be clamped to 0 or 255. - **V2** only. - """ +**V2** only.""" ... class Button: - """The class for the buttons ``button_a`` and ``button_b``.""" + """La classe dels botons ``button_a`` i ``button_b``. (botó)""" def is_pressed(self) -> bool: - """Check if the button is pressed. + """Verifica si el botó està premut. (és premut) - :return: ``True`` if the specified button ``button`` is pressed, and ``False`` otherwise. - """ +:return: ``True`` if the specified button ``button`` is pressed, and ``False`` otherwise.""" ... + def was_pressed(self) -> bool: - """Check if the button was pressed since the device started or the last time this method was called. + """Verifica si el botó ha estat premut d'ençà que el dispositiu va arrancar o l'última vegada que aquest mètode va ser cridat. (ha estat premut) - Calling this method will clear the press state so - that the button must be pressed again before this method will return - ``True`` again. +Calling this method will clear the press state so +that the button must be pressed again before this method will return +``True`` again. - :return: ``True`` if the specified button ``button`` was pressed, and ``False`` otherwise - """ +:return: ``True`` if the specified button ``button`` was pressed, and ``False`` otherwise""" ... + def get_presses(self) -> int: - """Get the running total of button presses, and resets this total - to zero before returning. + """Obté el total acumulat de pressions dels botons i restableix aquest total +a zero abans de tornar. (obté pitjades) - :return: The number of presses since the device started or the last time this method was called - """ +:return: The number of presses since the device started or the last time this method was called""" ... - button_a: Button -"""The left button ``Button`` object.""" - +"""L'objecte botó esquerre ``Button`` . (botó a)""" button_b: Button -"""The right button ``Button`` object.""" +"""L'objecte el botó dret ``Button``. (botó b)""" class MicroBitDigitalPin: - """A digital pin. - - Some pins support analog and touch features using the ``MicroBitAnalogDigitalPin`` and ``MicroBitTouchPin`` subclasses. - """ + """Un pin digital. +Some pins support analog and touch features using the ``MicroBitAnalogDigitalPin`` and ``MicroBitTouchPin`` subclasses.""" NO_PULL: int PULL_UP: int PULL_DOWN: int + def read_digital(self) -> int: - """Get the digital value of the pin. + """Obté el valor digital del pin. (llegeix digital) - Example: ``value = pin0.read_digital()`` +Example: ``value = pin0.read_digital()`` - :return: 1 if the pin is high, and 0 if it's low. - """ +:return: 1 if the pin is high, and 0 if it's low.""" ... + def write_digital(self, value: int) -> None: - """Set the digital value of the pin. + """Assigna el valor digital del pin. (escriu digital) - Example: ``pin0.write_digital(1)`` +Example: ``pin0.write_digital(1)`` - :param value: 1 to set the pin high or 0 to set the pin low""" +:param value: (valor) 1 per posar el pin alt o 0 per posar el pin baix""" ... + def set_pull(self, value: int) -> None: - """Set the pull state to one of three possible values: ``PULL_UP``, ``PULL_DOWN`` or ``NO_PULL``. + """Configura les resistències de pull-up/pull-down un dels tres valors possibles: ``PULL_UP``, ``PULL_DOWN`` o ``NO_PULL``. (configuració de les resistències de pull up/down) - Example: ``pin0.set_pull(pin0.PULL_UP)`` +Example: ``pin0.set_pull(pin0.PULL_UP)`` - :param value: The pull state from the relevant pin, e.g. ``pin0.PULL_UP``. - """ +:param value: (valor) L'estat del pull-up/pull-down del pin corresponent, per ex. ``pin0.PULL_UP``.""" ... + def get_pull(self) -> int: - """Get the pull state on a pin. + """Obté l'estat de pull-up/pull-down d'un pin. - Example: ``pin0.get_pull()`` +Example: ``pin0.get_pull()`` - :return: ``NO_PULL``, ``PULL_DOWN``, or ``PULL_UP`` +:return: ``NO_PULL``, ``PULL_DOWN``, or ``PULL_UP`` - These are set using the ``set_pull()`` method or automatically configured - when a pin mode requires it. - """ +These are set using the ``set_pull()`` method or automatically configured +when a pin mode requires it.""" ... + def get_mode(self) -> str: - """Returns the pin mode. + """Retorna el mode del pin (obté el mode) - Example: ``pin0.get_mode()`` +Example: ``pin0.get_mode()`` - When a pin is used for a specific function, like - writing a digital value, or reading an analog value, the pin mode - changes. +When a pin is used for a specific function, like +writing a digital value, or reading an analog value, the pin mode +changes. - :return: ``"unused"``, ``"analog"``, ``"read_digital"``, ``"write_digital"``, ``"display"``, ``"button"``, ``"music"``, ``"audio"``, ``"touch"``, ``"i2c"``, or ``"spi"`` - """ +:return: ``"unused"``, ``"analog"``, ``"read_digital"``, ``"write_digital"``, ``"display"``, ``"button"``, ``"music"``, ``"audio"``, ``"touch"``, ``"i2c"``, or ``"spi"``""" ... + def write_analog(self, value: int) -> None: - """Output a PWM signal on the pin, with the duty cycle proportional to ``value``. + """Genera un senyal PWM al pin, amb el cicle de treball proporcional a ``value``. (escriu analògic) + +Example: ``pin0.write_analog(254)`` - Example: ``pin0.write_analog(254)`` +:param value: (valor) Un nombre enter o de coma flotant entre 0 (cicle de treball del 0%) i 1023 (cicle de treball del 100%).""" - :param value: 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. + """Estableix el període del senyal PWM a ``period`` en mil·lisegons. (configura el període amb un valor analògic) - Example: ``pin0.set_analog_period(10)`` +Example: ``pin0.set_analog_period(10)`` + +:param period: (període) El període en mil·lisegons amb un valor mínim vàlid d'1\u202fms""" - :param period: The period in milliseconds with a minimum valid value of 1ms. - """ def set_analog_period_microseconds(self, period: int) -> None: - """Set the period of the PWM signal being output to ``period`` in microseconds. + """Estableix el període del senyal PWM a ``period`` microsegons. (configura el període amb un valor analògic en microsegons) - Example: ``pin0.set_analog_period_microseconds(512)`` +Example: ``pin0.set_analog_period_microseconds(512)`` - :param period: The period in microseconds with a minimum valid value of 256µs. - """ +:param period: (període) El període en microsegons amb un valor vàlid mínim de 256\u202fµs.""" class MicroBitAnalogDigitalPin(MicroBitDigitalPin): - """A pin with analog and digital features.""" + """Un pin amb funcions analògiques i digitals.""" def read_analog(self) -> int: - """Read the voltage applied to the pin. + """Llegeix el voltatge aplicat al pin. (llegeix analògic) - Example: ``pin0.read_analog()`` +Example: ``pin0.read_analog()`` - :return: An integer between 0 (meaning 0V) and 1023 (meaning 3.3V). - """ +:return: An integer between 0 (meaning 0V) and 1023 (meaning 3.3V).""" class MicroBitTouchPin(MicroBitAnalogDigitalPin): - """A pin with analog, digital and touch features.""" - + """Un pin amb característiques analògiques, digitals i tàctils.""" CAPACITIVE: int RESISTIVE: int + def is_touched(self) -> bool: - """Check if the pin is being touched. + """Comprova si el pin està sent tocat. (està tocat) - Example: ``pin0.is_touched()`` +Example: ``pin0.is_touched()`` - The default touch mode for the pins on the edge connector is ``resistive``. - The default for the logo pin **V2** is ``capacitive``. +The default touch mode for the pins on the edge connector is ``resistive``. +The default for the logo pin **V2** is ``capacitive``. - **Resistive touch** - This test is done by measuring how much resistance there is between the - pin and ground. A low resistance gives a reading of ``True``. To get - a reliable reading using a finger you may need to touch the ground pin - with another part of your body, for example your other hand. +**Resistive touch** +This test is done by measuring how much resistance there is between the +pin and ground. A low resistance gives a reading of ``True``. To get +a reliable reading using a finger you may need to touch the ground pin +with another part of your body, for example your other hand. - **Capacitive touch** - This test is done by interacting with the electric field of a capacitor - using a finger as a conductor. `Capacitive touch - `_ - does not require you to make a ground connection as part of a circuit. +**Capacitive touch** +This test is done by interacting with the electric field of a capacitor +using a finger as a conductor. `Capacitive touch +`_ +does not require you to make a ground connection as part of a circuit. - :return: ``True`` if the pin is being touched with a finger, otherwise return ``False``. - """ +:return: ``True`` if the pin is being touched with a finger, otherwise return ``False``.""" ... + def set_touch_mode(self, value: int) -> None: - """Set the touch mode for the pin. + """Estableix el mode tàctil per al pin. (estableix el mode tàctil) - Example: ``pin0.set_touch_mode(pin0.CAPACITIVE)`` +Example: ``pin0.set_touch_mode(pin0.CAPACITIVE)`` - The default touch mode for the pins on the edge connector is - ``resistive``. The default for the logo pin **V2** is ``capacitive``. +The default touch mode for the pins on the edge connector is +``resistive``. The default for the logo pin **V2** is ``capacitive``. - :param value: ``CAPACITIVE`` or ``RESISTIVE`` from the relevant pin. - """ +:param value: (valor) ``CAPACITIVE`` o ``RESISTIVE`` del pin corresponent.""" ... - pin0: MicroBitTouchPin -"""Pin with digital, analog and touch features.""" - +"""Pin amb característiques digitals, analògiques i tàctils.""" pin1: MicroBitTouchPin -"""Pin with digital, analog and touch features.""" - +"""Pin amb característiques digitals, analògiques i tàctils.""" pin2: MicroBitTouchPin -"""Pin with digital, analog and touch features.""" - +"""Pin amb característiques digitals, analògiques i tàctils.""" pin3: MicroBitAnalogDigitalPin -"""Pin with digital and analog features.""" - +"""Pin amb característiques digitals i analògiques.""" pin4: MicroBitAnalogDigitalPin -"""Pin with digital and analog features.""" - +"""Pin amb característiques digitals i analògiques.""" pin5: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin amb característiques digitals.""" pin6: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin amb característiques digitals.""" pin7: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin amb característiques digitals.""" pin8: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin amb característiques digitals.""" pin9: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin amb característiques digitals.""" pin10: MicroBitAnalogDigitalPin -"""Pin with digital and analog features.""" - +"""Pin amb característiques digitals i analògiques.""" pin11: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin amb característiques digitals.""" pin12: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin amb característiques digitals.""" pin13: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin amb característiques digitals.""" pin14: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin amb característiques digitals.""" pin15: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin amb característiques digitals.""" pin16: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin amb característiques digitals.""" pin19: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin amb característiques digitals.""" pin20: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin amb característiques digitals.""" pin_logo: MicroBitTouchPin -"""A touch sensitive logo pin on the front of the micro:bit, which by default is set to capacitive touch mode.""" - +"""Un logotip tàctil a la part frontal de la micro:bit, que per defecte està establert al mode tàctil capacitiu. (pin logotip)""" pin_speaker: MicroBitAnalogDigitalPin -"""A pin to address the micro:bit speaker. +"""Un pin per adreçar-se a l'altaveu micro:bit. (pin altaveu) This API is intended only for use in Pulse-Width Modulation pin operations e.g. pin_speaker.write_analog(128). """ class Image: - """An image to show on the micro:bit LED display. + """Una imatge per mostrar a la pantalla LED de micro:bit. (imatge) - Given an image object it's possible to display it via the ``display`` API:: - - display.show(Image.HAPPY) - """ +Given an image object it's possible to display it via the ``display`` API:: + display.show(Image.HAPPY)""" HEART: Image - """Heart image.""" - + """Imatge d'un cor. (cor)""" HEART_SMALL: Image - """Small heart image.""" - + """Imatge d'un cor petit (cor petit)""" HAPPY: Image - """Happy face image.""" - + """Imatge d'una cara feliç (feliç)""" SMILE: Image - """Smiling mouth image.""" - + """Imatge d'una cara somrient (somriure)""" SAD: Image - """Sad face image.""" - + """Imatge d'una cara trista (tristesa)""" CONFUSED: Image - """Confused face image.""" - + """Imatge de cara confusa. (confusa)""" ANGRY: Image - """Angry face image.""" - + """Imatge d'una cara enfadada. (enfadat)""" ASLEEP: Image - """Sleeping face image.""" - + """Imatge d'una cara dormint. (despert)""" SURPRISED: Image - """Surprised face image.""" - + """Imatge d'una cara de sorpresa (sorprès)""" SILLY: Image - """Silly face image.""" - + """Imatge d'una cara ximple. (ximple)""" FABULOUS: Image - """Sunglasses face image.""" - + """Imatge d'una cara amb ulleres de sol. (fabulós)""" MEH: Image - """Unimpressed face image.""" - + """Imatge d'una cara inexpressiva. (BAH avorrit)""" YES: Image - """Tick image.""" - + """Imatge d'una marca tic. (sí)""" NO: Image - """Cross image.""" - + """Imatge d'una creu.""" CLOCK12: Image - """Image with line pointing to 12 o'clock.""" - + """Imatge d'una línia apuntant les dotze. (les dotze)""" CLOCK11: Image - """Image with line pointing to 11 o'clock.""" - + """Imatge d'una línia apuntant les onze. (les onze)""" CLOCK10: Image - """Image with line pointing to 10 o'clock.""" - + """Imatge d'una línia apuntant les deu. (les deu)""" CLOCK9: Image - """Image with line pointing to 9 o'clock.""" - + """Imatge d'una línia apuntant les nou. (les nou)""" CLOCK8: Image - """Image with line pointing to 8 o'clock.""" - + """Imatge d'una línia apuntant les vuit. (les vuit)""" CLOCK7: Image - """Image with line pointing to 7 o'clock.""" - + """Imatge d'una línia apuntant les set. (les set)""" CLOCK6: Image - """Image with line pointing to 6 o'clock.""" - + """Imatge amb una línia apuntant a les 6 en punt. (les sis)""" CLOCK5: Image - """Image with line pointing to 5 o'clock.""" - + """Imatge amb una línia apuntant a les 5 en punt. (les cinc)""" CLOCK4: Image - """Image with line pointing to 4 o'clock.""" - + """Imatge amb una línia apuntant a les 4 en punt. (les quatre)""" CLOCK3: Image - """Image with line pointing to 3 o'clock.""" - + """Imatge amb una línia apuntant a les 3 en punt. (les tres)""" CLOCK2: Image - """Image with line pointing to 2 o'clock.""" - + """Imatge amb una línia apuntant a les 2 en punt. (les dues)""" CLOCK1: Image - """Image with line pointing to 1 o'clock.""" - + """Imatge amb una línia apuntant a la 1 en punt. (la una)""" ARROW_N: Image - """Image of arrow pointing north.""" - + """Imatge de fletxa apuntant al nord. (fletxa n)""" ARROW_NE: Image - """Image of arrow pointing north east.""" - + """Imatge de fletxa apuntant al nord-est. (fletxa ne)""" ARROW_E: Image - """Image of arrow pointing east.""" - + """Imatge de fletxa apuntant a l'est. (fletxa e)""" ARROW_SE: Image - """Image of arrow pointing south east.""" - + """Imatge de fletxa apuntant al sud-est. (fletxa se)""" ARROW_S: Image - """Image of arrow pointing south.""" - + """Imatge de fletxa apuntant al sud. (fletxa s)""" ARROW_SW: Image - """Image of arrow pointing south west.""" - + """Imatge de fletxa apuntant al sud-oest. (fletxa so)""" ARROW_W: Image - """Image of arrow pointing west.""" - + """Imatge de fletxa apuntant a l'oest. (fletxa o)""" ARROW_NW: Image - """Image of arrow pointing north west.""" - + """Imatge de fletxa apuntant al nord-oest. (fletxa no)""" TRIANGLE: Image - """Image of a triangle pointing up.""" - + """Imatge d'un triangle apuntant amunt.""" TRIANGLE_LEFT: Image - """Image of a triangle in the left corner.""" - + """Imatge d'un triangle en la cantonada esquerra. (triangle a l'esquerra)""" CHESSBOARD: Image - """Alternate LEDs lit in a chessboard pattern.""" - + """Leds alternatius il·luminats en un patró d'escacs. (Tauler d'escacs)""" DIAMOND: Image - """Diamond image.""" - + """Imatge d'un diamant (diamant)""" DIAMOND_SMALL: Image - """Small diamond image.""" - + """Imatge d'un diamant petit (diamant petit)""" SQUARE: Image - """Square image.""" - + """Imatge d'un quadrat (quadrat)""" SQUARE_SMALL: Image - """Small square image.""" - + """Imatge d'un quadrat petit (quadrat petit)""" RABBIT: Image - """Rabbit image.""" - + """Imatge d'un conill. (conill)""" COW: Image - """Cow image.""" - + """Imatge d'una vaca. (vaca)""" MUSIC_CROTCHET: Image - """Crotchet note image.""" - + """Imatge de la nota musical negra (nota musical negra)""" MUSIC_QUAVER: Image - """Quaver note image.""" - + """Imatge de la nota musical corxera (nota musical corxera)""" MUSIC_QUAVERS: Image - """Pair of quavers note image.""" - + """Imatge d'un parell de notes musicals corxeres (nota musical corxera)""" PITCHFORK: Image - """Pitchfork image.""" - + """Imatge d'una forca. (forca)""" XMAS: Image - """Christmas tree image.""" - + """Imatge d'un arbre de Nadal (nadal)""" PACMAN: Image - """Pac-Man arcade character image.""" - + """Imatge del personatge de Pac-man a arcade""" TARGET: Image - """Target image.""" - + """Imatge d'objectiu. (diana)""" TSHIRT: Image - """T-shirt image.""" - + """Imatge de samarreta. (Imatge d'una samarreta T-shirt)""" ROLLERSKATE: Image - """Rollerskate image.""" - + """Imatge d'un patinet. (patinet)""" DUCK: Image - """Duck image.""" - + """Imatge d'un ànec. (ànec)""" HOUSE: Image - """House image.""" - + """Imatge d'una casa. (casa)""" TORTOISE: Image - """Tortoise image.""" - + """Imatge d'una tortuga. (tortuga)""" BUTTERFLY: Image - """Butterfly image.""" - + """Imatge d'una papallona. (papallona)""" STICKFIGURE: Image - """Stick figure image.""" - + """Imatge de figura d'un pal. (imatge d'un pal)""" GHOST: Image - """Ghost image.""" - + """Imatge d'un fantasma. (fantasma)""" SWORD: Image - """Sword image.""" - + """Imatge d'una espasa (espasa)""" GIRAFFE: Image - """Giraffe image.""" - + """Imatge d'una girafa. (girafa)""" SKULL: Image - """Skull image.""" - + """Imatge d'un crani. (crani)""" UMBRELLA: Image - """Umbrella image.""" - + """Imatge d'un paraigua, (paraigua)""" SNAKE: Image - """Snake image.""" - + """Imatge d'una serp. (serp)""" SCISSORS: Image - """Scissors image.""" - + """Imatge d'unes tisores. (tisores)""" ALL_CLOCKS: List[Image] - """A list containing all the CLOCK_ images in sequence.""" - + """Una llista que conté totes les imatges CLOCK_ en seqüència. (tots els rellotges)""" ALL_ARROWS: List[Image] - """A list containing all the ARROW_ images in sequence.""" + """Una llista que conté totes les ARROW_images en seqüència. (totes les fletxes)""" + @overload def __init__(self, string: str) -> None: - """Create an image from a string describing which LEDs are lit. + """Crea una imatge a partir d'una cadena que descrigui quins leds estan encesos. - ``string`` has to consist of digits 0-9 arranged into lines, - describing the image, for example:: +``string`` has to consist of digits 0-9 arranged into lines, +describing the image, for example:: - image = Image("90009:" - "09090:" - "00900:" - "09090:" - "90009") + 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 newlines (\\n) insead of the colons. +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 newlines (\\n) insead of the colons. - :param string: The string describing the image. - """ +:param string: (cadena) La cadena descrivint la imatge.""" ... + @overload - def __init__( - self, width: int = 5, height: int = 5, buffer: ReadableBuffer = None - ) -> None: - """Create an empty image with ``width`` columns and ``height`` rows. + def __init__(self, width: int=5, height: int=5, buffer: ReadableBuffer=None) -> None: + """Crea una imatge buida amb ``width`` columnes i ``height`` files. - :param width: Optional width of the image - :param height: Optional height of the image - :param buffer: Optional array or bytes of ``width``×``height`` integers in range 0-9 to initialize the image +:param width: (amplada) Amplada opcional de la imatge +:param height: (alçària) Alçària opcional de la imatge +:param buffer: (memòria intermèdia) Llistes o bytes opcionals d'enters de ``width``×``height`` dins l'interval de 0 a 9 per inicialitzar la imatge - Examples:: +Examples:: - Image(2, 2, b'\x08\x08\x08\x08') - Image(2, 2, bytearray([9,9,9,9])) + Image(2, 2, b'\x08\x08\x08\x08') + Image(2, 2, bytearray([9,9,9,9])) - These create 2 x 2 pixel images at full brightness. - """ +These create 2 x 2 pixel images at full brightness.""" ... + def width(self) -> int: - """Get the number of columns. + """Obté el nombre de columnes (amplada) - :return: The number of columns in the image - """ +:return: The number of columns in the image""" ... + def height(self) -> int: - """Get the number of rows. + """Obté el nombre de files. (alçària) - :return: The number of rows in the image - """ +:return: The number of rows in the image""" ... + def set_pixel(self, x: int, y: int, value: int) -> None: - """Set the brightness of a pixel. + """Estableix la brillantor d'un píxel. (estableix píxel) - Example: ``my_image.set_pixel(0, 0, 9)`` +Example: ``my_image.set_pixel(0, 0, 9)`` - :param x: The column number - :param y: The row number - :param value: The brightness as an integer between 0 (dark) and 9 (bright) +:param x: El nombre de la columna +:param y: El nombre de la fila +:param value: (valor) La brillantor com a nombre enter entre 0 (fosc) i 9 (brillant) - This method will raise an exception when called on any of the built-in - read-only images, like ``Image.HEART``. - """ +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: - """Get the brightness of a pixel. + """Obté la brillantor d'un píxel. (obté píxel) - Example: ``my_image.get_pixel(0, 0)`` +Example: ``my_image.get_pixel(0, 0)`` - :param x: The column number - :param y: The row number - :return: The brightness as an integer between 0 and 9. - """ +:param x: El nombre de la columna +:param y: El nombre de la fila +:return: The brightness as an integer between 0 and 9.""" ... + def shift_left(self, n: int) -> Image: - """Create a new image by shifting the picture left. + """Crea una imatge nova movent-la cap a l'esquerra. (desplaça a l'esquerra) - Example: ``Image.HEART_SMALL.shift_left(1)`` +Example: ``Image.HEART_SMALL.shift_left(1)`` - :param n: The number of columns to shift by - :return: The shifted image - """ +:param n: El nombre de columnes per desplaçar-se +:return: The shifted image""" ... + def shift_right(self, n: int) -> Image: - """Create a new image by shifting the picture right. + """Crea una imatge nova movent-la cap a la dreta. (desplaça a la dreta) - Example: ``Image.HEART_SMALL.shift_right(1)`` +Example: ``Image.HEART_SMALL.shift_right(1)`` - :param n: The number of columns to shift by - :return: The shifted image - """ +:param n: El nombre de columnes per desplaçar-se +:return: The shifted image""" ... + def shift_up(self, n: int) -> Image: - """Create a new image by shifting the picture up. + """Crea una imatge nova desplaçant la imatge cap amunt. (desplaça cap amunt) - Example: ``Image.HEART_SMALL.shift_up(1)`` +Example: ``Image.HEART_SMALL.shift_up(1)`` - :param n: The number of rows to shift by - :return: The shifted image - """ +:param n: El nombre de files per desplaçar-se +:return: The shifted image""" ... + def shift_down(self, n: int) -> Image: - """Create a new image by shifting the picture down. + """Crea una imatge nova desplaçant-la cap avall. (desplaça cap avall) - Example: ``Image.HEART_SMALL.shift_down(1)`` +Example: ``Image.HEART_SMALL.shift_down(1)`` - :param n: The number of rows to shift by - :return: The shifted image - """ +:param n: El nombre de files per desplaçar-se +:return: The shifted image""" ... + def crop(self, x: int, y: int, w: int, h: int) -> Image: - """Create a new image by cropping the picture. + """Crea una imatge nova retallant la imatge. (retalla) - Example: ``Image.HEART.crop(1, 1, 3, 3)`` +Example: ``Image.HEART.crop(1, 1, 3, 3)`` - :param x: The crop offset column - :param y: The crop offset row - :param w: The crop width - :param h: The crop height - :return: The new image - """ +:param x: La columna de desplaçament del retall +:param y: La fila de desplaçament del retall +:param w: L'amplada del retall +:param h: L'alçària del retall +:return: The new image""" ... + def copy(self) -> Image: - """Create an exact copy of the image. + """Crea una còpia exacta de la imatge (còpia) - Example: ``Image.HEART.copy()`` +Example: ``Image.HEART.copy()`` - :return: The new image - """ +:return: The new image""" ... + def invert(self) -> Image: - """Create a new image by inverting the brightness of the pixels in the - source image. + """Crea una imatge nova invertint la brillantor dels píxels de la imatge +font. (inverteix) - Example: ``Image.SMALL_HEART.invert()`` +Example: ``Image.SMALL_HEART.invert()`` - :return: The new image. - """ +:return: The new image.""" ... + def fill(self, value: int) -> None: - """Set the brightness of all the pixels in the image. + """Assigna la brillantor de tots els píxels de la imatge (omple) - Example: ``my_image.fill(5)`` +Example: ``my_image.fill(5)`` - :param value: The new brightness as a number between 0 (dark) and 9 (bright). +:param value: (valor) La nova brillantor com a nombre entre 0 (fosc) i 9 (brillant). - This method will raise an exception when called on any of the built-in - read-only images, like ``Image.HEART``. - """ +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 an area from another image into this image. - - Example: ``my_image.blit(Image.HEART, 1, 1, 3, 3, 1, 1)`` - - :param src: The source image - :param x: The starting column offset in the source image - :param y: The starting row offset in the source image - :param w: The number of columns to copy - :param h: The number of rows to copy - :param xdest: The column offset to modify in this image - :param ydest: The row offset to modify in this image - - Pixels outside the source image are treated as having a brightness 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 blit(self, src: Image, x: int, y: int, w: int, h: int, xdest: int=0, ydest: int=0) -> None: + """Copia una àrea d'una altra imatge a aquesta imatge. + +Example: ``my_image.blit(Image.HEART, 1, 1, 3, 3, 1, 1)`` + +:param src: (font) La imatge font +:param x: Desplaçament de la columna inicial a la imatge d'origen +:param y: Desplaçament de la fila inicial a la imatge d'origen +:param w: El nombre de columnes a copiar +:param h: El nombre de files a copiar +:param xdest: El desplaçament de columna a modificar en aquesta imatge +:param ydest: El desplaçament de fila que cal modificar en aquesta imatge + +Pixels outside the source image are treated as having a brightness 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.""" + """Obté una representació de cadena compacta de la imatge. (repr - Obté una representació de cadena compacta de la imatge.)""" ... + def __str__(self) -> str: - """Get a readable string representation of the image.""" + """Obté una representació de cadena llegible de la imatge.""" ... + def __add__(self, other: Image) -> Image: - """Create a new image by adding the brightness values from the two - images for each pixel. + """Crea una imatge nova afegint els valors de brillantor de les dues +imatges per a cada píxel. (afegeix) - Example: ``Image.HEART + Image.HAPPY`` +Example: ``Image.HEART + Image.HAPPY`` - :param other: The image to add. - """ +:param other: (altre) La imatge a afegir.""" ... + def __sub__(self, other: Image) -> Image: - """Create a new image by subtracting the brightness values of the - other image from this image. + """Crea una imatge nova restant els valors de brillantor d'una altra imatge d'aquesta imatge. - Example: ``Image.HEART - Image.HEART_SMALL`` +Example: ``Image.HEART - Image.HEART_SMALL`` - :param other: The image to subtract. - """ +:param other: (altre) La imatge a restar.""" ... + def __mul__(self, n: float) -> Image: - """Create a new image by multiplying the brightness of each pixel by - ``n``. + """Crea una imatge nova multiplicant la brillantor de cada píxel per +``n``. - Example: ``Image.HEART * 0.5`` +Example: ``Image.HEART * 0.5`` - :param n: The value to multiply by. - """ +:param n: El valor per multiplicar.""" ... + def __truediv__(self, n: float) -> Image: - """Create a new image by dividing the brightness of each pixel by - ``n``. + """Crea una imatge nova dividint la brillantor de cada píxel per +``n``. - Example: ``Image.HEART / 2`` +Example: ``Image.HEART / 2`` - :param n: The value to divide by. - """ +:param n: El valor del divisor.""" ... class SoundEvent: LOUD: SoundEvent - """Represents the transition of sound events, from ``quiet`` to ``loud`` like clapping or shouting.""" - + """Representa la transició dels esdeveniments de so, des de ``quiet`` a ``loud`` com picant de mans o cridant. (so fort)""" QUIET: SoundEvent - """Represents the transition of sound events, from ``loud`` to ``quiet`` like speaking or background music.""" + """Representa la transició dels esdeveniments de so, des de ``loud`` a ``quiet`` com parlant o música de fons. (so fluix)""" class Sound: - """The built-in sounds can be called using ``audio.play(Sound.NAME)``.""" - + """Els sons integrats es poden reproduir mitjançant ``audio.play(Sound.NAME)``. (so)""" GIGGLE: Sound - """Giggling sound.""" - + """So de riure (riure)""" HAPPY: Sound - """Happy sound.""" - + """So feliç. (feliç)""" HELLO: Sound - """Greeting sound.""" - + """So de salutació. (hola)""" MYSTERIOUS: Sound - """Mysterious sound.""" - + """So misteriós. (misteriós)""" SAD: Sound - """Sad sound.""" - + """So trist. (tristesa)""" SLIDE: Sound - """Sliding sound.""" - + """So lliscant (so lliscant)""" SOARING: Sound - """Soaring sound.""" - + """So creixent. (creixent)""" SPRING: Sound - """Spring sound.""" - + """So primaveral. (primaveral)""" TWINKLE: Sound - """Twinkling sound.""" - + """So de centelleig. (centelleig)""" YAWN: Sound - """Yawning sound.""" + """So de badall. (badall)""" \ No newline at end of file diff --git a/lang/ca/typeshed/stdlib/microbit/accelerometer.pyi b/lang/ca/typeshed/stdlib/microbit/accelerometer.pyi index bac82c0..c52b9d7 100644 --- a/lang/ca/typeshed/stdlib/microbit/accelerometer.pyi +++ b/lang/ca/typeshed/stdlib/microbit/accelerometer.pyi @@ -1,115 +1,103 @@ -"""Measure the acceleration of the micro:bit and recognise gestures. -""" - +"""Mesura l'acceleració de la micro:bit i reconeix els gestos. (acceleròmetre)""" from typing import Tuple def get_x() -> int: - """Get the acceleration measurement in the ``x`` axis in milli-g. + """Obté la mesura de l'acceleració a l'eix ``x`` en mili-g. (obté x) - Example: ``accelerometer.get_x()`` +Example: ``accelerometer.get_x()`` - :return: A positive or negative integer depending on direction in the range +/- 2000mg. - """ +:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" ... def get_y() -> int: - """Get the acceleration measurement in the ``y`` axis in milli-g. + """Obté la mesura de l'acceleració a l'eix ``y`` en mili-g. (obté y) - Example: ``accelerometer.get_y()`` +Example: ``accelerometer.get_y()`` - :return: A positive or negative integer depending on direction in the range +/- 2000mg. - """ +:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" ... def get_z() -> int: - """Get the acceleration measurement in the ``z`` axis in milli-g. + """Obté la mesura de l'acceleració a l'eix ``z`` en mili-g. (obté z) - Example: ``accelerometer.get_z()`` +Example: ``accelerometer.get_z()`` - :return: A positive or negative integer depending on direction in the range +/- 2000mg. - """ +:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" ... def get_values() -> Tuple[int, int, int]: - """Get the acceleration measurements in all axes at once as a tuple. + """Obté les mesures d'acceleració en tots els eixos alhora com una tupla. (obté valors) - Example: ``x, y, z = accelerometer.get_values()`` +Example: ``x, y, z = accelerometer.get_values()`` - :return: a three-element tuple of integers ordered as X, Y, Z, each value a positive or negative integer depending on direction in the range +/- 2000mg - """ +:return: a three-element tuple of integers ordered as X, Y, Z, each value a positive or negative integer depending on direction in the range +/- 2000mg""" ... def get_strength() -> int: - """Get the acceleration measurement of all axes combined, as a positive integer. This is the Pythagorean sum of the X, Y and Z axes. + """Obté la mesura de l'acceleració de tots els eixos combinats, com un nombre enter positiu. Aquest serà la suma Pitagòrica dels eixos X, Y i Z. (obté la força) - Example: ``accelerometer.get_strength()`` +Example: ``accelerometer.get_strength()`` - :return: The combined acceleration strength of all the axes, in milli-g. - """ +:return: The combined acceleration strength of all the axes, in milli-g.""" ... def current_gesture() -> str: - """Get the name of the current gesture. + """Obté el nom del gest actual. (El gest actual) - Example: ``accelerometer.current_gesture()`` +Example: ``accelerometer.current_gesture()`` - 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. +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. - :return: The current gesture - """ +:return: The current gesture""" ... def is_gesture(name: str) -> bool: - """Check if the named gesture is currently active. + """Comprova si el gest nomenat està actiu actualment. - Example: ``accelerometer.is_gesture('shake')`` +Example: ``accelerometer.is_gesture('shake')`` - 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. +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. - :param name: The gesture name. - :return: ``True`` if the gesture is active, ``False`` otherwise. - """ +:param name: (nom) El nom del gest +:return: ``True`` if the gesture is active, ``False`` otherwise.""" ... def was_gesture(name: str) -> bool: - """Check if the named gesture was active since the last call. + """Comprova si el gest nomenat ha estat actiu des de l'última crida. - Example: ``accelerometer.was_gesture('shake')`` +Example: ``accelerometer.was_gesture('shake')`` - 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. +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. - :param name: The gesture name. - :return: ``True`` if the gesture was active since the last call, ``False`` otherwise. - """ +:param name: (nom) El nom del gest +:return: ``True`` if the gesture was active since the last call, ``False`` otherwise.""" def get_gestures() -> Tuple[str, ...]: - """Return a tuple of the gesture history. + """Retorna una tupla de l'historial de gestos. (obté gestos) - Example: ``accelerometer.get_gestures()`` +Example: ``accelerometer.get_gestures()`` - Clears the gesture history before returning. +Clears the gesture history before returning. - Gestures are not updated in the background so there needs to be constant - calls to some accelerometer method to do the gesture detection. Usually - gestures can be detected using a loop with a small :func:`microbit.sleep` delay. +Gestures are not updated in the background so there needs to be constant +calls to some accelerometer method to do the gesture detection. Usually +gestures can be detected using a loop with a small :func:`microbit.sleep` delay. - :return: The history as a tuple, most recent last. - """ +:return: The history as a tuple, most recent last.""" ... def set_range(value: int) -> None: - """Set the accelerometer sensitivity range, in g (standard gravity), to the closest values supported by the hardware, so it rounds to either ``2``, ``4``, or ``8`` g. + """Estableix l'interval de la sensibilitat de l'acceleròmetre, en g (gravetat estàndard), al valor més proper acceptat pel maquinari, arrodonit a ``2``, ``4``, o ``8`` - Example: ``accelerometer.set_range(8)`` +Example: ``accelerometer.set_range(8)`` - :param value: New range for the accelerometer, an integer in ``g``. - """ +:param value: (valor) Nou interval per a l'acceleròmetre, un nombre enter a ``g``.""" \ No newline at end of file diff --git a/lang/ca/typeshed/stdlib/microbit/audio.pyi b/lang/ca/typeshed/stdlib/microbit/audio.pyi index 3b1e327..8c8c6bd 100644 --- a/lang/ca/typeshed/stdlib/microbit/audio.pyi +++ b/lang/ca/typeshed/stdlib/microbit/audio.pyi @@ -1,160 +1,124 @@ -"""Play sounds using the micro:bit (import ``audio`` for V1 compatibility). -""" - +"""Reprodueix sons amb la micro:bit (importa ``audio`` per a la compatibilitat amb V1). (àudio)""" from ..microbit import MicroBitDigitalPin, Sound, pin0 from typing import ClassVar, Iterable, Union -def play( - source: Union[Iterable[AudioFrame], Sound, SoundEffect], - wait: bool = True, - pin: MicroBitDigitalPin = pin0, - return_pin: Union[MicroBitDigitalPin, None] = None, -) -> None: - """Play a built-in sound, sound effect or custom audio frames. +def play(source: Union[Iterable[AudioFrame], Sound, SoundEffect], wait: bool=True, pin: MicroBitDigitalPin=pin0, return_pin: Union[MicroBitDigitalPin, None]=None) -> None: + """Reprodueix un so incorporat, un efecte de só o marcs d'àudio personalitzats. - Example: ``audio.play(Sound.GIGGLE)`` +Example: ``audio.play(Sound.GIGGLE)`` - :param source: A built-in ``Sound`` such as ``Sound.GIGGLE``, a ``SoundEffect`` or sample data as an iterable of ``AudioFrame`` objects. - :param wait: If ``wait`` is ``True``, this function will block until the sound is complete. - :param pin: An optional argument to specify the output pin can be used to override the default of ``pin0``. If we do not want any sound to play we can use ``pin=None``. - :param return_pin: Specifies a differential edge connector pin to connect to an external speaker instead of ground. This is ignored for the **V2** revision. - """ +:param source: (origen) Un objecte de ``Sound`` incorporat com ``Sound.GIGGLE``, un ``SoundEffect`` o una data de mostra com un iterable de ``AudioFrame`` . +:param wait: (espera) Si ``wait`` és ``True``, aquesta funció es bloquejarà fins que s'acabi el so. +:param pin: Es pot utilitzar un argument opcional per especificar el pin de sortida per anul·lar el valor predeterminat de ``pin0``. Si no vols que es reprodueixi cap so, pots utilitzar ``pin=None``. +:param return_pin: (retorna el pin) Especifica un pin diferent del connector d'expansió per connectar-lo a un altaveu extern en lloc de posar a terra. Això s'ignora per a la revisió **V2**.""" def is_playing() -> bool: - """Check whether a sound is playing. + """Verifica si s'està reproduint un so. (està reproduint) - Example: ``audio.is_playing()`` +Example: ``audio.is_playing()`` - :return: ``True`` if audio is playing, otherwise ``False``.""" +:return: ``True`` if audio is playing, otherwise ``False``.""" ... def stop() -> None: - """Stop all audio playback. + """Atura tota la reproducció d'àudio. (atura) - Example: ``audio.stop()`` - """ +Example: ``audio.stop()``""" ... class SoundEffect: - """A sound effect, composed by a set of parameters configured via the constructor or attributes.""" - + """Un efecte sonor, compost per un conjunt de paràmetres configurats via el constructor o atributs.""" WAVEFORM_SINE: ClassVar[int] - """Sine wave option used for the ``waveform`` parameter.""" - + """Opció d'ona sinusoidal pel paràmetre ``waveform``. (forma d'ona sinusoidal)""" WAVEFORM_SAWTOOTH: ClassVar[int] - """Sawtooth wave option used for the ``waveform`` parameter.""" - + """Opció d'ona de dent de serra pel paràmetre ``waveform``. (forma d'ona de dent de serra)""" WAVEFORM_TRIANGLE: ClassVar[int] - """Triangle wave option used for the ``waveform`` parameter.""" - + """Opció d'ona triangular pel paràmetre ``waveform``. (forma d'ona triangular)""" WAVEFORM_SQUARE: ClassVar[int] - """Square wave option used for the ``waveform`` parameter.""" - + """Opció d'ona quadrada pel paràmetre ``waveform``. (forma d'ona quadrada)""" WAVEFORM_NOISE: ClassVar[int] - """Noise option used for the ``waveform`` parameter.""" - + """Opció d'ona de soroll pel paràmetre ``waveform``. (forma d'ona de soroll)""" SHAPE_LINEAR: ClassVar[int] - """Linear interpolation option used for the ``shape`` parameter.""" - + """Opció d'ona lineal pel paràmetre ``shape``. (forma lineal)""" SHAPE_CURVE: ClassVar[int] - """Curve interpolation option used for the ``shape`` parameter.""" - + """Opció d'interpolació de corba usada pel paràmetre ``shape``. (forma de corba)""" SHAPE_LOG: ClassVar[int] - """Logarithmic interpolation option used for the ``shape`` parameter.""" - + """Opció d'interpolació logarítmica utilitzada pel paràmetre ``shape``. (forma logarítmica)""" FX_NONE: ClassVar[int] - """No effect option used for the ``fx`` parameter.""" - + """Opció de cap efecte utilitzat pel paràmetre ``fx``. (fx cap)""" FX_TREMOLO: ClassVar[int] - """Tremolo effect option used for the ``fx`` parameter.""" - + """Opció d'efecte trèmolo utilitzat pel paràmetre ``fx``. (fx trémolo)""" FX_VIBRATO: ClassVar[int] - """Vibrato effect option used for the ``fx`` parameter.""" - + """Opció d'efecte vibrato utilitzat pel paràmetre ``fx``.""" FX_WARBLE: ClassVar[int] - """Warble effect option used for the ``fx`` parameter.""" - + """Opció d'efecte gorjeu utilitzat pel paràmetre ``fx``. (Efecte gorjeu)""" freq_start: int - """Start frequency in Hertz (Hz), a number between ``0`` and ``9999``""" - + """Freqüència inicial en Hertz (Hz), un nombre entre ``0`` i ``9999`` (freqüència inicial)""" freq_end: int - """End frequency in Hertz (Hz), a number between ``0`` and ``9999``""" - + """Freqüència final en Hertz (Hz), un nombre entre ``0`` i ``9999`` (frequència final)""" duration: int - """Duration of the sound in milliseconds, a number between ``0`` and ``9999``""" - + """Durada del so en mil·lisegons, un nombre entre ``0`` and ``9999`` (Durada - duració)""" vol_start: int - """Start volume value, a number between ``0`` and ``255``""" - + """Volum inicial, un nombre entre ``0`` and ``255`` (volum inicial)""" vol_end: int - """End volume value, a number between ``0`` and ``255``""" - + """Valor del volum final, un nombre entre ``0`` and ``255`` (volum final)""" waveform: int - """Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise)""" - + """Tipus de forma d'ona, un d'aquest valors: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise) (forma d'ona)""" fx: int - """Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``""" - + """Efecte a afegir al so, un dels següents valors: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE`` (efecte)""" shape: int - """The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``""" - - def __init__( - self, - freq_start: int = 500, - freq_end: int = 2500, - duration: int = 500, - vol_start: int = 255, - vol_end: int = 0, - waveform: int = WAVEFORM_SQUARE, - fx: int = FX_NONE, - shape: int = SHAPE_LOG, - ): - """Create a new sound effect. - - Example: ``my_effect = SoundEffect(duration=1000)`` - - All the parameters are optional, with default values as shown above, and - they can all be modified via attributes of the same name. For example, we - can first create an effect ``my_effect = SoundEffect(duration=1000)``, - and then change its attributes ``my_effect.duration = 500``. - - :param freq_start: Start frequency in Hertz (Hz), a number between ``0`` and ``9999``. - :param freq_end: End frequency in Hertz (Hz), a number between ``0`` and ``9999``. - :param duration: Duration of the sound in milliseconds, a number between ``0`` and ``9999``. - :param vol_start: Start volume value, a number between ``0`` and ``255``. - :param vol_end: End volume value, a number between ``0`` and ``255``. - :param waveform: Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise). - :param fx: Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``. - :param shape: The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``. - """ + """El tipus de corba d'interpolació entre les freqüències inicial i final, diferents formes d'ona tenen diferents ràtios de canvi en la freqüència. Un dels següents valors: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG`` (forma)""" + + def __init__(self, freq_start: int=500, freq_end: int=2500, duration: int=500, vol_start: int=255, vol_end: int=0, waveform: int=WAVEFORM_SQUARE, fx: int=FX_NONE, shape: int=SHAPE_LOG): + """Crea un efecte de so nou. (inicial) + +Example: ``my_effect = SoundEffect(duration=1000)`` + +All the parameters are optional, with default values as shown above, and +they can all be modified via attributes of the same name. For example, we +can first create an effect ``my_effect = SoundEffect(duration=1000)``, +and then change its attributes ``my_effect.duration = 500``. + +:param freq_start: (freqüència inicial) Freqüència inicial en Hertz (Hz), un nombre entre ``0`` i ``9999``. +:param freq_end: (frequència final) Freqüència final en Hertz (Hz), un nombre entre ``0`` i ``9999``. +:param duration: (Durada - duració) Duració del so en mil·lisegons, un nombre entre ``0`` i ``9999``. +:param vol_start: (volum inicial) Valor del volum inicial, un nombre entre ``0`` i ``255``. +:param vol_end: (volum final) Valor del volum final, un nombre entre ``0`` i ``255``. +:param waveform: (forma d'ona) Tipus de forma d'ona, un d'aquests valors: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (soroll generat aleatòriament). +:param fx: (efecte) Efecte a afegir al so, un del següents valors: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``. +:param shape: (forma) El tipus de corba d'interpolació entre les freqüències inicial i final, diferents formes d'ona tenen diferents ràtios de canvi en la freqüència. Un dels següents valors: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``""" + def copy(self) -> SoundEffect: - """Create a copy of this ``SoundEffect``. + """Crea una còpia d'aquest ``SoundEffect``. (còpia) - Example: ``sound_2 = sound_1.copy()`` +Example: ``sound_2 = sound_1.copy()`` - :return: A copy of the SoundEffect. - """ +:return: A copy of the SoundEffect.""" class AudioFrame: - """An ``AudioFrame`` object is a list of 32 samples each of which is a unsigned byte - (whole number between 0 and 255). + """Un objecte ``AudioFrame`` és una llista de 32 mostres cadascuna de les quals és un byte sense signar +(nombre enter entre 0 i 255). - It takes just over 4 ms to play a single frame. +It takes just over 4 ms to play a single frame. - Example:: +Example:: - frame = AudioFrame() - for i in range(len(frame)): - frame[i] = 252 - i * 8 - """ + frame = AudioFrame() + for i in range(len(frame)): + frame[i] = 252 - i * 8""" def copyfrom(self, other: AudioFrame) -> None: - """Overwrite the data in this ``AudioFrame`` with the data from another ``AudioFrame`` instance. + """Sobreposa les dades d'aquest ``AudioFrame`` amb les dades d'una altra instància ``AudioFrame`` . (copia desde) + +Example: ``my_frame.copyfrom(source_frame)`` + +:param other: (altre) ``AudioFrame`` instància de la qual copiar les dades.""" + + def __len__(self) -> int: + ... - Example: ``my_frame.copyfrom(source_frame)`` + def __setitem__(self, key: int, value: int) -> None: + ... - :param other: ``AudioFrame`` instance from which to copy the data. - """ - def __len__(self) -> int: ... - def __setitem__(self, key: int, value: int) -> None: ... - def __getitem__(self, key: int) -> int: ... + def __getitem__(self, key: int) -> int: + ... \ No newline at end of file diff --git a/lang/ca/typeshed/stdlib/microbit/compass.pyi b/lang/ca/typeshed/stdlib/microbit/compass.pyi index c74a47b..9d7bc37 100644 --- a/lang/ca/typeshed/stdlib/microbit/compass.pyi +++ b/lang/ca/typeshed/stdlib/microbit/compass.pyi @@ -1,78 +1,70 @@ -"""Use the built-in compass. -""" +"""Utilitza la brúixola integrada. (brúixola)""" def calibrate() -> None: - """Starts the calibration process. + """Comença el procés de calibració (calibrar) - Example: ``compass.calibrate()`` +Example: ``compass.calibrate()`` - 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. - """ +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: - """Check is the compass is calibrated. + """Verifica si la brúixola està calibrada. (s'ha calibrat) - Example: ``compass.is_calibrated()`` +Example: ``compass.is_calibrated()`` - :return: ``True`` if the compass has been successfully calibrated, ``False`` otherwise. - """ +:return: ``True`` if the compass has been successfully calibrated, ``False`` otherwise.""" ... def clear_calibration() -> None: - """Undoes the calibration, making the compass uncalibrated again. + """Desfà el calibratge, fent que la brúixola torni a estar sense calibració. (esborra la calibració) - Example: ``compass.clear_calibration()`` - """ +Example: ``compass.clear_calibration()``""" ... def get_x() -> int: - """Get the magnetic field strength on the ``x`` axis. + """Obté la intensitat del camp magnètic de l'eix ``x`` . (obté x) - Example: ``compass.get_x()`` +Example: ``compass.get_x()`` - Call ``calibrate`` first or the results will be inaccurate. +Call ``calibrate`` first or the results will be inaccurate. - :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. - """ +:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" ... def get_y() -> int: - """Get the magnetic field strength on the ``y`` axis. + """Obté la intensitat del camp magnètic de l'eix ``y`` . (obté y) - Example: ``compass.get_y()`` +Example: ``compass.get_y()`` - Call ``calibrate`` first or the results will be inaccurate. +Call ``calibrate`` first or the results will be inaccurate. - :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. - """ +:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" ... def get_z() -> int: - """Get the magnetic field strength on the ``z`` axis. + """Obté la intensitat del camp magnètic a l'eix ``z``. (obté z) - Example: ``compass.get_z()`` +Example: ``compass.get_z()`` - Call ``calibrate`` first or the results will be inaccurate. +Call ``calibrate`` first or the results will be inaccurate. - :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. - """ +:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" ... def heading() -> int: - """Get the compass heading. + """Obté l'orientació de la brúixola. - Example: ``compass.heading()`` +Example: ``compass.heading()`` - :return: An integer in the range from 0 to 360, representing the angle in degrees, clockwise, with north as 0. - """ +:return: An integer in the range from 0 to 360, representing the angle in degrees, clockwise, with north as 0.""" ... def get_field_strength() -> int: - """Get the magnitude of the magnetic field around the device. + """Obté la magnitud del camp magnètic al voltant del dispositiu. (obté la intensitat del camp) - Example: ``compass.get_field_strength()`` +Example: ``compass.get_field_strength()`` - :return: An integer indication of the magnitude of the magnetic field in nano tesla.""" - ... +:return: An integer indication of the magnitude of the magnetic field in nano tesla.""" + ... \ No newline at end of file diff --git a/lang/ca/typeshed/stdlib/microbit/display.pyi b/lang/ca/typeshed/stdlib/microbit/display.pyi index aa4013e..e302f86 100644 --- a/lang/ca/typeshed/stdlib/microbit/display.pyi +++ b/lang/ca/typeshed/stdlib/microbit/display.pyi @@ -1,115 +1,92 @@ -"""Show text, images and animations on the 5×5 LED display. -""" - +"""Mostra text, imatges i animacions a la pantalla LED 5×5. (pantalla)""" from ..microbit import Image from typing import Union, overload, Iterable def get_pixel(x: int, y: int) -> int: - """Get the brightness of the LED at column ``x`` and row ``y``. + """Obté la brillantor del LED a la columna ``x`` i la fila ``y``. (obté píxel) - Example: ``display.get_pixel(0, 0)`` +Example: ``display.get_pixel(0, 0)`` - :param x: The display column (0..4) - :param y: The display row (0..4) - :return: A number between 0 (off) and 9 (bright) - """ +:param x: La columna de la pantalla (0...4) +:param y: La fila de la pantalla (0...4) +:return: A number 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``. + """Estableix la brillantor del LED a la columna ``x`` i la fila ``y``. (estableix píxel) - Example: ``display.set_pixel(0, 0, 9)`` +Example: ``display.set_pixel(0, 0, 9)`` - :param x: The display column (0..4) - :param y: The display row (0..4) - :param value: The brightness between 0 (off) and 9 (bright) - """ +:param x: La columna de la pantalla (0...4) +:param y: La fila de la pantalla (0...4) +:param value: (valor) La brillantor entre 0 (apagat) i 9 (brillant)""" ... def clear() -> None: - """Set the brightness of all LEDs to 0 (off). + """Estableix la brillantor de tots els leds a 0 (apagat). - Example: ``display.clear()`` - """ +Example: ``display.clear()``""" ... -def show( - image: Union[str, float, int, Image, Iterable[Image]], - delay: int = 400, - wait: bool = True, - loop: bool = False, - clear: bool = False, -) -> None: - """Shows images, letters or digits on the LED display. +def show(image: Union[str, float, int, Image, Iterable[Image]], delay: int=400, wait: bool=True, loop: bool=False, clear: bool=False) -> None: + """Mostra imatges, lletres o dígits en la pantalla LED. (mostra) - Example: ``display.show(Image.HEART)`` +Example: ``display.show(Image.HEART)`` - When ``image`` is an image or a list of images then each image is displayed in turn. - If ``image`` is a string or number, each letter or digit is displayed in turn. +When ``image`` is an image or a list of images then each image is displayed in turn. +If ``image`` is a string or number, each letter or digit is displayed in turn. - :param image: A string, number, image or list of images to show. - :param delay: Each letter, digit or image is shown with ``delay`` milliseconds between them. - :param wait: If ``wait`` is ``True``, this function will block until the animation is finished, otherwise the animation will happen in the background. - :param loop: If ``loop`` is ``True``, the animation will repeat forever. - :param clear: If ``clear`` is ``True``, the display will be cleared after the sequence has finished. +:param image: (imatge) Una cadena, un nombre, una imatge o una llista d'imatges per mostrar. +:param delay: (retard) Cada lletra, dígit o imatge es mostra amb un ``delay`` mil·lisegons entre ells. +:param wait: (espera) Si ``wait`` és ``True``, aquesta funció es bloquejarà fins que s'acabi l'animació, en cas contrari, l'animació passarà en segon pla. +:param loop: (bucle) Si el ``loop`` és ``True``, l'animació es repetirà per sempre. +:param clear: Si ``clear`` és ``True``, la pantalla s'esborrarà un cop finalitzada la seqüència. - The ``wait``, ``loop`` and ``clear`` arguments must be specified using their keyword. - """ +The ``wait``, ``loop`` and ``clear`` arguments must be specified using their keyword.""" ... -def scroll( - text: Union[str, float, int], - delay: int = 150, - wait: bool = True, - loop: bool = False, - monospace: bool = False, -) -> None: - """Scrolls a number or text on the LED display. - - Example: ``display.scroll('micro:bit')`` - - :param text: The string to scroll. If ``text`` is an integer or float it is first converted to a string using ``str()``. - :param delay: The ``delay`` parameter controls how fast the text is scrolling. - :param wait: If ``wait`` is ``True``, this function will block until the animation is finished, otherwise the animation will happen in the background. - :param loop: If ``loop`` is ``True``, the animation will repeat forever. - :param monospace: 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. - - The ``wait``, ``loop`` and ``monospace`` arguments must be specified - using their keyword. - """ +def scroll(text: Union[str, float, int], delay: int=150, wait: bool=True, loop: bool=False, monospace: bool=False) -> None: + """Desplaça un número o text per la pantalla LED. + +Example: ``display.scroll('micro:bit')`` + +:param text: La cadena per a desplaçar. Si ``text`` és un nombre enter o flotant, primer es converteix en una cadena mitjançant ``str()``. +:param delay: (retard) El paràmetre ``delay`` controla la rapidesa amb què es desplaça el text. +:param wait: (espera) Si ``wait`` és ``True``, aquesta funció es bloquejarà fins que s'acabi l'animació, en cas contrari, l'animació passarà en segon pla. +:param loop: (bucle) Si el ``loop`` és ``True``, l'animació es repetirà per sempre. +:param monospace: Si ``monospace`` és ``True``, tots els caràcters ocuparan 5 columnes de píxels d'amplada, en cas contrari, hi haurà exactament 1 columna de píxels en blanc entre cada caràcter mentre es desplacen. + +The ``wait``, ``loop`` and ``monospace`` arguments must be specified +using their keyword.""" ... def on() -> None: - """Turn on the LED display. + """Encén la pantalla LED. - Example: ``display.on()`` - """ +Example: ``display.on()``""" ... def off() -> None: - """Turn off the LED display (disabling the display allows you to re-use the GPIO pins for other purposes). + """Apaga la pantalla LED (desactivar la pantalla et permet reutilitzar els pins GPIO per a altres finalitats). - Example: ``display.off()`` - """ +Example: ``display.off()``""" ... def is_on() -> bool: - """Check whether the LED display is enabled. + """Comprova si la pantalla LED està habilitada. - Example: ``display.is_on()`` +Example: ``display.is_on()`` - :return: ``True`` if the display is on, otherwise returns ``False``. - """ +:return: ``True`` if the display is on, otherwise returns ``False``.""" ... def read_light_level() -> int: - """Read the light level. + """Llegeix el nivell de llum. (llegir el nivell de llum) - Example: ``display.read_light_level()`` +Example: ``display.read_light_level()`` - Uses the display's LEDs in reverse-bias mode to sense the amount of light - falling on the display. +Uses the display's LEDs in reverse-bias mode to sense the amount of light +falling on the display. - :return: An integer between 0 and 255 representing the light level, with larger meaning more light. - """ - ... +:return: An integer between 0 and 255 representing the light level, with larger meaning more light.""" + ... \ No newline at end of file diff --git a/lang/ca/typeshed/stdlib/microbit/i2c.pyi b/lang/ca/typeshed/stdlib/microbit/i2c.pyi index df26efa..6f4ca40 100644 --- a/lang/ca/typeshed/stdlib/microbit/i2c.pyi +++ b/lang/ca/typeshed/stdlib/microbit/i2c.pyi @@ -1,57 +1,49 @@ -"""Communicate with devices using the I²C bus protocol. -""" - +"""Comunicar-se amb dispositius mitjançant el protocol de bus I²C.""" from _typeshed import ReadableBuffer from ..microbit import MicroBitDigitalPin, pin19, pin20 from typing import List -def init( - freq: int = 100000, sda: MicroBitDigitalPin = pin20, scl: MicroBitDigitalPin = pin19 -) -> None: - """Re-initialize a peripheral. +def init(freq: int=100000, sda: MicroBitDigitalPin=pin20, scl: MicroBitDigitalPin=pin19) -> None: + """Reinicialitzar un perifèric. - Example: ``i2c.init()`` +Example: ``i2c.init()`` - :param freq: clock frequency - :param sda: ``sda`` pin (default 20) - :param scl: ``scl`` pin (default 19) +:param freq: freqüència del rellotge +:param sda: Pin ``sda`` (per defecte 20) +:param scl: pin ``scl`` (per defecte 19) - On a micro:bit V1 board, changing the I²C pins from defaults will make - the accelerometer and compass stop working, as they are connected - internally to those pins. This warning does not apply to the **V2** - revision of the micro:bit as this has `separate I²C lines `_ - for the motion sensors and the edge connector. - """ +On a micro:bit V1 board, changing the I²C pins from defaults will make +the accelerometer and compass stop working, as they are connected +internally to those pins. This warning does not apply to the **V2** +revision of the micro:bit as this has `separate I²C lines `_ +for the motion sensors and the edge connector.""" ... def scan() -> List[int]: - """Scan the bus for devices. + """Escaneja el bus dels dispositius - Example: ``i2c.scan()`` +Example: ``i2c.scan()`` - :return: A list of 7-bit addresses corresponding to those devices that responded to the scan. - """ +:return: A list of 7-bit addresses corresponding to those devices that responded to the scan.""" ... -def read(addr: int, n: int, repeat: bool = False) -> bytes: - """Read bytes from a device. +def read(addr: int, n: int, repeat: bool=False) -> bytes: + """Llegeix bytes des d'un dispositiu. (llegeix) - Example: ``i2c.read(0x50, 64)`` +Example: ``i2c.read(0x50, 64)`` - :param addr: The 7-bit address of the device - :param n: The number of bytes to read - :param repeat: If ``True``, no stop bit will be sent - :return: The bytes read - """ +:param addr: L'adreça de 7-bit del dispositiu +:param n: El nombre de bytes a llegir +:param repeat: (repeteix) Si ``True``, no s'enviarà cap bit d'aturada +:return: The bytes read""" ... -def write(addr: int, buf: ReadableBuffer, repeat: bool = False) -> None: - """Write bytes to a device. +def write(addr: int, buf: ReadableBuffer, repeat: bool=False) -> None: + """Escriu bytes en un dispositiu (escriu) - Example: ``i2c.write(0x50, bytes([1, 2, 3]))`` +Example: ``i2c.write(0x50, bytes([1, 2, 3]))`` - :param addr: The 7-bit address of the device - :param buf: A buffer containing the bytes to write - :param repeat: If ``True``, no stop bit will be sent - """ - ... +:param addr: L'adreça de 7-bit del dispositiu +:param buf: Una memòria intermèdia que conté els bytes per escriure +:param repeat: (repeteix) Si ``True``, no s'enviarà cap bit d'aturada""" + ... \ No newline at end of file diff --git a/lang/ca/typeshed/stdlib/microbit/microphone.pyi b/lang/ca/typeshed/stdlib/microbit/microphone.pyi index 68e8f3a..b36703c 100644 --- a/lang/ca/typeshed/stdlib/microbit/microphone.pyi +++ b/lang/ca/typeshed/stdlib/microbit/microphone.pyi @@ -1,70 +1,62 @@ -"""Respond to sound using the built-in microphone (V2 only). -""" - +"""Respon al so fent servir el micròfon integrat (només V2). (micròfon)""" from typing import Optional, Tuple from ..microbit import SoundEvent def current_event() -> Optional[SoundEvent]: - """Get the last recorded sound event + """Obté l'últim esdeveniment de sonor gravat (esdeveniment actual) - Example: ``microphone.current_event()`` +Example: ``microphone.current_event()`` - :return: The event, ``SoundEvent('loud')`` or ``SoundEvent('quiet')``. - """ +:return: The event, ``SoundEvent('loud')`` or ``SoundEvent('quiet')``.""" ... def was_event(event: SoundEvent) -> bool: - """Check if a sound was heard at least once since the last call. + """Comprova si s'ha sentit un so almenys una vegada des de l'última crida. (va ser un esdeveniment) - Example: ``microphone.was_event(SoundEvent.LOUD)`` +Example: ``microphone.was_event(SoundEvent.LOUD)`` - This call clears the sound history before returning. +This call clears the sound history before returning. - :param event: The event to check for, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET`` - :return: ``True`` if sound was heard at least once since the last call, otherwise ``False``. - """ +:param event: (esdeveniment) L'esdeveniment per comprovar, com ara ``SoundEvent.LOUD`` o ``SoundEvent.QUIET`` +:return: ``True`` if sound was heard at least once since the last call, otherwise ``False``.""" ... def is_event(event: SoundEvent) -> bool: - """Check the most recent sound event detected. + """Comprova l'esdeveniment sonor més recent detectat. (és un esdeveniment) - Example: ``microphone.is_event(SoundEvent.LOUD)`` +Example: ``microphone.is_event(SoundEvent.LOUD)`` - This call does not clear the sound event history. +This call does not clear the sound event history. - :param event: The event to check for, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET`` - :return: ``True`` if sound was the most recent heard, ``False`` otherwise. - """ +:param event: (esdeveniment) L'esdeveniment per comprovar, com ara ``SoundEvent.LOUD`` o ``SoundEvent.QUIET`` +:return: ``True`` if sound was the most recent heard, ``False`` otherwise.""" ... def get_events() -> Tuple[SoundEvent, ...]: - """Get the sound event history as a tuple. + """Obté l'historial d'esdeveniments sonors com una tupla. (obté esdeveniments) - Example: ``microphone.get_events()`` +Example: ``microphone.get_events()`` - This call clears the sound history before returning. +This call clears the sound history before returning. - :return: A tuple of the event history with the most recent event last. - """ +:return: A tuple of the event history with the most recent event last.""" ... def set_threshold(event: SoundEvent, value: int) -> None: - """Set the threshold for a sound event. + """Assigna el llinar per un esdeveniment sonor (estableix llindar) - Example: ``microphone.set_threshold(SoundEvent.LOUD, 250)`` +Example: ``microphone.set_threshold(SoundEvent.LOUD, 250)`` - A high threshold means the event will only trigger if the sound is very loud (>= 250 in the example). +A high threshold means the event will only trigger if the sound is very loud (>= 250 in the example). - :param event: A sound event, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET``. - :param value: The threshold level in the range 0-255. - """ +:param event: (esdeveniment) Un esdeveniment sonor, com ara ``SoundEvent.LOUD`` o ``SoundEvent.QUIET``. +:param value: (valor) El llindar en l'interval 0-255.""" ... def sound_level() -> int: - """Get the sound pressure level. + """Obté el nivell de pressió sonora. (nivell de so) - Example: ``microphone.sound_level()`` +Example: ``microphone.sound_level()`` - :return: A representation of the sound pressure level in the range 0 to 255. - """ - ... +:return: A representation of the sound pressure level in the range 0 to 255.""" + ... \ No newline at end of file diff --git a/lang/ca/typeshed/stdlib/microbit/speaker.pyi b/lang/ca/typeshed/stdlib/microbit/speaker.pyi index 5a74a4d..dbce9de 100644 --- a/lang/ca/typeshed/stdlib/microbit/speaker.pyi +++ b/lang/ca/typeshed/stdlib/microbit/speaker.pyi @@ -1,18 +1,15 @@ -"""Control the built-in speaker (V2 only). -""" +"""Controla l'altaveu integrat (només V2). (altaveu)""" def off() -> None: - """Turn the speaker off. + """Apaga l'altaveu. - Example: ``speaker.off()`` +Example: ``speaker.off()`` - This does not disable sound output to an edge connector pin. - """ +This does not disable sound output to an edge connector pin.""" ... def on() -> None: - """Turn the speaker on. + """Encén l'altaveu. - Example: ``speaker.on()`` - """ - ... +Example: ``speaker.on()``""" + ... \ No newline at end of file diff --git a/lang/ca/typeshed/stdlib/microbit/spi.pyi b/lang/ca/typeshed/stdlib/microbit/spi.pyi index 09c4046..9bfac9f 100644 --- a/lang/ca/typeshed/stdlib/microbit/spi.pyi +++ b/lang/ca/typeshed/stdlib/microbit/spi.pyi @@ -1,60 +1,47 @@ -"""Communicate with devices using the serial peripheral interface (SPI) bus. -""" - +"""Comunica amb dispositius mitjançant el bus d'interfície perifèrica sèrie (SPI).""" from _typeshed import ReadableBuffer, WriteableBuffer from ..microbit import pin13, pin14, pin15, MicroBitDigitalPin -def init( - baudrate: int = 1000000, - bits: int = 8, - mode: int = 0, - sclk: MicroBitDigitalPin = pin13, - mosi: MicroBitDigitalPin = pin15, - miso: MicroBitDigitalPin = pin14, -) -> None: - """Initialize SPI communication. - - Example: ``spi.init()`` - - For correct communication, the parameters have to be the same on both communicating devices. - - :param baudrate: The speed of communication. - :param bits: The width in bits of each transfer. Currently only ``bits=8`` is supported. However, this may change in the future. - :param mode: Determines the combination of clock polarity and phase - `see online table `_. - :param sclk: sclk pin (default 13) - :param mosi: mosi pin (default 15) - :param miso: miso pin (default 14) - """ +def init(baudrate: int=1000000, bits: int=8, mode: int=0, sclk: MicroBitDigitalPin=pin13, mosi: MicroBitDigitalPin=pin15, miso: MicroBitDigitalPin=pin14) -> None: + """Inicialitzar la comunicació SPI. + +Example: ``spi.init()`` + +For correct communication, the parameters have to be the same on both communicating devices. + +:param baudrate: (Velocitat de bauds) La velocitat de comunicació. +:param bits: L'amplada en bits de cada transferència. Actualment només ``bits=8`` és acceptada . Tot i que això pot canviar en el futur +:param mode: Determina la combinació de polaritat i fase del rellotge: `consulta la taula en línia `_. +:param sclk: pin sclk (per defecte 13) +:param mosi: mosi pin (per defecte 15) +:param miso: miso pin (per defecte 14)""" ... -def read(nbytes: int, out: int = 0) -> bytes: - """Read at most ``nbytes`` while continuously writing the single byte given by ``out``. +def read(nbytes: int, out: int=0) -> bytes: + """Llegeix com a màxim ``nbytes`` mentre escriu contínuament l'únic byte donat per ``out``. (llegeix) - Example: ``spi.read(64)`` +Example: ``spi.read(64)`` - :param nbytes: Maximum number of bytes to read. - :param out: The byte value to write (default 0). - :return: The bytes read. - """ +:param nbytes: Nombre màxim de bytes per llegir. +:param out: El valor del byte a escriure (per defecte 0). +:return: The bytes read.""" ... def write(buffer: ReadableBuffer) -> None: - """Write bytes to the bus. + """Escriu bytes al bus. (escriu) - Example: ``spi.write(bytes([1, 2, 3]))`` +Example: ``spi.write(bytes([1, 2, 3]))`` - :param buffer: A buffer to read data from. - """ +:param buffer: (memòria intermèdia) Una memòria intermèdia per a llegir dades.""" ... def write_readinto(out: WriteableBuffer, in_: ReadableBuffer) -> None: - """Write the ``out`` buffer to the bus and read any response into the ``in_`` buffer. + """Escriu la memòria intermèdia ``out`` al bus i llegeix qualsevol resposta a la memòria intermèdia ``in_``. - Example: ``spi.write_readinto(out_buffer, in_buffer)`` +Example: ``spi.write_readinto(out_buffer, in_buffer)`` - The length of the buffers should be the same. The buffers can be the same object. +The length of the buffers should be the same. The buffers can be the same object. - :param out: The buffer to write any response to. - :param in_: The buffer to read data from. - """ - ... +:param out: La memòria intermèdia per a escriure qualsevol resposta. +:param in_: La memòria intermèdia per a llegir dades.""" + ... \ No newline at end of file diff --git a/lang/ca/typeshed/stdlib/microbit/uart.pyi b/lang/ca/typeshed/stdlib/microbit/uart.pyi index 2ab650f..7ff8baa 100644 --- a/lang/ca/typeshed/stdlib/microbit/uart.pyi +++ b/lang/ca/typeshed/stdlib/microbit/uart.pyi @@ -1,96 +1,79 @@ -"""Communicate with a device using a serial interface. -""" - +"""Comunica amb un dispositiu mitjançant una interfície sèrie.""" from _typeshed import WriteableBuffer from ..microbit import MicroBitDigitalPin from typing import Optional, Union - ODD: int -"""Odd parity""" - +"""Paritat senar (senar)""" EVEN: int -"""Even parity""" - -def init( - baudrate: int = 9600, - bits: int = 8, - parity: Optional[int] = None, - stop: int = 1, - tx: Optional[MicroBitDigitalPin] = None, - rx: Optional[MicroBitDigitalPin] = None, -) -> None: - """Initialize serial communication. - - Example: ``uart.init(115200, tx=pin0, rx=pin1)`` - - :param baudrate: The speed of communication. - :param bits: The size of bytes being transmitted. micro:bit only supports 8. - :param parity: How parity is checked, ``None``, ``uart.ODD`` or ``uart.EVEN``. - :param stop: The number of stop bits, has to be 1 for micro:bit. - :param tx: Transmitting pin. - :param rx: Receiving pin. - - 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. - - For more details see `the online documentation `_. - """ +"""Paritat parella (parell)""" + +def init(baudrate: int=9600, bits: int=8, parity: Optional[int]=None, stop: int=1, tx: Optional[MicroBitDigitalPin]=None, rx: Optional[MicroBitDigitalPin]=None) -> None: + """Inicialitzar la comunicació en sèrie. + +Example: ``uart.init(115200, tx=pin0, rx=pin1)`` + +:param baudrate: (Velocitat de bauds) La velocitat de comunicació. +:param bits: La mida dels bytes que es transmeten. micro:bit només n'admet 8. +:param parity: (paritat) Com es verifica la paritat, ``None``, ``uart.ODD`` o ``uart.EVEN``. +:param stop: (atura) El nombre de bits de parada ha de ser 1 per micro:bit. +:param tx: Pin transmissor. +:param rx: Receiving pin. + +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. + +For more details see `the online documentation `_.""" ... def any() -> bool: - """Check if any data is waiting. + """Verifica si hi ha alguna data esperant. - Example: ``uart.any()`` +Example: ``uart.any()`` - :return: ``True`` if any data is waiting, else ``False``. - """ +:return: ``True`` if any data is waiting, else ``False``.""" ... -def read(nbytes: Optional[int] = None) -> Optional[bytes]: - """Read bytes. +def read(nbytes: Optional[int]=None) -> Optional[bytes]: + """Llegeix bytes (llegeix) - Example: ``uart.read()`` +Example: ``uart.read()`` - :param nbytes: If ``nbytes`` is specified then read at most that many bytes, otherwise read as many bytes as possible - :return: A bytes object or ``None`` on timeout - """ +:param nbytes: Si s'especifica ``nbytes``, llegeix com a màxim tants bytes, en cas contrari llegeix tants bytes com sigui possible +:return: A bytes object or ``None`` on timeout""" ... -def readinto(buf: WriteableBuffer, nbytes: Optional[int] = None) -> Optional[int]: - """Read bytes into the ``buf``. +def readinto(buf: WriteableBuffer, nbytes: Optional[int]=None) -> Optional[int]: + """Llegeix bytes al ``buf``. - Example: ``uart.readinto(input_buffer)`` +Example: ``uart.readinto(input_buffer)`` - :param buf: The buffer to write to. - :param nbytes: If ``nbytes`` is specified then read at most that many bytes, otherwise read ``len(buf)`` bytes. - :return: number of bytes read and stored into ``buf`` or ``None`` on timeout. - """ +:param buf: La memòria intermèdia a on escriure. +:param nbytes: Si s'especifica ``nbytes``, llegeix com a màxim aquests bytes, en cas contrari llegeix ``len(buf)`` bytes. +:return: number of bytes read and stored into ``buf`` or ``None`` on timeout.""" ... def readline() -> Optional[bytes]: - """Read a line, ending in a newline character. + """Llegir una línia que acaba en un caràcter de nova línia. - Example: ``uart.readline()`` +Example: ``uart.readline()`` - :return: The line read or ``None`` on timeout. The newline character is included in the returned bytes. - """ +:return: The line read or ``None`` on timeout. The newline character is included in the returned bytes.""" ... def write(buf: Union[bytes, str]) -> Optional[int]: - """Write a buffer to the bus. + """Escriu una memòria intermèdia al bus (escriu) - Example: ``uart.write('hello world')`` +Example: ``uart.write('hello world')`` - :param buf: A bytes object or a string. - :return: The number of bytes written, or ``None`` on timeout. +:param buf: Un objecte bytes o una cadena. +:return: The number of bytes written, or ``None`` on timeout. - Examples:: +Examples:: - uart.write('hello world') - uart.write(b'hello world') - uart.write(bytes([1, 2, 3])) - """ - ... + uart.write('hello world') + uart.write(b'hello world') + uart.write(bytes([1, 2, 3]))""" + ... \ No newline at end of file diff --git a/lang/ca/typeshed/stdlib/micropython.pyi b/lang/ca/typeshed/stdlib/micropython.pyi index 7a6079f..2b2ca4a 100644 --- a/lang/ca/typeshed/stdlib/micropython.pyi +++ b/lang/ca/typeshed/stdlib/micropython.pyi @@ -1,144 +1,133 @@ -"""MicroPython internals.""" - +"""Components interns de MicroPython.""" from typing import Any, TypeVar, overload - -_T = TypeVar("_T") +_T = TypeVar('_T') def const(expr: _T) -> _T: - """Used to declare that the expression is a constant so that the compiler can - optimise it. + """S'utilitza per declarar que l'expressió és una constant perquè el compilador pugui +optimitzar-la. - The use of this function should be as follows:: +The use of this function should be as follows:: - from micropython import const - CONST_X = const(123) - CONST_Y = const(2 * CONST_X + 1) + from micropython import const + CONST_X = const(123) + CONST_Y = const(2 * CONST_X + 1) - Constants declared this way are still accessible as global variables from - outside the module they are declared in. On the other hand, if a constant - begins with an underscore then it is hidden, it is not available as a - global variable, and does not take up any memory during execution. +Constants declared this way are still accessible as global variables from +outside the module they are declared in. On the other hand, if a constant +begins with an underscore then it is hidden, it is not available as a +global variable, and does not take up any memory during execution. - :param expr: A constant expression. - """ +:param expr: Una expressió constant""" ... @overload def opt_level() -> int: - """Get the current optimisation level for the compilation of scripts. + """Obté el nivell d'optimització actual per a la compilació d'scripts. - Example: ``micropython.opt_level()`` +Example: ``micropython.opt_level()`` - The optimisation level controls the following compilation features: +The optimisation level controls the following compilation features: - - Assertions: at level 0 assertion statements are enabled and compiled - into the bytecode; at levels 1 and higher assertions are not compiled. +- Assertions: at level 0 assertion statements are enabled and compiled + into the bytecode; at levels 1 and higher assertions are not compiled. - - Built-in ``__debug__`` variable: at level 0 this variable expands to - True; at levels 1 and higher it expands to False. +- Built-in ``__debug__`` variable: at level 0 this variable expands to + True; at levels 1 and higher it expands to False. - - Source-code line numbers: at levels 0, 1 and 2 source-code line number - are stored along with the bytecode so that exceptions can report the - line number they occurred at; at levels 3 and higher line numbers are - not stored. +- Source-code line numbers: at levels 0, 1 and 2 source-code line number + are stored along with the bytecode so that exceptions can report the + line number they occurred at; at levels 3 and higher line numbers are + not stored. - :return: An integer representing the current level. - """ +:return: An integer representing the current level.""" ... @overload def opt_level(level: int) -> None: - """Sets the optimisation level for subsequent compilation of scripts. + """Estableix el nivell d'optimització per a la compilació posterior dels scripts. - Example: ``micropython.opt_level(1)`` +Example: ``micropython.opt_level(1)`` - The optimisation level controls the following compilation features: +The optimisation level controls the following compilation features: - - Assertions: at level 0 assertion statements are enabled and compiled - into the bytecode; at levels 1 and higher assertions are not compiled. +- Assertions: at level 0 assertion statements are enabled and compiled + into the bytecode; at levels 1 and higher assertions are not compiled. - - Built-in ``__debug__`` variable: at level 0 this variable expands to - True; at levels 1 and higher it expands to False. +- Built-in ``__debug__`` variable: at level 0 this variable expands to + True; at levels 1 and higher it expands to False. - - Source-code line numbers: at levels 0, 1 and 2 source-code line number - are stored along with the bytecode so that exceptions can report the - line number they occurred at; at levels 3 and higher line numbers are - not stored. +- Source-code line numbers: at levels 0, 1 and 2 source-code line number + are stored along with the bytecode so that exceptions can report the + line number they occurred at; at levels 3 and higher line numbers are + not stored. - The default optimisation level is usually level 0. +The default optimisation level is usually level 0. - :param level: An integer optimisation level. - """ +:param level: Un nivell d'optimització enter.""" ... -def mem_info(verbose: Any = None) -> None: - """Print information about currently used memory. +def mem_info(verbose: Any=None) -> None: + """Imprimeix informació sobre la memòria utilitzada actualment. (informació de la memòria) - Example: ``micropython.mem_info()`` +Example: ``micropython.mem_info()`` - :param verbose: If the ``verbose`` argument is given then extra information is printed. - """ +:param verbose: Si es dona l'argument ``verbose``, s'imprimeix informació addicional.""" ... -def qstr_info(verbose: Any = None) -> None: - """Print information about currently interned strings. +def qstr_info(verbose: Any=None) -> None: + """Imprimeix informació sobre les cadenes internades actualment. - Example: ``micropython.qstr_info()`` +Example: ``micropython.qstr_info()`` - :param verbose: If the ``verbose`` argument is given then extra information is printed. +:param verbose: Si es dona l'argument ``verbose``, s'imprimeix informació addicional. - The information that is printed is implementation dependent, but currently - includes the number of interned strings and the amount of RAM they use. In - verbose mode it prints out the names of all RAM-interned strings. - """ +The information that is printed is implementation dependent, but currently +includes the number of interned strings and the amount of RAM they use. In +verbose mode it prints out the names of all RAM-interned strings.""" ... def stack_use() -> int: - """Return an integer representing the current amount of stack that is being - used. + """Retorna un nombre enter que representa la quantitat actual de pila que està sent +utilitzada. - Example: ``micropython.stack_use()`` +Example: ``micropython.stack_use()`` - The absolute value of this is not particularly useful, rather it - should be used to compute differences in stack usage at different points. +The absolute value of this is not particularly useful, rather it +should be used to compute differences in stack usage at different points. - :return: An integer representing current stack use. - """ +:return: An integer representing current stack use.""" ... def heap_lock() -> None: - """Lock the heap. + """Bloqueja el munt. - Example: ``micropython.heap_lock()`` +Example: ``micropython.heap_lock()`` - When locked no memory allocation can occur and a ``MemoryError`` will be - raised if any heap allocation is attempted. - """ +When locked no memory allocation can occur and a ``MemoryError`` will be +raised if any heap allocation is attempted.""" ... def heap_unlock() -> None: - """Unlock the heap. + """Desbloqueja el munt. - Example: ``micropython.heap_unlock()`` +Example: ``micropython.heap_unlock()`` - When locked no memory allocation can occur and a ``MemoryError`` will be - raised if any heap allocation is attempted. - """ +When locked no memory allocation can occur and a ``MemoryError`` will be +raised if any heap allocation is attempted.""" ... def kbd_intr(chr: int) -> None: - """Set the character that will raise a ``KeyboardInterrupt`` exception. + """Estableix el caràcter que generarà una excepció ``KeyboardInterrupt``. - Example: ``micropython.kbd_intr(-1)`` +Example: ``micropython.kbd_intr(-1)`` - :param chr: Character code to raise the interrupt or -1 to disable capture of Ctrl-C. +:param chr: Codi de caràcter per augmentar la interrupció o -1 per desactivar la captura de Ctrl-C. - By default this is set to 3 during script execution, corresponding to Ctrl-C. - Passing -1 to this function will disable capture of Ctrl-C, and passing 3 - will restore it. +By default this is set to 3 during script execution, corresponding to Ctrl-C. +Passing -1 to this function will disable capture of Ctrl-C, and passing 3 +will restore it. - This function can be used to prevent the capturing of Ctrl-C on the - incoming stream of characters that is usually used for the REPL, in case - that stream is used for other purposes. - """ - ... +This function can be used to prevent the capturing of Ctrl-C on the +incoming stream of characters that is usually used for the REPL, in case +that stream is used for other purposes.""" + ... \ No newline at end of file diff --git a/lang/ca/typeshed/stdlib/music.pyi b/lang/ca/typeshed/stdlib/music.pyi index 5f4778b..b748d9f 100644 --- a/lang/ca/typeshed/stdlib/music.pyi +++ b/lang/ca/typeshed/stdlib/music.pyi @@ -1,167 +1,128 @@ -"""Create and play melodies. -""" +"""Crea i toca melodies. (música)""" from typing import Optional, Tuple, Union, List - from .microbit import MicroBitDigitalPin, pin0 - DADADADUM: Tuple[str, ...] -"""Melody: the opening to Beethoven’s 5th Symphony in C minor.""" - +"""Melodia: l'obertura de la cinquena simfonia de Beethoven en Do menor.""" ENTERTAINER: Tuple[str, ...] -"""Melody: the opening fragment of Scott Joplin’s Ragtime classic “The Entertainer”.""" - +"""Melodia: el fragment inicial del clàssic Ragtime de Scott Joplin "The Entertainer".""" PRELUDE: Tuple[str, ...] -"""Melody: the opening of the first Prelude in C Major of J.S.Bach’s 48 Preludes and Fugues.""" - +"""Melodia: obertura del primer Preludi en Do Major dels 48 Preludis i Fugues de J.S. Bach. (preludi)""" ODE: Tuple[str, ...] -"""Melody: the “Ode to Joy” theme from Beethoven’s 9th Symphony in D minor.""" - +"""Melodia: el tema "Oda a l'alegria" de la 9a simfonia en Re menor de Beethoven. (oda)""" NYAN: Tuple[str, ...] -"""Melody: the Nyan Cat theme (http://www.nyan.cat/). +"""Melodia: el tema Nyan Cat (http://www.nyan.cat/). The composer is unknown. This is fair use for educational porpoises (as they say in New York).""" - RINGTONE: Tuple[str, ...] -"""Melody: something that sounds like a mobile phone ringtone. +"""Melodia: quelcom que sona com un to de trucada de telèfon mòbil. (to de trucada) To be used to indicate an incoming message. """ - FUNK: Tuple[str, ...] -"""Melody: a funky bass line for secret agents and criminal masterminds.""" - +"""Melodia: una línia de baix funky per a agents secrets i cervells criminals.""" BLUES: Tuple[str, ...] -"""Melody: a boogie-woogie 12-bar blues walking bass.""" - +"""Melodia: un blues walking bass boogie-woogie de dotze compassos.""" BIRTHDAY: Tuple[str, ...] -"""Melody: “Happy Birthday to You…” +"""Melodia: “Feliç aniversari…” (aniversari) For copyright status see: http://www.bbc.co.uk/news/world-us-canada-34332853 """ - WEDDING: Tuple[str, ...] -"""Melody: the bridal chorus from Wagner’s opera “Lohengrin”.""" - +"""Melodia: el cor nupcial de l'òpera Lohengrin de Wagner. (casament)""" FUNERAL: Tuple[str, ...] -"""Melody: the “funeral march” otherwise known as Frédéric Chopin’s Piano Sonata No. 2 in B♭ minor, Op. 35.""" - +"""Melodia: la “marxa fúnebre” com es coneix la Sonata per a piano No 2. en Si bemoll menor Op. 35 de Frédéric Chopin .""" PUNCHLINE: Tuple[str, ...] -"""Melody: a fun fragment that signifies a joke has been made.""" - +"""Melodia: un fragment divertit que significa que s'ha fet una broma.""" PYTHON: Tuple[str, ...] -"""Melody: John Philip Sousa’s march “Liberty Bell” aka, the theme for “Monty Python’s Flying Circus” (after which the Python programming language is named).""" - +"""Melodia: la marxa de John Philip Sousa "Liberty Bell", també conegut com, el tema de "Monty Python's Flying Circus" (a partir de la qual s'anomena el llenguatge de programació Python).""" BADDY: Tuple[str, ...] -"""Melody: silent movie era entrance of a baddy.""" - +"""Melodia: entrada d'un dolent a l'era del cinema mut. (dolent)""" CHASE: Tuple[str, ...] -"""Melody: silent movie era chase scene.""" - +"""Melodia: escena de persecució de l'era del cinema mut. (persecució)""" BA_DING: Tuple[str, ...] -"""Melody: a short signal to indicate something has happened.""" - +"""Melodia: senyal breu per indicar que alguna cosa ha passat.""" WAWAWAWAA: Tuple[str, ...] -"""Melody: a very sad trombone.""" - +"""Melodia: un trombó molt trist.""" JUMP_UP: Tuple[str, ...] -"""Melody: for use in a game, indicating upward movement.""" - +"""Melodia: per utilitzar-se en un joc, indicant moviment cap amunt. (saltar cap amunt)""" JUMP_DOWN: Tuple[str, ...] -"""Melody: for use in a game, indicating downward movement.""" - +"""Melodia: per utilitzar en un joc, que indica moviment cap avall. (saltar cap avall)""" POWER_UP: Tuple[str, ...] -"""Melody: a fanfare to indicate an achievement unlocked.""" - +"""Melodia: una fanfàrria per indicar un assoliment desbloquejat. (engegar)""" POWER_DOWN: Tuple[str, ...] -"""Melody: a sad fanfare to indicate an achievement lost.""" +"""Melodia: una trista fanfàrria per indicar un assoliment perdut. (apagar)""" -def set_tempo(ticks: int = 4, bpm: int = 120) -> None: - """Sets the approximate tempo for playback. +def set_tempo(ticks: int=4, bpm: int=120) -> None: + """Estableix el tempo aproximat per la reproducció. - Example: ``music.set_tempo(bpm=120)`` +Example: ``music.set_tempo(bpm=120)`` - :param ticks: The number of ticks constituting a beat. - :param bpm: An integer determining how many beats per minute. +:param ticks: El nombre de tics que constitueixen un ritme. +:param bpm: Un nombre enter determinant quantes pulsacions per minut. - Suggested default values allow the following useful behaviour: +Suggested default values allow the following useful behaviour: - - music.set_tempo() – reset the tempo to default of ticks = 4, bpm = 120 - - music.set_tempo(ticks=8) – change the “definition” of a beat - - music.set_tempo(bpm=180) – just change the tempo +- music.set_tempo() – reset the tempo to default of ticks = 4, bpm = 120 +- music.set_tempo(ticks=8) – change the “definition” of a beat +- music.set_tempo(bpm=180) – just change the tempo - To work out the length of a tick in milliseconds is very simple arithmetic: - 60000/bpm/ticks_per_beat. For the default values that’s - 60000/120/4 = 125 milliseconds or 1 beat = 500 milliseconds. - """ +To work out the length of a tick in milliseconds is very simple arithmetic: +60000/bpm/ticks_per_beat. For the default values that’s +60000/120/4 = 125 milliseconds or 1 beat = 500 milliseconds.""" ... def get_tempo() -> Tuple[int, int]: - """Gets the current tempo as a tuple of integers: ``(ticks, bpm)``. + """Obté el tempo actual com una tupla d'enters:``(ticks, bpm)``. (obté el tempo) - Example: ``ticks, beats = music.get_tempo()`` +Example: ``ticks, beats = music.get_tempo()`` - :return: The temp as a tuple with two integer values, the ticks then the beats per minute. - """ +:return: The temp as a tuple with two integer values, the ticks then the beats per minute.""" ... -def play( - music: Union[str, List[str], Tuple[str, ...]], - pin: Optional[MicroBitDigitalPin] = pin0, - wait: bool = True, - loop: bool = False, -) -> None: - """Plays music. +def play(music: Union[str, List[str], Tuple[str, ...]], pin: Optional[MicroBitDigitalPin]=pin0, wait: bool=True, loop: bool=False) -> None: + """Tocar música - Example: ``music.play(music.NYAN)`` +Example: ``music.play(music.NYAN)`` - :param music: music specified in `a special notation `_ - :param pin: the output pin for use with an external speaker (default ``pin0``), ``None`` for no sound. - :param wait: If ``wait`` is set to ``True``, this function is blocking. - :param loop: If ``loop`` is set to ``True``, the tune repeats until ``stop`` is called or the blocking call is interrupted. +:param music: (música) música especificada en `una notació especial `_ +:param pin: el pin de sortida per utilitzar-lo amb un altaveu extern (``pin0`` per defecte), ``None`` per no fer so. +:param wait: (espera) Si ``wait`` s'estableix en ``True``, aquesta funció està bloquejant. +:param loop: (bucle) Si el ``loop`` s'estableix en ``True``, la melodia es repeteix fins que es crida ``stop`` o s'interromp la trucada de bloqueig. - Many built-in melodies are defined in this module. - """ +Many built-in melodies are defined in this module.""" ... -def pitch( - frequency: int, - duration: int = -1, - pin: Optional[MicroBitDigitalPin] = pin0, - wait: bool = True, -) -> None: - """Play a note. +def pitch(frequency: int, duration: int=-1, pin: Optional[MicroBitDigitalPin]=pin0, wait: bool=True) -> None: + """Toca una nota. (altura del to) - Example: ``music.pitch(185, 1000)`` +Example: ``music.pitch(185, 1000)`` - :param frequency: An integer frequency - :param duration: A millisecond duration. If negative then sound is continuous until the next call or a call to ``stop``. - :param pin: Optional output pin (default ``pin0``). - :param wait: If ``wait`` is set to ``True``, this function is blocking. +:param frequency: (freqüència) Una freqüència de nombre enter +:param duration: (Durada - duració) Una duració d'un mil·lisegon. Si és negativa, el so és continu fins a la nova crida o una crida a ``stop``. +:param pin: Pin de sortida opcional (``pin0`` per defecte). +:param wait: (espera) Si ``wait`` s'estableix en ``True``, aquesta funció està bloquejant. - For example, if the frequency is set to 440 and the length to - 1000 then we hear a standard concert A for one second. +For example, if the frequency is set to 440 and the length to +1000 then we hear a standard concert A for one second. - You can only play one pitch on one pin at any one time. - """ +You can only play one pitch on one pin at any one time.""" ... -def stop(pin: Optional[MicroBitDigitalPin] = pin0) -> None: - """Stops all music playback on the built-in speaker and any pin outputting sound. +def stop(pin: Optional[MicroBitDigitalPin]=pin0) -> None: + """Atura tota la reproducció de música a l'altaveu integrat i qualsevol so de sortida de pin. (atura) - Example: ``music.stop()`` +Example: ``music.stop()`` - :param pin: An optional argument can be provided to specify a pin, e.g. ``music.stop(pin1)``. - """ +:param pin: Es pot proporcionar un argument opcional per especificar un pin, per exemple ``music.stop(pin1)``.""" def reset() -> None: - """Resets ticks, bpm, duration and octave to their default values. + """Restableix els tics, ppm, duració i octava al seu valor per defecte. (reiniciar) - Example: ``music.reset()`` +Example: ``music.reset()`` - Values: - - ``ticks = 4`` - - ``bpm = 120`` - - ``duration = 4`` - - ``octave = 4`` - """ - ... +Values: +- ``ticks = 4`` +- ``bpm = 120`` +- ``duration = 4`` +- ``octave = 4``""" + ... \ No newline at end of file diff --git a/lang/ca/typeshed/stdlib/neopixel.pyi b/lang/ca/typeshed/stdlib/neopixel.pyi index 2d5a749..ec85e74 100644 --- a/lang/ca/typeshed/stdlib/neopixel.pyi +++ b/lang/ca/typeshed/stdlib/neopixel.pyi @@ -1,82 +1,81 @@ -"""Individually addressable RGB and RGBW LED strips. -""" +"""Cintes LED RGB i RGBW adreçables individualment.""" from .microbit import MicroBitDigitalPin from typing import Tuple class NeoPixel: - def __init__(self, pin: MicroBitDigitalPin, n: int, bpp: int = 3) -> None: - """Initialise a new strip of neopixel LEDs controlled via a pin. - Example: ``np = neopixel.NeoPixel(pin0, 8)`` + def __init__(self, pin: MicroBitDigitalPin, n: int, bpp: int=3) -> None: + """Inicialitza una nova tira de LED de neopixel controlada mitjançant un pin. - To support RGBW neopixels, a third argument can be passed to - ``NeoPixel`` to indicate the number of bytes per pixel (``bpp``). - For RGBW, this is is 4 rather than the default of 3 for RGB and GRB. +Example: ``np = neopixel.NeoPixel(pin0, 8)`` - Each pixel is addressed by a position (starting from 0). Neopixels are - given RGB (red, green, blue) / RGBW (red, green, blue, white) values - between 0-255 as a tuple. For example, in RGB, ``(255,255,255)`` is - white. In RGBW, ``(255,255,255,0)`` or ``(0,0,0,255)`` is white. +To support RGBW neopixels, a third argument can be passed to +``NeoPixel`` to indicate the number of bytes per pixel (``bpp``). +For RGBW, this is is 4 rather than the default of 3 for RGB and GRB. - See `the online docs `_ for warnings and other advice. +Each pixel is addressed by a position (starting from 0). Neopixels are +given RGB (red, green, blue) / RGBW (red, green, blue, white) values +between 0-255 as a tuple. For example, in RGB, ``(255,255,255)`` is +white. In RGBW, ``(255,255,255,0)`` or ``(0,0,0,255)`` is white. - :param pin: The pin controlling the neopixel strip. - :param n: The number of neopixels in the strip. - :param bpp: Bytes per pixel. For RGBW neopixel support, pass 4 rather than the default of 3 for RGB and GRB. - """ +See `the online docs `_ for warnings and other advice. + +:param pin: El pin que controla la tira de neopíxels. +:param n: El nombre de neopíxels de la tira. +:param bpp: Bytes per píxel. Per al suport del neopixel RGBW , passa 4 en lloc dels 3 per defecte per a RGB i GRB.""" ... + def clear(self) -> None: - """Clear all the pixels. + """Esborra tots els píxels. - Example: ``np.clear()`` - """ +Example: ``np.clear()``""" ... + def show(self) -> None: - """Show the pixels. + """mostra els píxels. - Example: ``np.show()`` +Example: ``np.show()`` - Must be called for any updates to become visible. - """ +Must be called for any updates to become visible.""" ... + def write(self) -> None: - """Show the pixels (micro:bit V2 only). + """Mostra els píxels (només micro:bit V2) (escriu) - Example: ``np.write()`` +Example: ``np.write()`` - Must be called for any updates to become visible. +Must be called for any updates to become visible. - Equivalent to ``show``. - """ +Equivalent to ``show``.""" ... + def fill(self, colour: Tuple[int, ...]) -> None: - """Colour all pixels a given RGB/RGBW value (micro:bit V2 only). + """Acoloreix tots els píxels amb un valor RGB/RGBW determinat (només micro:bit V2). (omple) - Example: ``np.fill((0, 0, 255))`` +Example: ``np.fill((0, 0, 255))`` - :param colour: A tuple of the same length as the number of bytes per pixel (bpp). +:param colour: (color) Una tupla de la mateixa longitud que el nombre de bytes per píxel (bpp). - Use in conjunction with ``show()`` to update the neopixels. - """ +Use in conjunction with ``show()`` to update the neopixels.""" ... + def __setitem__(self, key: int, value: Tuple[int, ...]) -> None: - """Set a pixel colour. + """Estableix un color de píxel. - Example: ``np[0] = (255, 0, 0)`` +Example: ``np[0] = (255, 0, 0)`` + +:param key: El nombre de píxels. +:param value: (valor) El color.""" - :param key: The pixel number. - :param value: The colour. - """ def __getitem__(self, key: int) -> Tuple[int, ...]: - """Get a pixel colour. + """Obté un color de píxel. + +Example: ``r, g, b = np[0]`` - Example: ``r, g, b = np[0]`` +:param key: El nombre de píxels. +:return: The colour tuple.""" - :param key: The pixel number. - :return: The colour tuple. - """ def __len__(self) -> int: - """Get length of this pixel strip. + """Obté la longitud d'aquesta cinta de píxels. - Example: ``len(np)`` - """ +Example: ``len(np)``""" \ No newline at end of file diff --git a/lang/ca/typeshed/stdlib/os.pyi b/lang/ca/typeshed/stdlib/os.pyi index 2f2db77..53b62c0 100644 --- a/lang/ca/typeshed/stdlib/os.pyi +++ b/lang/ca/typeshed/stdlib/os.pyi @@ -1,73 +1,63 @@ -"""Access the file system. -""" - +"""Accedeix al sistema de fitxers.""" from typing import Tuple from typing import List def listdir() -> List[str]: - """List files. + """Llista dels fitxers. - Example: ``os.listdir()`` +Example: ``os.listdir()`` - :return: A list of the names of all the files contained within the local - persistent on-device file system. - """ +:return: A list of the names of all the files contained within the local +persistent on-device file system.""" ... def remove(filename: str) -> None: - """Remove (delete) a file. + """Eliminar (suprimir) un fitxer. (eliminar) - Example: ``os.remove('data.txt')`` +Example: ``os.remove('data.txt')`` - :param filename: The file to delete. +:param filename: (nom del fitxer) El fitxer a suprimir. - If the file does not exist an ``OSError`` exception will occur. - """ +If the file does not exist an ``OSError`` exception will occur.""" ... def size(filename: str) -> int: - """Returns the size of a file. + """Retorna la mida d'un fitxer (mida) - Example: ``os.size('data.txt')`` +Example: ``os.size('data.txt')`` - :param filename: The file - :return: The size in bytes. +:param filename: (nom del fitxer) El fitxer +:return: The size in bytes. - If the file does not exist an ``OSError`` exception will occur. - """ +If the file does not exist an ``OSError`` exception will occur.""" class uname_result(Tuple[str, str, str, str, str]): - """Result of ``os.uname()``""" + """Resultat de ``os.uname()``""" sysname: str - """Operating system name.""" - + """Nom del sistema operatiu.""" nodename: str - """Name of machine on network (implementation-defined).""" - + """Nom de la màquina a la xarxa (definida per la implementació).""" release: str - """Operating system release.""" - + """Versió del sistema operatiu. (versió)""" version: str - """Operating system version.""" - + """Versió del sistema operatiu. (versió)""" machine: str - """Hardware identifier.""" + """Identificador del maquinari. (màquina)""" def uname() -> uname_result: - """Returns information identifying the current operating system. + """Retorna informació que identifica el sistema operatiu actual. - Example: ``os.uname()`` +Example: ``os.uname()`` - The return value is an object with five attributes: +The return value is an object with five attributes: - - ``sysname`` - operating system name - - ``nodename`` - name of machine on network (implementation-defined) - - ``release`` - operating system release - - ``version`` - operating system version - - ``machine`` - hardware identifier +- ``sysname`` - operating system name +- ``nodename`` - name of machine on network (implementation-defined) +- ``release`` - operating system release +- ``version`` - operating system version +- ``machine`` - hardware identifier - There is no underlying operating system in MicroPython. As a result the - information returned by the ``uname`` function is mostly useful for - versioning details. - """ - ... +There is no underlying operating system in MicroPython. As a result the +information returned by the ``uname`` function is mostly useful for +versioning details.""" + ... \ No newline at end of file diff --git a/lang/ca/typeshed/stdlib/radio.pyi b/lang/ca/typeshed/stdlib/radio.pyi index 8dd0267..8b7bc98 100644 --- a/lang/ca/typeshed/stdlib/radio.pyi +++ b/lang/ca/typeshed/stdlib/radio.pyi @@ -1,152 +1,130 @@ -"""Communicate between micro:bits with the built-in radio. -""" - +"""Comunicar-se entre micro:bits amb la ràdio integrada. (ràdio)""" from _typeshed import WriteableBuffer from typing import Optional, Tuple - RATE_1MBIT: int -"""Constant used to indicate a throughput of 1 MBit a second.""" - +"""La constant utilitzada per indicar un rendiment d'1 Mbit per segon. (velocitat de transmissió 1mbit)""" RATE_2MBIT: int -"""Constant used to indicate a throughput of 2 MBit a second.""" +"""La constant utilitzada per indicar un rendiment de 2 Mbit per segon. (velocitat de transmissió 2mbit)""" def on() -> None: - """Turns the radio on. + """Encén la ràdio. - Example: ``radio.on()`` +Example: ``radio.on()`` - This needs to be explicitly called since the radio draws power and takes - up memory that you may otherwise need. - """ +This needs to be explicitly called since the radio draws power and takes +up memory that you may otherwise need.""" ... def off() -> None: - """Turns off the radio, saving power and memory. + """Apaga la ràdio, estalviant energia i memòria. - Example: ``radio.off()`` - """ +Example: ``radio.off()``""" ... -def config( - length: int = 32, - queue: int = 3, - channel: int = 7, - power: int = 6, - address: int = 0x75626974, - group: int = 0, - data_rate: int = RATE_1MBIT, -) -> None: - """Configures the radio. - - Example: ``radio.config(group=42)`` - - The default configuration is suitable for most use. - - :param length: (default=32) defines the maximum length, in bytes, of a message sent via the radio. - It can be up to 251 bytes long (254 - 3 bytes for S0, LENGTH and S1 preamble). - :param queue: (default=3) specifies the number of messages that can be stored on the incoming message queue. - If there are no spaces left on the queue for incoming messages, then the incoming message is dropped. - :param channel: (default=7) an integer value from 0 to 83 (inclusive) that defines an arbitrary "channel" to which the radio is tuned. - Messages will be sent via this channel and only messages received via this channel will be put onto the incoming message queue. Each step is 1MHz wide, based at 2400MHz. - :param power: (default=6) is an integer value from 0 to 7 (inclusive) to indicate the strength of signal used when broadcasting a message. - The higher the value the stronger the signal, but the more power is consumed by the device. The numbering translates to positions in the following list of dBm (decibel milliwatt) values: -30, -20, -16, -12, -8, -4, 0, 4. - :param address: (default=0x75626974) an arbitrary name, expressed as a 32-bit address, that's used to filter incoming packets at the hardware level, keeping only those that match the address you set. - The default used by other micro:bit related platforms is the default setting used here. - :param group: (default=0) an 8-bit value (0-255) used with the ``address`` when filtering messages. - Conceptually, "address" is like a house/office address and "group" is like the person at that address to which you want to send your message. - :param data_rate: (default=``radio.RATE_1MBIT``) indicates the speed at which data throughput takes place. - Can be one of the following constants defined in the ``radio`` module: ``RATE_250KBIT``, ``RATE_1MBIT`` or ``RATE_2MBIT``. - - If ``config`` is not called then the defaults described above are assumed. - """ +def config(length: int=32, queue: int=3, channel: int=7, power: int=6, address: int=1969383796, group: int=0, data_rate: int=RATE_1MBIT) -> None: + """Configura la ràdio. + +Example: ``radio.config(group=42)`` + +The default configuration is suitable for most use. + +:param length: (llargada) (per defecte=32) defineix la longitud màxima, en bytes, d'un missatge enviat a través de la ràdio. +Pot tenir una longitud de fins a 251 bytes (254 - 3 bytes per al preàmbul S0, LENGTH i S1). +:param queue: (cua) (per defecte=3) especifica el nombre de missatges que es poden emmagatzemar a la cua de missatges entrants. +Si no queden espais a la cua per als missatges entrants, s'elimina el missatge entrant. +:param channel: (canal) (per defecte=7) un valor enter de 0 a 83 (inclosos) que defineix un "canal" arbitrari al qual està sintonitzada la ràdio. +Els missatges s'enviaran a través d'aquest canal i només els missatges rebuts per aquest canal es posaran a la cua de missatges entrants. Cada pas té una amplada d'1MHz, basat en 2400MHz. +:param power: (per defecte=6) és un valor enter de 0 a 7 (inclosos) per indicar la intensitat del senyal utilitzat quan s'emet un missatge. +Com més alt sigui el valor, més fort és el senyal, però més potència consumeix el dispositiu. La numeració es tradueix en posicions a la llista següent de valors en dBm (decibels mil·liwatts): -30, -20, -16, -12, -8, -4, 0, 4. +:param address: (adreça) (per defecte=0x75626974) un nom arbitrari, expressat com una adreça de 32 bits, que s'utilitza per filtrar els paquets entrants a nivell de maquinari, conservant només els que coincideixen amb l'adreça que has establert. +La configuració predeterminada utilitzada per altres plataformes relacionades amb micro:bit és la configuració predeterminada que s'utilitza aquí. +:param group: (grup) (per defecte=0) un valor de 8 bits (0-255) utilitzat amb l'``address`` (adreça) en filtrar missatges. +Conceptualment, "adreça" és com una adreça de casa/oficina i "grup" és com la persona a aquesta adreça a la qual vols enviar el teu missatge. +:param data_rate: (velocitat de dades) (per defecte=``radio.RATE_1MBIT``) indica la velocitat a la qual es produeix la transmissió de les dades. +Pot ser una de les constants següents definides al mòdul ``radio``: ``RATE_250KBIT``, ``RATE_1MBIT`` o ``RATE_2MBIT``. + +If ``config`` is not called then the defaults described above are assumed.""" ... def reset() -> None: - """Reset the settings to their default values. + """Restableix la configuració als seus valors predeterminats. (reiniciar) - Example: ``radio.reset()`` +Example: ``radio.reset()`` - The defaults as as per the ``config`` function above. - """ +The defaults as as per the ``config`` function above.""" ... def send_bytes(message: bytes) -> None: - """Sends a message containing bytes. + """Envia un missatge que conté bytes. (enviar bytes) - Example: ``radio.send_bytes(b'hello')`` +Example: ``radio.send_bytes(b'hello')`` - :param message: The bytes to send. - """ +:param message: (missatge) Els bytes a ser enviats.""" ... def receive_bytes() -> Optional[bytes]: - """Receive the next incoming message on the message queue. + """Rebràs el següent missatge entrant a la cua de missatges. (rebre bytes) - Example: ``radio.receive_bytes()`` +Example: ``radio.receive_bytes()`` - :return: The message bytes if any, otherwise ``None``. - """ +:return: The message bytes if any, otherwise ``None``.""" ... def receive_bytes_into(buffer: WriteableBuffer) -> Optional[int]: - """Copy the next incoming message on the message queue into a buffer. + """Copia el següent missatge entrant de la cua de missatges a una memòria intermèdia. (rebre bytes a) - Example: ``radio.receive_bytes_info(buffer)`` +Example: ``radio.receive_bytes_info(buffer)`` - :param buffer: The target buffer. The message is truncated if larger than the buffer. - :return: ``None`` if there are no pending messages, otherwise it returns the length of the message (which might be more than the length of the buffer). - """ +:param buffer: (memòria intermèdia) La memòria intermèdia objectiu. El missatge es trunca si és més gran que la memòria intermèdia. +:return: ``None`` if there are no pending messages, otherwise it returns the length of the message (which might be more than the length of the buffer).""" ... def send(message: str) -> None: - """Sends a message string. + """Envia una cadena de missatge. (envia) - Example: ``radio.send('hello')`` +Example: ``radio.send('hello')`` - This is the equivalent of ``radio.send_bytes(bytes(message, 'utf8'))`` but with ``b'\x01\x00\x01'`` - prepended to the front (to make it compatible with other platforms that target the micro:bit). +This is the equivalent of ``radio.send_bytes(bytes(message, 'utf8'))`` but with ``b'\x01\x00\x01'`` +prepended to the front (to make it compatible with other platforms that target the micro:bit). - :param message: The string to send. - """ +:param message: (missatge) La cadena a enviar.""" ... def receive() -> Optional[str]: - """Works in exactly the same way as ``receive_bytes`` but returns whatever was sent. + """Funciona exactament de la mateixa manera que ``receive_bytes`` però retorna el que s'ha enviat. - Example: ``radio.receive()`` +Example: ``radio.receive()`` - Equivalent to ``str(receive_bytes(), 'utf8')`` but with a check that the the first - three bytes are ``b'\x01\x00\x01'`` (to make it compatible with other platforms that - may target the micro:bit). +Equivalent to ``str(receive_bytes(), 'utf8')`` but with a check that the the first +three bytes are ``b'\x01\x00\x01'`` (to make it compatible with other platforms that +may target the micro:bit). - :return: The message with the prepended bytes stripped and converted to a string. +:return: The message with the prepended bytes stripped and converted to a string. - A ``ValueError`` exception is raised if conversion to string fails. - """ +A ``ValueError`` exception is raised if conversion to string fails.""" ... def receive_full() -> Optional[Tuple[bytes, int, int]]: - """Returns a tuple containing three values representing the next incoming message on the message queue. + """Retorna una tupla que conté tres valors que representen el següent missatge entrant a la cua de missatges. (rebre ple) - Example: ``radio.receive_full()`` +Example: ``radio.receive_full()`` - If there are no pending messages then ``None`` is returned. +If there are no pending messages then ``None`` is returned. - The three values in the tuple represent: +The three values in the tuple represent: - - the next incoming message on the message queue as bytes. - - the RSSI (signal strength): a value between 0 (strongest) and -255 (weakest) as measured in dBm. - - a microsecond timestamp: the value returned by ``time.ticks_us()`` when the message was received. +- the next incoming message on the message queue as bytes. +- the RSSI (signal strength): a value between 0 (strongest) and -255 (weakest) as measured in dBm. +- a microsecond timestamp: the value returned by ``time.ticks_us()`` when the message was received. - For example:: +For example:: - details = radio.receive_full() - if details: - msg, rssi, timestamp = details + details = radio.receive_full() + if details: + msg, rssi, timestamp = details - This function is useful for providing information needed for triangulation - and/or trilateration with other micro:bit devices. +This function is useful for providing information needed for triangulation +and/or trilateration with other micro:bit devices. - :return: ``None`` if there is no message, otherwise a tuple of length three with the bytes, strength and timestamp values. - """ - ... +:return: ``None`` if there is no message, otherwise a tuple of length three with the bytes, strength and timestamp values.""" + ... \ No newline at end of file diff --git a/lang/ca/typeshed/stdlib/random.pyi b/lang/ca/typeshed/stdlib/random.pyi index a2c2ef3..34ccc2b 100644 --- a/lang/ca/typeshed/stdlib/random.pyi +++ b/lang/ca/typeshed/stdlib/random.pyi @@ -1,93 +1,81 @@ -"""Generate random numbers. -""" +"""Genera nombres aleatoris. (aleatori)""" from typing import TypeVar, Sequence, Union, overload def getrandbits(n: int) -> int: - """Generate an integer with ``n`` random bits. + """Genera un nombre enter amb ``n`` bits aleatoris. - Example: ``random.getrandbits(1)`` +Example: ``random.getrandbits(1)`` - :param n: A value between 1-30 (inclusive). - """ +:param n: Un valor entre 1-30 (inclusiu).""" ... def seed(n: int) -> None: - """Initialize the random number generator. + """Inicialitza el generador de nombres aleatoris. (llavor) - Example: ``random.seed(0)`` +Example: ``random.seed(0)`` - :param n: The integer seed +:param n: The integer seed - This will give you reproducibly deterministic randomness from a given starting - state (``n``). - """ +This will give you reproducibly deterministic randomness from a given starting +state (``n``).""" ... def randint(a: int, b: int) -> int: - """Choose a random integer between ``a`` and ``b`` inclusive. + """Tria un nombre enter aleatori entre ``a`` i ``b`` inclosos. - Example: ``random.randint(0, 9)`` +Example: ``random.randint(0, 9)`` - :param a: Start value for the range (inclusive) - :param b: End value for the range (inclusive) +:param a: Valor inicial de l'interval (inclòs) +:param b: Valor final de l'interval (inclòs) - Alias for ``randrange(a, b + 1)``. - """ +Alias for ``randrange(a, b + 1)``.""" ... @overload def randrange(stop: int) -> int: - """Choose a randomly selected integer between zero and up to (but not - including) ``stop``. + """Tria un nombre enter seleccionat aleatòriament entre zero i fins a (però no +inclòs) ``stop``. - Example: ``random.randrange(10)`` +Example: ``random.randrange(10)`` - :param stop: End value for the range (exclusive) - """ +:param stop: (atura) Valor final de l'interval (exclòs)""" ... @overload -def randrange(start: int, stop: int, step: int = 1) -> int: - """ - Choose a randomly selected element from ``range(start, stop, step)``. +def randrange(start: int, stop: int, step: int=1) -> int: + """Tria un element seleccionat aleatòriament de ``range(start, stop, step)``. - Example: ``random.randrange(0, 10)`` +Example: ``random.randrange(0, 10)`` - :param start: The start of the range (inclusive) - :param stop: The end of the range (exclusive) - :param step: The step. - """ +:param start: L'inici de l'interval (inclòs) +:param stop: (atura) El final de l'interval (exclusiu) +:param step: El pas.""" ... - -_T = TypeVar("_T") +_T = TypeVar('_T') def choice(seq: Sequence[_T]) -> _T: - """Choose a random element from the non-empty sequence ``seq``. + """Tria un element aleatori de la seqüència no buida ``seq``. - Example: ``random.choice([Image.HAPPY, Image.SAD])`` +Example: ``random.choice([Image.HAPPY, Image.SAD])`` - :param seq: A sequence. +:param seq: Una seqüència. - If ``seq`` is empty, raises ``IndexError``. - """ +If ``seq`` is empty, raises ``IndexError``.""" ... def random() -> float: - """Generate a random floating point number in the range [0.0, 1.0). + """Genera un nombre aleatori de coma flotant en l'interval [0.0, 1.0). (aleatori) - Example: ``random.random()`` +Example: ``random.random()`` - :return: The random floating point number - """ +:return: The random floating point number""" ... def uniform(a: float, b: float) -> float: - """ - Return a random floating point number between ``a`` and ``b`` inclusive. + """Retorna un nombre de coma flotant aleatori entre ``a`` i ``b`` inclosos. (uniforme) - Example: ``random.uniform(0, 9)`` +Example: ``random.uniform(0, 9)`` - :param a: Start value for the range (inclusive) - :param b: End value for the range (inclusive) - """ - ... +:param a: Valor inicial de l'interval (inclòs) +:param b: Valor final de l'interval (inclòs)""" + ... \ No newline at end of file diff --git a/lang/ca/typeshed/stdlib/speech.pyi b/lang/ca/typeshed/stdlib/speech.pyi index 349d188..2e29ea3 100644 --- a/lang/ca/typeshed/stdlib/speech.pyi +++ b/lang/ca/typeshed/stdlib/speech.pyi @@ -1,106 +1,79 @@ -"""Make the micro:bit talk, sing and make other speech like sounds. -""" - +"""Fes que la micro:bit parli, canti i fer altres expressions com els sons.""" from typing import Optional from .microbit import MicroBitDigitalPin, pin0 def translate(words: str) -> str: - """Translate English words to phonemes. + """Tradueix paraules angleses a fonemes. (tradueix) - Example: ``speech.translate('hello world')`` +Example: ``speech.translate('hello world')`` - :param words: A string of English words. - :return: A string containing a best guess at the appropriate phonemes to pronounce. - The output is generated from this `text to phoneme translation table `_. +:param words: (paraules) Una cadena de paraules angleses. +:return: A string containing a best guess at the appropriate phonemes to pronounce. +The output is generated from this `text to phoneme translation table `_. - This function should be used to generate a first approximation of phonemes - that can be further hand-edited to improve accuracy, inflection and - emphasis. +This function should be used to generate a first approximation of phonemes +that can be further hand-edited to improve accuracy, inflection and +emphasis. - See `the online documentation `_ for detailed information. - """ +See `the online documentation `_ for detailed information.""" ... -def pronounce( - phonemes: str, - pitch: int = 64, - speed: int = 72, - mouth: int = 128, - throat: int = 128, - pin: Optional[MicroBitDigitalPin] = pin0, -) -> None: - """Pronounce phonemes. - - Example: ``speech.pronounce(' /HEHLOW WERLD')`` - - :param phonemes: The string of phonemes to pronounce - :param pitch: A number representing the pitch of the voice - :param speed: A number representing the speed of the voice - :param mouth: A number representing the mouth of the voice - :param throat: A number representing the throat of the voice - :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. - If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. - - Override the optional pitch, speed, mouth and throat settings to change the - timbre (quality) of the voice. - - See `the online documentation `_ for detailed information. - """ - ... +def pronounce(phonemes: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: Optional[MicroBitDigitalPin]=pin0) -> None: + """Pronuncia fonemes. (pronuncia) + +Example: ``speech.pronounce(' /HEHLOW WERLD')`` + +:param phonemes: (fonemes) La cadena de fonemes a pronunciar +:param pitch: (to) Un nombre que representa la freqüència de la veu +:param speed: (velocitat) Un nombre que representa la velocitat de la veu +:param mouth: (boca) Un nombre que representa la boca de la veu +:param throat: Un nombre que representa la gola de la veu +:param pin: L'argument opcional per especificar el pin de sortida es pot utilitzar per anul·lar el valor predeterminat de ``pin0``. +Si no vols que es reprodueixi cap so en els pins, podts utilitzar ``pin=None``. Només micro:bit V2. -def say( - words: str, - pitch: int = 64, - speed: int = 72, - mouth: int = 128, - throat: int = 128, - pin: MicroBitDigitalPin = pin0, -) -> None: - """Say English words. - - Example: ``speech.say('hello world')`` - - :param words: The string of words to say. - :param pitch: A number representing the pitch of the voice - :param speed: A number representing the speed of the voice - :param mouth: A number representing the mouth of the voice - :param throat: A number representing the throat of the voice - :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. - If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. - - The result is semi-accurate for English. Override the optional pitch, speed, - mouth and throat settings to change the timbre (quality) of the voice. - - This is a short-hand equivalent of: - ``speech.pronounce(speech.translate(words))`` - - See `the online documentation `_ for detailed information. - """ +Override the optional pitch, speed, mouth and throat settings to change the +timbre (quality) of the voice. + +See `the online documentation `_ for detailed information.""" ... -def sing( - phonemes: str, - pitch: int = 64, - speed: int = 72, - mouth: int = 128, - throat: int = 128, - pin: MicroBitDigitalPin = pin0, -) -> None: - """Sing phonemes. - - Example: ``speech.sing(' /HEHLOW WERLD')`` - - :param phonemes: The string of words to sing. - :param pitch: A number representing the pitch of the voice - :param speed: A number representing the speed of the voice - :param mouth: A number representing the mouth of the voice - :param throat: A number representing the throat of the voice - :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. - If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. - - Override the optional pitch, speed, mouth and throat settings to change - the timbre (quality) of the voice. - - See `the online documentation `_ for detailed information. - """ +def say(words: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: MicroBitDigitalPin=pin0) -> None: + """Digues paraules en anglès. + +Example: ``speech.say('hello world')`` + +:param words: (paraules) La cadena de paraules a dir. +:param pitch: (to) Un nombre que representa la freqüència de la veu +:param speed: (velocitat) Un nombre que representa la velocitat de la veu +:param mouth: (boca) Un nombre que representa la boca de la veu +:param throat: Un nombre que representa la gola de la veu +:param pin: L'argument opcional per especificar el pin de sortida es pot utilitzar per anul·lar el valor predeterminat del ``pin0``. +Si no vols que es reprodueixi cap so en els pins, pots utilitzar ``pin=None``. Només micro:bit V2. + +The result is semi-accurate for English. Override the optional pitch, speed, +mouth and throat settings to change the timbre (quality) of the voice. + +This is a short-hand equivalent of: +``speech.pronounce(speech.translate(words))`` + +See `the online documentation `_ for detailed information.""" ... + +def sing(phonemes: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: MicroBitDigitalPin=pin0) -> None: + """Cantar fonemes. + +Example: ``speech.sing(' /HEHLOW WERLD')`` + +:param phonemes: (fonemes) La cadena de paraules a cantar. +:param pitch: (to) Un nombre que representa la freqüència de la veu +:param speed: (velocitat) Un nombre que representa la velocitat de la veu +:param mouth: (boca) Un nombre que representa la boca de la veu +:param throat: Un nombre que representa la gola de la veu +:param pin: L'argument opcional per especificar el pin de sortida es pot utilitzar per anul·lar el valor predeterminat de ``pin0``. +Si no vols que es reprodueixi cap so en els pins, podts utilitzar ``pin=None``. Només micro:bit V2. + +Override the optional pitch, speed, mouth and throat settings to change +the timbre (quality) of the voice. + +See `the online documentation `_ for detailed information.""" + ... \ No newline at end of file diff --git a/lang/ca/typeshed/stdlib/struct.pyi b/lang/ca/typeshed/stdlib/struct.pyi index 53b3e0b..75c7eee 100644 --- a/lang/ca/typeshed/stdlib/struct.pyi +++ b/lang/ca/typeshed/stdlib/struct.pyi @@ -1,65 +1,56 @@ -"""Pack and unpack primitive data types. -""" - +"""Empaquetar i desempaquetar tipus de dades primitius.""" from _typeshed import ReadableBuffer, WriteableBuffer from typing import Any, Tuple, Union def calcsize(fmt: str) -> int: - """Get the number of bytes needed to store the given ``fmt``. + """Obté el nombre de bytes necessaris per emmagatzemar el ``fmt`` donat. - Example: ``struct.calcsize('hf')`` +Example: ``struct.calcsize('hf')`` - :param fmt: A format string. - :return The number of bytes needed to store such a value. - """ +:param fmt: Una cadena de format. +:return The number of bytes needed to store such a value.""" ... def pack(fmt: str, v1: Any, *vn: Any) -> bytes: - """Pack values according to a format string. + """Empaqueta els valors segons una cadena de format. - Example: ``struct.pack('hf', 1, 3.1415)`` +Example: ``struct.pack('hf', 1, 3.1415)`` - :param fmt: The format string. - :param v1: The first value. - :param *vn: The remaining values. - :return A bytes object encoding the values. - """ +:param fmt: La cadena de format. +:param v1: El primer valor. +:param *vn: La resta de valors. +:return A bytes object encoding the values.""" ... -def pack_into( - fmt: str, buffer: WriteableBuffer, offset: int, v1: Any, *vn: Any -) -> None: - """Pack values according to a format string. +def pack_into(fmt: str, buffer: WriteableBuffer, offset: int, v1: Any, *vn: Any) -> None: + """Empaqueta els valors segons una cadena de format. - Example: ``struct.pack_info('hf', buffer, 1, 3.1415)`` +Example: ``struct.pack_info('hf', buffer, 1, 3.1415)`` - :param fmt: The format string. - :param buffer: The target buffer to write into. - :param offset: The offset into the buffer. May be negative to count from the end of the buffer. - :param v1: The first value. - :param *vn: The remaining values. - """ +:param fmt: La cadena de format. +:param buffer: (memòria intermèdia) La memòria intermèdia de destinació on escriure. +:param offset: El desplaçament a la memòria intermèdia. Pot ser negatiu per comptar des del final de la memòria intermèdia. +:param v1: El primer valor. +:param *vn: La resta de valors.""" ... def unpack(fmt: str, data: ReadableBuffer) -> Tuple[Any, ...]: - """Unpack data according to a format string. + """Desempaqueta les dades segons una cadena de format. - Example: ``v1, v2 = struct.unpack('hf', buffer)`` +Example: ``v1, v2 = struct.unpack('hf', buffer)`` - :param fmt: The format string. - :param data: The data. - :return: A tuple of the unpacked values. - """ +:param fmt: La cadena de format. +:param data: Les dades. +:return: A tuple of the unpacked values.""" ... -def unpack_from(fmt: str, buffer: ReadableBuffer, offset: int = 0) -> Tuple: - """Unpack data from a buffer according to a format string. +def unpack_from(fmt: str, buffer: ReadableBuffer, offset: int=0) -> Tuple: + """Desempaqueta les dades d'una memòria intermèdia segons una cadena de format. (desempaqueta des de) - Example: ``v1, v2 = struct.unpack_from('hf', buffer)`` +Example: ``v1, v2 = struct.unpack_from('hf', buffer)`` - :param fmt: The format string. - :param buffer: The source buffer to read from. - :param offset: The offset into the buffer. May be negative to count from the end of the buffer. - :return: A tuple of the unpacked values. - """ - ... +:param fmt: La cadena de format. +:param buffer: (memòria intermèdia) La memòria intermèdia d'origen d'on llegir. +:param offset: El desplaçament a la memòria intermèdia. Pot ser negatiu per comptar des del final de la memòria intermèdia. +:return: A tuple of the unpacked values.""" + ... \ No newline at end of file diff --git a/lang/ca/typeshed/stdlib/sys.pyi b/lang/ca/typeshed/stdlib/sys.pyi index 320bac9..aea4bac 100644 --- a/lang/ca/typeshed/stdlib/sys.pyi +++ b/lang/ca/typeshed/stdlib/sys.pyi @@ -1,43 +1,36 @@ -"""System specific functions""" - +"""Funcions específiques del sistema""" from typing import Any, Dict, List, NoReturn, TextIO, Tuple -def exit(retval: object = ...) -> NoReturn: - """Terminate current program with a given exit code. +def exit(retval: object=...) -> NoReturn: + """Finalitza el programa actual amb un codi de sortida determinat. - Example: ``sys.exit(1)`` +Example: ``sys.exit(1)`` - This function raises a ``SystemExit`` exception. If an argument is given, its - value given as an argument to ``SystemExit``. +This function raises a ``SystemExit`` exception. If an argument is given, its +value given as an argument to ``SystemExit``. - :param retval: The exit code or message. - """ +:param retval: El codi o missatge de sortida.""" ... def print_exception(exc: Exception) -> None: - """ - Print an exception with a traceback. - - Example: ``sys.print_exception(e)`` + """Imprimeix una excepció amb un rastreig. - :param exc: The exception to print +Example: ``sys.print_exception(e)`` - This is simplified version of a function which appears in the - ``traceback`` module in CPython. - """ +:param exc: L'excepció a imprimir +This is simplified version of a function which appears in the +``traceback`` module in CPython.""" argv: List[str] -"""A mutable list of arguments the current program was started with.""" - +"""Una llista mutable d'arguments amb què s'ha iniciat el programa actual.""" byteorder: str -"""The byte order of the system (``"little"`` or ``"big"``).""" +"""L'ordre dels bytes del sistema (``"little"`` o ``"big"``).""" class _implementation: name: str version: Tuple[int, int, int] - implementation: _implementation -"""Object with information about the current Python implementation. +"""Objecte amb informació sobre la implementació actual de Python. (implementació) For MicroPython, it has following attributes: @@ -51,13 +44,12 @@ minimal ports). CPython mandates more attributes for this object, but the actual useful bare minimum is implemented in MicroPython. """ - maxsize: int """ -Maximum value which a native integer type can hold on the current platform, -or maximum value representable by MicroPython integer type, if it's smaller -than platform max value (that is the case for MicroPython ports without -long int support). +Valor màxim que pot tenir un tipus d'enter natiu a la plataforma actual, +o valor màxim representable pel tipus d'enter MicroPython, si és més petit +que el valor màxim de la plataforma (és el cas dels ports MicroPython sense +suport d'enter llarg - long int support). This attribute is useful for detecting "bitness" of a platform (32-bit vs 64-bit, etc.). It's recommended to not compare this attribute to some @@ -77,17 +69,14 @@ value directly, but instead count number of bits in it:: # (e.g. 31) due to peculiarities described above, so use "> 16", # "> 32", "> 64" style of comparisons. """ - modules: Dict[str, Any] -"""Dictionary of loaded modules. +"""Diccionari de mòduls carregats. (mòduls) On some ports, it may not include builtin modules.""" - path: List[str] -"""A mutable list of directories to search for imported modules.""" - +"""Una llista mutable de directoris per cercar mòduls importats.""" platform: str -"""The platform that MicroPython is running on. +"""La plataforma en què s'executa MicroPython. (plataforma) For OS/RTOS ports, this is usually an identifier of the OS, e.g. ``"linux"``. For baremetal ports it is an identifier of a board, e.g. ``"pyboard"`` for @@ -97,13 +86,11 @@ distinguish one board from another. If you need to check whether your program runs on MicroPython (vs other Python implementation), use ``sys.implementation`` instead. """ - version: str -"""Python language version that this implementation conforms to, as a string.""" - +"""Versió del llenguatge Python a la qual s'ajusta aquesta implementació, com a cadena. (versió)""" version_info: Tuple[int, int, int] -"""Python language version that this implementation conforms to, as a tuple of ints. +"""Versió del llenguatge Python a la qual s'ajusta aquesta implementació, com una tupla d'enters. (informació de la versió) Only the first three version numbers (major, minor, micro) are supported and they can be referenced only by index, not by name. -""" +""" \ No newline at end of file diff --git a/lang/ca/typeshed/stdlib/time.pyi b/lang/ca/typeshed/stdlib/time.pyi index 598c483..c1e151f 100644 --- a/lang/ca/typeshed/stdlib/time.pyi +++ b/lang/ca/typeshed/stdlib/time.pyi @@ -1,132 +1,116 @@ -"""Measure time and add delays to programs. -""" - +"""Mesura el temps i afegeix retards als programes. (temps)""" from typing import Union def sleep(seconds: Union[int, float]) -> None: - """ - Delay a number of seconds. + """Retarda uns segons. (dormir) - Example: ``time.sleep(1)`` +Example: ``time.sleep(1)`` - :param seconds: The number of seconds to sleep for. - Use a floating-point number to sleep for a fractional number of seconds. - """ +:param seconds: (segons) El nombre de segons per posar en pausa. +Utilitza un nombre de coma flotant per posar en pausa durant una fracció de segons.""" ... def sleep_ms(ms: int) -> None: - """ - Delay for given number of milliseconds. + """Retard per a un nombre determinat de mil·lisegons. (retard en mil·lisegons) - Example: ``time.sleep_ms(1_000_000)`` +Example: ``time.sleep_ms(1_000_000)`` - :param ms: The number of milliseconds delay (>= 0). - """ +:param ms: El nombre de mil·lisegons de retard (>= 0).""" ... def sleep_us(us: int) -> None: - """ - Delay for given number of microseconds. + """Retard per a un nombre determinat de microsegons. - Example: ``time.sleep_us(1000)`` +Example: ``time.sleep_us(1000)`` - :param us: The number of microseconds delay (>= 0). - """ +:param us: El nombre de microsegons de retard (>= 0).""" ... def ticks_ms() -> int: - """ - Get an increasing, millisecond counter with an arbitrary reference point, - that wraps around after some value. + """Obté un comptador creixent de mil·lisegons amb un punt de referència arbitrari, +que es desborda després d'algun valor. (tics mil·lisegons) - Example: ``time.ticks_ms()`` +Example: ``time.ticks_ms()`` - :return: The counter value in milliseconds. - """ +:return: The counter value in milliseconds.""" ... def ticks_us() -> int: - """ - Get an increasing, microsecond counter with an arbitrary reference point, - that wraps around after some value. + """Obté un comptador creixent de microsegons amb un punt de referència arbitrari, +que es desborda després d'algun valor. (tics microsegons) - Example: ``time.ticks_us()`` +Example: ``time.ticks_us()`` - :return: The counter value in microseconds. - """ +:return: The counter value in microseconds.""" ... def ticks_add(ticks: int, delta: int) -> int: - """ - Offset ticks value by a given number, which can be either positive or - negative. + """Afegeix al valor de tics un desplaçament determinat, que pot ser positiu o +negatiu. (tics compensa) - Example: ``time.ticks_add(time.ticks_ms(), 200)`` +Example: ``time.ticks_add(time.ticks_ms(), 200)`` - Given a ticks value, this function allows to calculate ticks - value delta ticks before or after it, following modular-arithmetic - definition of tick values. +Given a ticks value, this function allows to calculate ticks +value delta ticks before or after it, following modular-arithmetic +definition of tick values. - :param ticks: A ticks value - :param delta: An integer offset +:param ticks: Un valor de tics +:param delta: Un desplaçament enter - Example:: +Example:: - # Find out what ticks value there was 100ms ago - print(ticks_add(time.ticks_ms(), -100)) + # Find out what ticks value there was 100ms ago + print(ticks_add(time.ticks_ms(), -100)) - # Calculate deadline for operation and test for it - deadline = ticks_add(time.ticks_ms(), 200) - while ticks_diff(deadline, time.ticks_ms()) > 0: - do_a_little_of_something() + # Calculate deadline for operation and test for it + deadline = ticks_add(time.ticks_ms(), 200) + while ticks_diff(deadline, time.ticks_ms()) > 0: + do_a_little_of_something() - # Find out TICKS_MAX used by this port - print(ticks_add(0, -1)) - """ + # Find out TICKS_MAX used by this port + print(ticks_add(0, -1))""" ... def ticks_diff(ticks1: int, ticks2: int) -> int: - """ - Measure ticks difference between values returned from - ``time.ticks_ms()`` or ``ticks_us()``, as a signed value - which may wrap around. - - Example: ``time.ticks_diff(scheduled_time, now)`` - - :param ticks1: The value to subtract from - :param ticks2: The value to subtract - - The argument order is the same as for subtraction operator, - ``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. - - ``ticks_diff()`` is designed to accommodate various usage - patterns, among them: - - Polling with timeout. In this case, the order of events is known, and you - will deal only with positive results of :func:`time.ticks_diff()`:: - - # Wait for GPIO pin to be asserted, but at most 500us - start = time.ticks_us() - while pin.value() == 0: - if time.ticks_diff(time.ticks_us(), start) > 500: - raise TimeoutError - - - Scheduling events. In this case, :func:`time.ticks_diff()` result may be - negative if an event is overdue:: - - # This code snippet is not optimized - now = time.ticks_ms() - scheduled_time = task.scheduled_time() - if ticks_diff(scheduled_time, now) > 0: - print("Too early, let's nap") - sleep_ms(ticks_diff(scheduled_time, now)) - task.run() - elif ticks_diff(scheduled_time, now) == 0: - print("Right at time!") - task.run() - elif ticks_diff(scheduled_time, now) < 0: - print("Oops, running late, tell task to run faster!") - task.run(run_faster=True) - """ - ... + """Mesura la diferència dels tics entre els valors retornats +``time.ticks_ms()`` o ``ticks_us()``, com a valor amb signe +que pot desbordar-se. + +Example: ``time.ticks_diff(scheduled_time, now)`` + +:param ticks1: El valor a restar de +:param ticks2: El valor a restar + +The argument order is the same as for subtraction operator, +``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. + +``ticks_diff()`` is designed to accommodate various usage +patterns, among them: + +Polling with timeout. In this case, the order of events is known, and you +will deal only with positive results of :func:`time.ticks_diff()`:: + + # Wait for GPIO pin to be asserted, but at most 500us + start = time.ticks_us() + while pin.value() == 0: + if time.ticks_diff(time.ticks_us(), start) > 500: + raise TimeoutError + + +Scheduling events. In this case, :func:`time.ticks_diff()` result may be +negative if an event is overdue:: + + # This code snippet is not optimized + now = time.ticks_ms() + scheduled_time = task.scheduled_time() + if ticks_diff(scheduled_time, now) > 0: + print("Too early, let's nap") + sleep_ms(ticks_diff(scheduled_time, now)) + task.run() + elif ticks_diff(scheduled_time, now) == 0: + print("Right at time!") + task.run() + elif ticks_diff(scheduled_time, now) < 0: + print("Oops, running late, tell task to run faster!") + task.run(run_faster=True)""" + ... \ No newline at end of file diff --git a/lang/de/typeshed/stdlib/gc.pyi b/lang/de/typeshed/stdlib/gc.pyi index 1370abf..0d8aee5 100644 --- a/lang/de/typeshed/stdlib/gc.pyi +++ b/lang/de/typeshed/stdlib/gc.pyi @@ -1,73 +1,68 @@ -"""Control the garbage collector""" - +"""Steuerung des Garbage Collectors""" from typing import overload def enable() -> None: - """Enable automatic garbage collection.""" + """Automatische Garbage Collection aktivieren.""" ... def disable() -> None: - """Disable automatic garbage collection. + """Automatische Garbage Collection deaktivieren. - Heap memory can still be allocated, - and garbage collection can still be initiated manually using ``gc.collect``.""" +Heap memory can still be allocated, +and garbage collection can still be initiated manually using ``gc.collect``.""" def collect() -> None: - """Run a garbage collection.""" + """Garbage Collection ausführen.""" ... def mem_alloc() -> int: - """Get the number of bytes of heap RAM that are allocated. + """Ermittelt die Anzahl der dem Heap-Speicher zugewiesen Bytes. - :return: The number of bytes allocated. +:return: The number of bytes allocated. - This function is MicroPython extension. - """ +This function is MicroPython extension.""" ... def mem_free() -> int: - """Get the number of bytes of available heap RAM, or -1 if this amount is not known. + """Gibt die Anzahl der Bytes des verfügbaren dynamischen Speichers zurück. -1 wird zurückgegeben, wenn dieser Wert unbekannt ist. - :return: The number of bytes free. +:return: The number of bytes free. - This function is MicroPython extension. - """ +This function is MicroPython extension.""" ... @overload def threshold() -> int: - """Query the additional GC allocation threshold. + """Den zusätzlichen GC-Zuteilungsschwellwert abfragen. - :return: The GC allocation threshold. +:return: The GC allocation threshold. - This function is a MicroPython extension. CPython has a similar - function - ``set_threshold()``, but due to different GC - implementations, its signature and semantics are different. - """ +This function is a MicroPython extension. CPython has a similar +function - ``set_threshold()``, but due to different GC +implementations, its signature and semantics are different.""" ... @overload def threshold(amount: int) -> None: - """Set the additional GC allocation threshold. - - Normally, a collection is triggered only when a new allocation - cannot be satisfied, i.e. on an out-of-memory (OOM) condition. - If this function is called, in addition to OOM, a collection - will be triggered each time after ``amount`` bytes have been - allocated (in total, since the previous time such an amount of bytes - have been allocated). ``amount`` is usually specified as less than the - full heap size, with the intention to trigger a collection earlier than when the - heap becomes exhausted, and in the hope that an early collection will prevent - excessive memory fragmentation. This is a heuristic measure, the effect - of which will vary from application to application, as well as - the optimal value of the ``amount`` parameter. - - A value of -1 means a disabled allocation threshold. - - This function is a MicroPython extension. CPython has a similar - function - ``set_threshold()``, but due to different GC - implementations, its signature and semantics are different. - - :param amount: The number of bytes after which a garbage collection should be triggered. - """ - ... + """Den zusätzlichen GC-Schwellenwert festlegen. + +Normally, a collection is triggered only when a new allocation +cannot be satisfied, i.e. on an out-of-memory (OOM) condition. +If this function is called, in addition to OOM, a collection +will be triggered each time after ``amount`` bytes have been +allocated (in total, since the previous time such an amount of bytes +have been allocated). ``amount`` is usually specified as less than the +full heap size, with the intention to trigger a collection earlier than when the +heap becomes exhausted, and in the hope that an early collection will prevent +excessive memory fragmentation. This is a heuristic measure, the effect +of which will vary from application to application, as well as +the optimal value of the ``amount`` parameter. + +A value of -1 means a disabled allocation threshold. + +This function is a MicroPython extension. CPython has a similar +function - ``set_threshold()``, but due to different GC +implementations, its signature and semantics are different. + +:param amount: Die Anzahl der Bytes, nach denen eine Garbage Collection ausgelöst werden soll.""" + ... \ No newline at end of file diff --git a/lang/de/typeshed/stdlib/log.pyi b/lang/de/typeshed/stdlib/log.pyi index c9870fa..24b39f8 100644 --- a/lang/de/typeshed/stdlib/log.pyi +++ b/lang/de/typeshed/stdlib/log.pyi @@ -1,104 +1,89 @@ -"""Log data to your micro:bit V2.""" - +"""Zeichne Daten auf deinem micro:bit V2 auf.""" from typing import Literal, Mapping, Optional, Union, overload - MILLISECONDS = 1 -"""Milliseconds timestamp format.""" - +"""Zeitstempelformat: Millisekunden (millisekunden)""" SECONDS = 10 -"""Seconds timestamp format.""" - +"""Zeitstempelformat: Sekunden (sekunden)""" MINUTES = 600 -"""Minutes timestamp format.""" - +"""Zeitstempelformat: Minuten (minuten)""" HOURS = 36000 -"""Hours timestamp format.""" - +"""Zeitstempelformat: Stunden (stunden)""" DAYS = 864000 -"""Days timestamp format.""" +"""Tage Zeitstempelformat.""" -def set_labels( - *labels: str, timestamp: Optional[Literal[1, 10, 36000, 864000]] = SECONDS -) -> None: - """Set up the log file header. +def set_labels(*labels: str, timestamp: Optional[Literal[1, 10, 36000, 864000]]=SECONDS) -> None: + """Den Logdatei-Header setzen (Beschriftungen festlegen) - Example: ``log.set_labels('X', 'Y', 'Z', timestamp=log.MINUTES)`` +Example: ``log.set_labels('X', 'Y', 'Z', timestamp=log.MINUTES)`` - Ideally this function should be called a single time, before any data is - logged, to configure the data table header once. +Ideally this function should be called a single time, before any data is +logged, to configure the data table header once. - If a log file already exists when the program starts, or if this function - is called multiple times, it will check the labels already defined in the - log file. If this function call contains any new labels not already - present, it will generate a new header row with the additional columns. +If a log file already exists when the program starts, or if this function +is called multiple times, it will check the labels already defined in the +log file. If this function call contains any new labels not already +present, it will generate a new header row with the additional columns. - By default the first column contains a timestamp for each row. The time - unit can be selected via the timestamp argument. +By default the first column contains a timestamp for each row. The time +unit can be selected via the timestamp argument. - :param *labels: Any number of positional arguments, each corresponding to an entry in the log header. - :param timestamp: Select the timestamp unit that will be automatically added as the first column in every row. Timestamp values can be one of ``log.MILLISECONDS``, ``log.SECONDS``, ``log.MINUTES``, ``log.HOURS``, ``log.DAYS`` or ``None`` to disable the timestamp. The default value is ``log.SECONDS``. - """ +:param *labels: Eine beliebige Anzahl von Positionsargumenten, die jeweils einem Eintrag in der Kopfzeile des Logs entsprechen. +:param timestamp: Wähle die Zeitstempel-Einheit, die automatisch als erste Spalte in jeder Zeile hinzugefügt wird. Der Zeitstempel kann einen der folgenden Werte annehmen: ``log.MILLISECONDS``, ``log.SECONDS``, ``log.MINUTES``, ``log.HOURS``, ``log.DAYS`` oder ``None``, um den Zeitstempel zu deaktivieren. Der Standardwert ist ``log.SECONDS``.""" ... @overload -def add( - data_dictionary: Optional[Mapping[str, Union[str, int, float]]], -) -> None: - """Add a data row to the log by passing a dictionary of headers and values. +def add(data_dictionary: Optional[Mapping[str, Union[str, int, float]]]) -> None: + """Füge dem Protokoll eine Datenzeile hinzu, indem du ein Dictionary mit Kopfzeileneinträgen und Werten übergibst. (hinzufügen) - Example: ``log.add({ 'temp': temperature() })`` +Example: ``log.add({ 'temp': temperature() })`` - Each call to this function adds a row to the log. +Each call to this function adds a row to the log. - New labels not previously specified via the set_labels function, or by a - previous call to this function, will trigger a new header entry to be added - to the log with the extra labels. +New labels not previously specified via the set_labels function, or by a +previous call to this function, will trigger a new header entry to be added +to the log with the extra labels. - Labels previously specified and not present in a call to this function will - be skipped with an empty value in the log row. +Labels previously specified and not present in a call to this function will +be skipped with an empty value in the log row. - :param data_dictionary: The data to log as a dictionary with a key for each header. - """ +:param data_dictionary: (daten wörterbuch) Die zu protokollierenden Daten in Form eines Dictionarys mit einem Schlüssel für jeden Kopfzeileneintrag.""" ... @overload def add(**kwargs: Union[str, int, float]) -> None: - """Add a data row to the log using keyword arguments. + """Füge dem Protokoll eine Datenzeile mit Schlüsselwörtern als Argumenten hinzu. (hinzufügen) - Example: ``log.add(temp=temperature())`` +Example: ``log.add(temp=temperature())`` - Each call to this function adds a row to the log. +Each call to this function adds a row to the log. - New labels not previously specified via the set_labels function, or by a - previous call to this function, will trigger a new header entry to be added - to the log with the extra labels. +New labels not previously specified via the set_labels function, or by a +previous call to this function, will trigger a new header entry to be added +to the log with the extra labels. - Labels previously specified and not present in a call to this function will - be skipped with an empty value in the log row. - """ +Labels previously specified and not present in a call to this function will +be skipped with an empty value in the log row.""" ... def delete(full=False): - """Deletes the contents of the log, including headers. + """Löscht den Inhalt des Protokolls, einschließlich der Kopfzeilen. (löschen) - Example: ``log.delete()`` +Example: ``log.delete()`` - To add the log headers again the ``set_labels`` function should to be called after this function. +To add the log headers again the ``set_labels`` function should to be called after this function. - There are two erase modes; “full” completely removes the data from the physical storage, - and “fast” invalidates the data without removing it. +There are two erase modes; “full” completely removes the data from the physical storage, +and “fast” invalidates the data without removing it. - :param full: ``True`` selects a “full” erase and ``False`` selects the “fast” erase method. - """ +:param full: (vollständig) Mit ``True`` wird ein " vollständiges" Löschen und mit ``False`` die "schnelle" Löschmethode gewählt.""" ... def set_mirroring(serial: bool): - """Configure mirroring of the data logging activity to the serial output. + """Richte die Spiegelung der Datenprotokollierung auf dem seriellen Ausgang ein. (spiegeln) - Example: ``log.set_mirroring(True)`` +Example: ``log.set_mirroring(True)`` - Serial mirroring is disabled by default. When enabled, it will print to serial each row logged into the log file. +Serial mirroring is disabled by default. When enabled, it will print to serial each row logged into the log file. - :param serial: ``True`` enables mirroring data to the serial output. - """ - ... +:param serial: (seriell) ``True`` aktiviert die Spiegelung von Daten auf dem seriellen Ausgang.""" + ... \ No newline at end of file diff --git a/lang/de/typeshed/stdlib/machine.pyi b/lang/de/typeshed/stdlib/machine.pyi index 2e82f5b..eda1989 100644 --- a/lang/de/typeshed/stdlib/machine.pyi +++ b/lang/de/typeshed/stdlib/machine.pyi @@ -1,97 +1,84 @@ -"""Low-level utilities. -""" +"""Low-Level-Utilities. (maschine)""" from typing import Any from .microbit import MicroBitDigitalPin def unique_id() -> bytes: - """Get a byte string with a unique identifier of a board. + """Liefert eine Byte-Zeichenkette mit einem eindeutigen Bezeichner für ein Board. (Eindeutige ID) - Example: ``machine.unique_id()`` +Example: ``machine.unique_id()`` - :return: An identifier that varies from one board instance to another. - """ +:return: An identifier that varies from one board instance to another.""" ... def reset() -> None: - """Reset the device in a manner similar to pushing the external RESET button. + """Setzt das Gerät zurück, als würde man die externe RESET-Taste drückt. (zurücksetzen) - Example: ``machine.reset()`` - """ +Example: ``machine.reset()``""" ... def freq() -> int: - """Get the CPU frequency in hertz. + """Ermittelt die Taktfrequenz der CPU in Hertz. - Example: ``machine.freq()`` +Example: ``machine.freq()`` - :return: The CPU frequency. - """ +:return: The CPU frequency.""" ... def disable_irq() -> Any: - """Disable interrupt requests. + """Deaktiviere Interrupt-Anforderungen. (IRQ deaktivieren) - Example: ``interrupt_state = machine.disable_irq()`` +Example: ``interrupt_state = machine.disable_irq()`` - :return: the previous IRQ state which should be considered an opaque value +:return: the previous IRQ state which should be considered an opaque value - The return value should be passed to the ``enable_irq`` function to restore - interrupts to their original state. - """ +The return value should be passed to the ``enable_irq`` function to restore +interrupts to their original state.""" ... def enable_irq(state: Any) -> None: - """Re-enable interrupt requests. + """Interrupt-Anfragen wieder aktivieren. (IRQ aktivieren) - Example: ``machine.enable_irq(interrupt_state)`` +Example: ``machine.enable_irq(interrupt_state)`` - :param state: The value that was returned from the most recent call to the ``disable_irq`` function. - """ +:param state: Der Wert, der beim letzten Aufruf der Funktion ``disable_irq`` zurückgegeben wurde.""" ... -def time_pulse_us( - pin: MicroBitDigitalPin, pulse_level: int, timeout_us: int = 1000000 -) -> int: - """Time a pulse on a pin. +def time_pulse_us(pin: MicroBitDigitalPin, pulse_level: int, timeout_us: int=1000000) -> int: + """Gibt die Dauer eines Impulses an einem Pin zurück. (zeitimpuls us) - Example: ``time_pulse_us(pin0, 1)`` +Example: ``time_pulse_us(pin0, 1)`` - If the current input value of the pin is different to ``pulse_level``, the - function first waits until the pin input becomes equal to - ``pulse_level``, then times the duration that the pin is equal to - ``pulse_level``. If the pin is already equal to ``pulse_level`` then timing - starts straight away. +If the current input value of the pin is different to ``pulse_level``, the +function first waits until the pin input becomes equal to +``pulse_level``, then times the duration that the pin is equal to +``pulse_level``. If the pin is already equal to ``pulse_level`` then timing +starts straight away. - :param pin: The pin to use - :param pulse_level: 0 to time a low pulse or 1 to time a high pulse - :param timeout_us: A microsecond timeout - :return: The duration of the pulse in microseconds, or -1 for a timeout waiting for the level to match ``pulse_level``, or -2 on timeout waiting for the pulse to end - """ +:param pin: Der zu verwendende Pin +:param pulse_level: (pulsstufe) 0, um einen Low-Impuls oder 1, um einen High-Impuls zu messen +:param timeout_us: Eine Verzögerung in Mikrosekunden +:return: The duration of the pulse in microseconds, or -1 for a timeout waiting for the level to match ``pulse_level``, or -2 on timeout waiting for the pulse to end""" ... class mem: - """The class for the ``mem8``, ``mem16`` and ``mem32`` memory views.""" + """Die Klasse für die ``mem8``, ``mem16`` und ``mem32`` Speicheranzeigen.""" def __getitem__(self, address: int) -> int: - """Access a value from memory. + """Greife auf einen Wert im Speicher zu. - :param address: The memory address. - :return: The value at that address as an integer. - """ +:param address: (adresse) Die Speicheradresse. +:return: The value at that address as an integer.""" ... + def __setitem__(self, address: int, value: int) -> None: - """Set a value at the given address. + """Setzt einen Wert an der angegebenen Adresse. - :param address: The memory address. - :param value: The integer value to set. - """ +:param address: (adresse) Die Speicheradresse. +:param value: (wert) Der zu setzende Integer-Wert.""" ... - mem8: mem -"""8-bit (byte) view of memory.""" - +"""8-Bit (Byte) Ansicht des Speichers.""" mem16: mem -"""16-bit view of memory.""" - +"""16-Bit (Byte) Ansicht des Speichers.""" mem32: mem -"""32-bit view of memory.""" +"""32-Bit (Byte) Ansicht des Speichers.""" \ No newline at end of file diff --git a/lang/de/typeshed/stdlib/math.pyi b/lang/de/typeshed/stdlib/math.pyi index f82d4de..574d825 100644 --- a/lang/de/typeshed/stdlib/math.pyi +++ b/lang/de/typeshed/stdlib/math.pyi @@ -1,273 +1,246 @@ -"""Mathematical functions. -""" - +"""Mathematische Funktionen.""" from typing import Tuple def acos(x: float) -> float: - """Calculate the inverse cosine. + """Berechnet den Arkuskosinus. - Example: ``math.acos(1)`` +Example: ``math.acos(1)`` - :param x: A number - :return: The inverse cosine of ``x`` - """ +:param x: Eine Zahl +:return: The inverse cosine of ``x``""" ... def asin(x: float) -> float: - """Calculate the inverse sine. + """Berechnet den Arkussinus. - Example: ``math.asin(0)`` +Example: ``math.asin(0)`` - :param x: A number - :return: The inverse sine of ``x`` - """ +:param x: Eine Zahl +:return: The inverse sine of ``x``""" ... def atan(x: float) -> float: - """Calculate the inverse tangent. + """Berechnet den Arkustangens. - Example: ``math.atan(0)`` +Example: ``math.atan(0)`` - :param x: A number - :return: The inverse tangent of ``x`` - """ +:param x: Eine Zahl +:return: The inverse tangent of ``x``""" ... def atan2(y: float, x: float) -> float: - """Calculate the principal value of the inverse tangent of ``y/x``. + """Berechnet den Hauptwert des Arkustangens von ``y/x``. - Example: ``math.atan2(0, -1)`` +Example: ``math.atan2(0, -1)`` - :param y: A number - :param x: A number - :return: The principal value of the inverse tangent of ``y/x`` - """ +:param y: Eine Zahl +:param x: Eine Zahl +:return: The principal value of the inverse tangent of ``y/x``""" ... def ceil(x: float) -> float: - """Round a number towards positive infinity. + """Rundet eine Zahl in Richtung positiver Unendlichkeit. - Example: ``math.ceil(0.1)`` +Example: ``math.ceil(0.1)`` - :param x: A number - :return: ``x`` rounded towards positive infinity. - """ +:param x: Eine Zahl +:return: ``x`` rounded towards positive infinity.""" ... def copysign(x: float, y: float) -> float: - """Calculate ``x`` with the sign of ``y``. + """Berechnet ``x`` mit dem Vorzeichen von ``y``. - Example: ``math.copysign(1, -1)`` +Example: ``math.copysign(1, -1)`` - :param x: A number - :param y: The source of the sign for the return value - :return: ``x`` with the sign of ``y`` - """ +:param x: Eine Zahl +:param y: Die Herkunft des Vorzeichens für den Rückgabewert +:return: ``x`` with the sign of ``y``""" ... def cos(x: float) -> float: - """Calculate the cosine of ``x``. + """Berechnet den Kosinus von ``x``. - Example: ``math.cos(0)`` +Example: ``math.cos(0)`` - :param x: A number - :return: The cosine of ``x`` - """ +:param x: Eine Zahl +:return: The cosine of ``x``""" ... def degrees(x: float) -> float: - """Convert radians to degrees. + """Wandelt Bogenmaß (Radiant) in Grad um. - Example: ``math.degrees(2 * math.pi)`` +Example: ``math.degrees(2 * math.pi)`` - :param x: A value in radians - :return: The value converted to degrees""" +:param x: Ein Wert in Radiant +:return: The value converted to degrees""" ... def exp(x: float) -> float: - """Calculate the exponential of ``x``. + """Berechnet den Exponentialwert von ``x``. - Example: ``math.exp(1)`` +Example: ``math.exp(1)`` - :param x: A number - :return: The exponential of ``x``. - """ +:param x: Eine Zahl +:return: The exponential of ``x``.""" ... def fabs(x: float) -> float: - """Return the absolute value of ``x``. + """Gibt den absoluten Wert von ``x`` zurück. - Example: ``math.fabs(-0.1)`` +Example: ``math.fabs(-0.1)`` - :param x: A number - :return: The absolute value of ``x`` - """ +:param x: Eine Zahl +:return: The absolute value of ``x``""" ... def floor(x: float) -> int: - """Round a number towards negative infinity. + """Rundet eine Zahl in Richtung negativer Unendlichkeit. - Example: ``math.floor(0.9)`` +Example: ``math.floor(0.9)`` - :param x: A number - :return: ``x`` rounded towards negative infinity. - """ +:param x: Eine Zahl +:return: ``x`` rounded towards negative infinity.""" ... def fmod(x: float, y: float) -> float: - """Calculate the remainder of ``x/y``. + """Berechnet den Rest von ``x/y``. - Example: ``math.fmod(10, 3)`` +Example: ``math.fmod(10, 3)`` - :param x: The numerator - :param y: The denominator - """ +:param x: Der Zähler +:param y: Der Nenner""" ... def frexp(x: float) -> Tuple[float, int]: - """Decomposes a floating-point number into its mantissa and exponent. + """Zerlegt eine Gleitkommazahl in ihre Mantisse und ihren Exponenten. - Example: ``mantissa, exponent = math.frexp(2)`` +Example: ``mantissa, exponent = math.frexp(2)`` - The returned value is the tuple ``(m, e)`` such that ``x == m * 2**e`` - exactly. If ``x == 0`` then the function returns ``(0.0, 0)``, otherwise - the relation ``0.5 <= abs(m) < 1`` holds. +The returned value is the tuple ``(m, e)`` such that ``x == m * 2**e`` +exactly. If ``x == 0`` then the function returns ``(0.0, 0)``, otherwise +the relation ``0.5 <= abs(m) < 1`` holds. - :param x: A floating-point number - :return: A tuple of length two containing its mantissa then exponent - """ +:param x: Eine Fließkommazahl +:return: A tuple of length two containing its mantissa then exponent""" ... def isfinite(x: float) -> bool: - """Check if a value is finite. + """Überprüft, ob ein Wert endlich ist. - Example: ``math.isfinite(float('inf'))`` +Example: ``math.isfinite(float('inf'))`` - :param x: A number. - :return: ``True`` if ``x`` is finite, ``False`` otherwise. - """ +:param x: Eine Zahl. +:return: ``True`` if ``x`` is finite, ``False`` otherwise.""" ... def isinf(x: float) -> bool: - """Check if a value is infinite. + """Überprüft, ob ein Wert unendlich ist. - Example: ``math.isinf(float('-inf'))`` +Example: ``math.isinf(float('-inf'))`` - :param x: A number. - :return: ``True`` if ``x`` is infinite, ``False`` otherwise. - """ +:param x: Eine Zahl. +:return: ``True`` if ``x`` is infinite, ``False`` otherwise.""" ... def isnan(x: float) -> bool: - """Check if a value is not-a-number (NaN). + """Prüft, ob ein Wert keine Zahl (NaN bzw. Not A Number) ist. - Example: ``math.isnan(float('nan'))`` +Example: ``math.isnan(float('nan'))`` - :param x: A number - :return: ``True`` if ``x`` is not-a-number (NaN), ``False`` otherwise.""" +:param x: Eine Zahl +:return: ``True`` if ``x`` is not-a-number (NaN), ``False`` otherwise.""" ... def ldexp(x: float, exp: int) -> float: - """Calculate ``x * (2**exp)``. + """Berechnet ``x * (2**exp)``. - Example: ``math.ldexp(0.5, 2)`` +Example: ``math.ldexp(0.5, 2)`` - :param x: A number - :param exp: Integer exponent - :return: ``x * (2**exp)`` - """ +:param x: Eine Zahl +:param exp: Ganzzahl-Exponent +:return: ``x * (2**exp)``""" ... -def log(x: float, base: float = e) -> float: - """Calculate the logarithm of ``x`` to the given base (defaults to natural logorithm). +def log(x: float, base: float=e) -> float: + """Berechnet den Logarithmus von ``x`` zur angegebenen Basis (standardmäßig den natürlichen Logarithmus). - Example: ``math.log(math.e)`` +Example: ``math.log(math.e)`` - With one argument, return the natural logarithm of x (to base e). +With one argument, return the natural logarithm of x (to base e). - With two arguments, return the logarithm of x to the given base, calculated as ``log(x)/log(base)``. +With two arguments, return the logarithm of x to the given base, calculated as ``log(x)/log(base)``. - :param x: A number - :param base: The base to use - :return: The natural logarithm of ``x`` - """ +:param x: Eine Zahl +:param base: Die zu verwendende Basis +:return: The natural logarithm of ``x``""" ... def modf(x: float) -> Tuple[float, float]: - """Calculate the fractional and integral parts of ``x``. + """Berechnet die gebrochenen und ganzzahligen Teile von ``x``. - Example: ``fractional, integral = math.modf(1.5)`` +Example: ``fractional, integral = math.modf(1.5)`` - :param x: A number - :return: A tuple of two floats representing the fractional then integral parts of ``x``. +:param x: Eine Zahl +:return: A tuple of two floats representing the fractional then integral parts of ``x``. - Both the fractional and integral values have the same sign as ``x``. - """ +Both the fractional and integral values have the same sign as ``x``.""" ... def pow(x: float, y: float) -> float: - """Returns ``x`` to the power of ``y``. + """Gibt ``x`` hoch ``y`` zurück. - Example: ``math.pow(4, 0.5)`` +Example: ``math.pow(4, 0.5)`` - :param x: A number - :param y: The exponent - :return: ``x`` to the power of ``y`` - """ +:param x: Eine Zahl +:param y: Der Exponent +:return: ``x`` to the power of ``y``""" ... def radians(x: float) -> float: - """Convert a degrees to radians. + """Wandelt Grad in Bogenmaß (Radiant) um. - Example: ``math.radians(360)`` +Example: ``math.radians(360)`` - :param x: A value in degrees - :return: The value converted to radians - """ +:param x: Ein Wert in Grad +:return: The value converted to radians""" ... def sin(x: float) -> float: - """Calculate the sine of ``x``. + """Berechnet den Sinus von ``x``. - Example: ``math.sin(math.pi/2)`` +Example: ``math.sin(math.pi/2)`` - :param x: A number - :return: The sine of ``x`` - """ +:param x: Eine Zahl +:return: The sine of ``x``""" ... def sqrt(x: float) -> float: - """Calculate the square root of ``x``. + """Berechnet die Quadratwurzel von ``x``. - Example: ``math.sqrt(4)`` +Example: ``math.sqrt(4)`` - :param x: A number - :return: The square root of ``x`` - """ +:param x: Eine Zahl +:return: The square root of ``x``""" ... def tan(x: float) -> float: - """Calculate the tangent of ``x``. + """Berechnet den Tangens von ``x``. - Example: ``math.tan(0)`` +Example: ``math.tan(0)`` - :param x: A number - :return: The tangent of ``x``. - """ +:param x: Eine Zahl +:return: The tangent of ``x``.""" ... def trunc(x: float) -> int: - """Round a number towards 0. + """Rundet eine Zahl gegen 0 ab. - Example: ``math.trunc(-0.9)`` +Example: ``math.trunc(-0.9)`` - :param x: A number - :return: ``x`` rounded towards zero. - """ +:param x: Eine Zahl +:return: ``x`` rounded towards zero.""" ... - e: float -"""Base of the natural logarithm""" - +"""Basis des natürlichen Logarithmus.""" pi: float -"""The ratio of a circle's circumference to its diameter""" +"""Das Verhältnis des Umfangs eines Kreises zu seinem Durchmesser.""" \ No newline at end of file diff --git a/lang/de/typeshed/stdlib/microbit/__init__.pyi b/lang/de/typeshed/stdlib/microbit/__init__.pyi index f12158f..08c6d1c 100644 --- a/lang/de/typeshed/stdlib/microbit/__init__.pyi +++ b/lang/de/typeshed/stdlib/microbit/__init__.pyi @@ -1,11 +1,6 @@ -"""Pins, images, sounds, temperature and volume. -""" - +"""Pins, Bilder, Töne, Temperatur und Lautstärke.""" from typing import Any, Callable, List, Optional, Tuple, Union, overload - from _typeshed import ReadableBuffer - -# V2 only from . import accelerometer as accelerometer from . import audio as audio from . import compass as compass @@ -16,831 +11,696 @@ from . import speaker as speaker from . import spi as spi from . import uart as uart -def run_every( - callback: Optional[Callable[[], None]] = None, - days: int = 0, - h: int = 0, - min: int = 0, - s: int = 0, - ms: int = 0, -) -> Callable[[Callable[[], None]], Callable[[], None]]: - """Schedule to run a function at the interval specified by the time arguments **V2 only**. +def run_every(callback: Optional[Callable[[], None]]=None, days: int=0, h: int=0, min: int=0, s: int=0, ms: int=0) -> Callable[[Callable[[], None]], Callable[[], None]]: + """Plant die Ausführung einer Funktion in dem durch die Zeitargumente festgelegten Intervall. **Nur micro:bit\xa0V2**. - Example: ``run_every(my_logging, min=5)`` +Example: ``run_every(my_logging, min=5)`` - ``run_every`` can be used in two ways: +``run_every`` can be used in two ways: - As a Decorator - placed on top of the function to schedule. For example:: +As a Decorator - placed on top of the function to schedule. For example:: - @run_every(h=1, min=20, s=30, ms=50) - def my_function(): - # Do something here + @run_every(h=1, min=20, s=30, ms=50) + def my_function(): + # Do something here - As a Function - passing the callback as a positional argument. For example:: +As a Function - passing the callback as a positional argument. For example:: - def my_function(): - # Do something here - run_every(my_function, s=30) + def my_function(): + # Do something here + run_every(my_function, s=30) - Each argument corresponds to a different time unit and they are additive. - So ``run_every(min=1, s=30)`` schedules the callback every minute and a half. +Each argument corresponds to a different time unit and they are additive. +So ``run_every(min=1, s=30)`` schedules the callback every minute and a half. - When an exception is thrown inside the callback function it deschedules the - function. To avoid this you can catch exceptions with ``try/except``. +When an exception is thrown inside the callback function it deschedules the +function. To avoid this you can catch exceptions with ``try/except``. - :param callback: Function to call at the provided interval. Omit when using as a decorator. - :param days: Sets the day mark for the scheduling. - :param h: Sets the hour mark for the scheduling. - :param min: Sets the minute mark for the scheduling. - :param s: Sets the second mark for the scheduling. - :param ms: Sets the millisecond mark for the scheduling. - """ +:param callback: Funktion, die in dem angegebenen Intervall aufgerufen wird. Bei Verwendung als Dekorator weglassen. +:param days: Legt den Tag für die Planung fest. +:param h: Legt die Uhrzeit für die Planung fest. +:param min: Legt die Minute für die Planung fest. +:param s: Legt die Sekunde für die Planung fest. +:param ms: Legt die Millisekunde für die Planung fest.""" def panic(n: int) -> None: - """Enter a panic mode. + """In einen Panik-Modus wechseln. - Example: ``panic(127)`` +Example: ``panic(127)`` - :param n: An arbitrary integer <= 255 to indicate a status. +:param n: Eine beliebige ganze Zahl <= 255, um einen Status anzugeben. - Requires restart. - """ +Requires restart.""" def reset() -> None: - """Restart the board.""" - + """Board neu starten.""" @overload def scale(value: float, from_: Tuple[float, float], to: Tuple[int, int]) -> int: - """Converts a value from a range to an integer range. + """Konvertiert einen Wert aus einem Bereich in einen Ganzzahlenbereich. - Example: ``volume = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255))`` +Example: ``volume = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255))`` - For example, to convert an accelerometer X value to a speaker volume. +For example, to convert an accelerometer X value to a speaker volume. - If one of the numbers in the ``to`` parameter is a floating point - (i.e a decimal number like ``10.0``), this function will return a - floating point number. +If one of the numbers in the ``to`` parameter is a floating point +(i.e a decimal number like ``10.0``), this function will return a +floating point number. - temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0)) + temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0)) - :param value: A number to convert. - :param from_: A tuple to define the range to convert from. - :param to: A tuple to define the range to convert to. - :return: The ``value`` converted to the ``to`` range. - """ +:param value: (wert) Eine umzurechnende Zahl. +:param from_: Ein Tupel, das den Bereich definiert, aus dem konvertiert werden soll. +:param to: Ein Tupel, das den Bereich definiert, in den konvertiert werden soll. +:return: The ``value`` converted to the ``to`` range.""" @overload def scale(value: float, from_: Tuple[float, float], to: Tuple[float, float]) -> float: - """Converts a value from a range to a floating point range. + """Konvertiert einen Wert von einem Bereich in einen Gleitkommabereich. - Example: ``temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0))`` +Example: ``temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0))`` - For example, to convert temperature from a Celsius scale to Fahrenheit. +For example, to convert temperature from a Celsius scale to Fahrenheit. - If one of the numbers in the ``to`` parameter is a floating point - (i.e a decimal number like ``10.0``), this function will return a - floating point number. - If they are both integers (i.e ``10``), it will return an integer:: +If one of the numbers in the ``to`` parameter is a floating point +(i.e a decimal number like ``10.0``), this function will return a +floating point number. +If they are both integers (i.e ``10``), it will return an integer:: - returns_int = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255)) + returns_int = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255)) - :param value: A number to convert. - :param from_: A tuple to define the range to convert from. - :param to: A tuple to define the range to convert to. - :return: The ``value`` converted to the ``to`` range. - """ +:param value: Eine umzurechnende Zahl. +:param from_: Ein Tupel, das den Bereich definiert, aus dem konvertiert werden soll. +:param to: Ein Tupel, das den Bereich definiert, in den konvertiert werden soll. +:return: The ``value`` converted to the ``to`` range.""" def sleep(n: float) -> None: - """Wait for ``n`` milliseconds. + """Wartet ``n`` Millisekunden. - Example: ``sleep(1000)`` +Example: ``sleep(1000)`` - :param n: The number of milliseconds to wait +:param n: Die Anzahl der zu wartenden Millisekunden - One second is 1000 milliseconds, so:: +One second is 1000 milliseconds, so:: - microbit.sleep(1000) + microbit.sleep(1000) - will pause the execution for one second. - """ +will pause the execution for one second.""" def running_time() -> int: - """Get the running time of the board. + """Ermittelt die Laufzeit des Boards. - :return: The number of milliseconds since the board was switched on or restarted. - """ +:return: The number of milliseconds since the board was switched on or restarted.""" def temperature() -> int: - """Get the temperature of the micro:bit in degrees Celsius.""" + """Ermittelt die Temperatur des micro:bit in Grad Celcius.""" def set_volume(v: int) -> None: - """Sets the volume. + """Legt die Lautstärke fest. - Example: ``set_volume(127)`` +Example: ``set_volume(127)`` - :param v: a value between 0 (low) and 255 (high). +:param v: ein Wert zwischen 0 (niedrig) und 255 (hoch). - Out of range values will be clamped to 0 or 255. +Out of range values will be clamped to 0 or 255. - **V2** only. - """ +**V2** only.""" ... class Button: - """The class for the buttons ``button_a`` and ``button_b``.""" + """Die Klasse für die Tasten ``button_a`` und ``button_b``.""" def is_pressed(self) -> bool: - """Check if the button is pressed. + """Überprüft, ob die Taste gedrückt ist. - :return: ``True`` if the specified button ``button`` is pressed, and ``False`` otherwise. - """ +:return: ``True`` if the specified button ``button`` is pressed, and ``False`` otherwise.""" ... + def was_pressed(self) -> bool: - """Check if the button was pressed since the device started or the last time this method was called. + """Überprüft, ob die Taste seit dem Start des Geräts oder dem letzten Aufruf dieser Methode gedrückt wurde. - Calling this method will clear the press state so - that the button must be pressed again before this method will return - ``True`` again. +Calling this method will clear the press state so +that the button must be pressed again before this method will return +``True`` again. - :return: ``True`` if the specified button ``button`` was pressed, and ``False`` otherwise - """ +:return: ``True`` if the specified button ``button`` was pressed, and ``False`` otherwise""" ... + def get_presses(self) -> int: - """Get the running total of button presses, and resets this total - to zero before returning. + """Ermittelt die Gesamtzahl der Tastendrücke und setzt diese Summe auf Null zurück, bevor sie zurückgegeben wird. - :return: The number of presses since the device started or the last time this method was called - """ +:return: The number of presses since the device started or the last time this method was called""" ... - button_a: Button -"""The left button ``Button`` object.""" - +"""Das Objekt ``Button`` der linken Taste.""" button_b: Button -"""The right button ``Button`` object.""" +"""Das Objekt ``Button`` der rechten Taste.""" class MicroBitDigitalPin: - """A digital pin. - - Some pins support analog and touch features using the ``MicroBitAnalogDigitalPin`` and ``MicroBitTouchPin`` subclasses. - """ + """Ein digitaler Pin. +Some pins support analog and touch features using the ``MicroBitAnalogDigitalPin`` and ``MicroBitTouchPin`` subclasses.""" NO_PULL: int PULL_UP: int PULL_DOWN: int + def read_digital(self) -> int: - """Get the digital value of the pin. + """Ermittelt den digitalen Wert des Pins. - Example: ``value = pin0.read_digital()`` +Example: ``value = pin0.read_digital()`` - :return: 1 if the pin is high, and 0 if it's low. - """ +:return: 1 if the pin is high, and 0 if it's low.""" ... + def write_digital(self, value: int) -> None: - """Set the digital value of the pin. + """Stellt den digitalen Wert des Pins ein. (digital schreiben) - Example: ``pin0.write_digital(1)`` +Example: ``pin0.write_digital(1)`` - :param value: 1 to set the pin high or 0 to set the pin low""" +:param value: (wert) 1, um den Pin zu aktivieren, oder 0, um den Pin zu deaktivieren""" ... + def set_pull(self, value: int) -> None: - """Set the pull state to one of three possible values: ``PULL_UP``, ``PULL_DOWN`` or ``NO_PULL``. + """Setze den Status des Pull-Widerstands auf einen von drei möglichen Werten: ``PULL_UP``, ``PULL_DOWN`` oder ``NO_PULL``. (setze Pull-Widerstand) - Example: ``pin0.set_pull(pin0.PULL_UP)`` +Example: ``pin0.set_pull(pin0.PULL_UP)`` - :param value: The pull state from the relevant pin, e.g. ``pin0.PULL_UP``. - """ +:param value: (wert) Der Status des Pull-Widerstands vom relevanten Pin, z.B. ``pin0.PULL_UP``.""" ... + def get_pull(self) -> int: - """Get the pull state on a pin. + """Abrufen des Status des Pull-Widerstands eines Pins. (gib Pull-Widerstand) - Example: ``pin0.get_pull()`` +Example: ``pin0.get_pull()`` - :return: ``NO_PULL``, ``PULL_DOWN``, or ``PULL_UP`` +:return: ``NO_PULL``, ``PULL_DOWN``, or ``PULL_UP`` - These are set using the ``set_pull()`` method or automatically configured - when a pin mode requires it. - """ +These are set using the ``set_pull()`` method or automatically configured +when a pin mode requires it.""" ... + def get_mode(self) -> str: - """Returns the pin mode. + """Gibt den Pin-Modus zurück. (gib Pin-Modus) - Example: ``pin0.get_mode()`` +Example: ``pin0.get_mode()`` - When a pin is used for a specific function, like - writing a digital value, or reading an analog value, the pin mode - changes. +When a pin is used for a specific function, like +writing a digital value, or reading an analog value, the pin mode +changes. - :return: ``"unused"``, ``"analog"``, ``"read_digital"``, ``"write_digital"``, ``"display"``, ``"button"``, ``"music"``, ``"audio"``, ``"touch"``, ``"i2c"``, or ``"spi"`` - """ +:return: ``"unused"``, ``"analog"``, ``"read_digital"``, ``"write_digital"``, ``"display"``, ``"button"``, ``"music"``, ``"audio"``, ``"touch"``, ``"i2c"``, or ``"spi"``""" ... + def write_analog(self, value: int) -> None: - """Output a PWM signal on the pin, with the duty cycle proportional to ``value``. + """Gib ein PWM-Signal am Pin aus, bei dem das Verhältnis von An- zu Auszeit proportional zu ``value`` ist. (analog schreiben) + +Example: ``pin0.write_analog(254)`` - Example: ``pin0.write_analog(254)`` +:param value: (wert) Eine Ganzzahl oder eine Gleitpunktzahl zwischen 0 (0% Einschaltdauer) und 1023 (100% Einschaltdauer).""" - :param value: 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. + """Setze die Periodendauer für die Ausgabe des PWM-Signals auf ``period`` in Mikrosekunden. (setze analoge Periodendauer) - Example: ``pin0.set_analog_period(10)`` +Example: ``pin0.set_analog_period(10)`` + +:param period: (Periodendauer) Der Periodendauer in Millisekunden mit einem Mindestwert von 1ms.""" - :param period: The period in milliseconds with a minimum valid value of 1ms. - """ def set_analog_period_microseconds(self, period: int) -> None: - """Set the period of the PWM signal being output to ``period`` in microseconds. + """Setzt den Zeitraum des PWM-Signals, das ausgegeben wird, auf ``period`` in Mikrosekunden. (setze analoge Periodendauer) - Example: ``pin0.set_analog_period_microseconds(512)`` +Example: ``pin0.set_analog_period_microseconds(512)`` - :param period: The period in microseconds with a minimum valid value of 256µs. - """ +:param period: (Periodendauer) Die Periodendauer in Mikrosekunden mit einem Mindestwert von 256\xa0μs.""" class MicroBitAnalogDigitalPin(MicroBitDigitalPin): - """A pin with analog and digital features.""" + """Ein Pin, der analogen und digitalen Signale erlaubt.""" def read_analog(self) -> int: - """Read the voltage applied to the pin. + """Einlesen der Spannung, die am Pin anliegt. (analog lesen) - Example: ``pin0.read_analog()`` +Example: ``pin0.read_analog()`` - :return: An integer between 0 (meaning 0V) and 1023 (meaning 3.3V). - """ +:return: An integer between 0 (meaning 0V) and 1023 (meaning 3.3V).""" class MicroBitTouchPin(MicroBitAnalogDigitalPin): - """A pin with analog, digital and touch features.""" - + """Ein Pin mit analogen, digitalen und Touchfunktionen.""" CAPACITIVE: int RESISTIVE: int + def is_touched(self) -> bool: - """Check if the pin is being touched. + """Überprüft, ob der Pin berührt wird. (wird berührt) - Example: ``pin0.is_touched()`` +Example: ``pin0.is_touched()`` - The default touch mode for the pins on the edge connector is ``resistive``. - The default for the logo pin **V2** is ``capacitive``. +The default touch mode for the pins on the edge connector is ``resistive``. +The default for the logo pin **V2** is ``capacitive``. - **Resistive touch** - This test is done by measuring how much resistance there is between the - pin and ground. A low resistance gives a reading of ``True``. To get - a reliable reading using a finger you may need to touch the ground pin - with another part of your body, for example your other hand. +**Resistive touch** +This test is done by measuring how much resistance there is between the +pin and ground. A low resistance gives a reading of ``True``. To get +a reliable reading using a finger you may need to touch the ground pin +with another part of your body, for example your other hand. - **Capacitive touch** - This test is done by interacting with the electric field of a capacitor - using a finger as a conductor. `Capacitive touch - `_ - does not require you to make a ground connection as part of a circuit. +**Capacitive touch** +This test is done by interacting with the electric field of a capacitor +using a finger as a conductor. `Capacitive touch +`_ +does not require you to make a ground connection as part of a circuit. - :return: ``True`` if the pin is being touched with a finger, otherwise return ``False``. - """ +:return: ``True`` if the pin is being touched with a finger, otherwise return ``False``.""" ... + def set_touch_mode(self, value: int) -> None: - """Set the touch mode for the pin. + """Legt den Berührungsmodus für den Pin fest. (definiert Berührungsmodus) - Example: ``pin0.set_touch_mode(pin0.CAPACITIVE)`` +Example: ``pin0.set_touch_mode(pin0.CAPACITIVE)`` - The default touch mode for the pins on the edge connector is - ``resistive``. The default for the logo pin **V2** is ``capacitive``. +The default touch mode for the pins on the edge connector is +``resistive``. The default for the logo pin **V2** is ``capacitive``. - :param value: ``CAPACITIVE`` or ``RESISTIVE`` from the relevant pin. - """ +:param value: (wert) ``CAPACITIVE`` oder ``RESISTIVE`` Touchmodus des entsprechenden Pins.""" ... - pin0: MicroBitTouchPin -"""Pin with digital, analog and touch features.""" - +"""Pin mit digitalen, analogen und Touchfunktionen.""" pin1: MicroBitTouchPin -"""Pin with digital, analog and touch features.""" - +"""Pin mit digitalen, analogen und Touchfunktionen.""" pin2: MicroBitTouchPin -"""Pin with digital, analog and touch features.""" - +"""Pin mit digitalen, analogen und Touchfunktionen.""" pin3: MicroBitAnalogDigitalPin -"""Pin with digital and analog features.""" - +"""Pin mit digitalen und analogen Funktionen.""" pin4: MicroBitAnalogDigitalPin -"""Pin with digital and analog features.""" - +"""Pin mit digitalen und analogen Funktionen.""" pin5: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin mit Unterstützung für digitale Signale.""" pin6: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin mit Unterstützung für digitale Signale.""" pin7: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin mit digitalen Funktionen.""" pin8: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin mit digitalen Funktionen.""" pin9: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin mit digitalen Funktionen.""" pin10: MicroBitAnalogDigitalPin -"""Pin with digital and analog features.""" - +"""Pin mit digitalen und analogen Funktionen.""" pin11: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin mit digitalen Funktionen.""" pin12: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin mit digitalen Funktionen.""" pin13: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin mit digitalen Funktionen.""" pin14: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin mit digitalen Funktionen.""" pin15: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin mit digitalen Funktionen.""" pin16: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin mit digitalen Funktionen.""" pin19: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin mit digitalen Funktionen.""" pin20: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin mit digitalen Funktionen.""" pin_logo: MicroBitTouchPin -"""A touch sensitive logo pin on the front of the micro:bit, which by default is set to capacitive touch mode.""" - +"""Ein berührungsempfindlicher Logo-Pin auf der Vorderseite des micro:bit, der standardmäßig auf den kapazitiven Berührungsmodus eingestellt ist.""" pin_speaker: MicroBitAnalogDigitalPin -"""A pin to address the micro:bit speaker. +"""Ein Pin zur Ansteuerung des micro:bit-Lautsprechers. This API is intended only for use in Pulse-Width Modulation pin operations e.g. pin_speaker.write_analog(128). """ class Image: - """An image to show on the micro:bit LED display. + """Ein Bild, das auf dem micro:bit LED-Display angezeigt werden soll. - Given an image object it's possible to display it via the ``display`` API:: - - display.show(Image.HAPPY) - """ +Given an image object it's possible to display it via the ``display`` API:: + display.show(Image.HAPPY)""" HEART: Image - """Heart image.""" - + """Herz-Bild.""" HEART_SMALL: Image - """Small heart image.""" - + """Kleines Herz-Bild.""" HAPPY: Image - """Happy face image.""" - + """Glückliches Gesichtsbild.""" SMILE: Image - """Smiling mouth image.""" - + """Lächelndes Gesichtsbild.""" SAD: Image - """Sad face image.""" - + """Trauriges Gesichtsbild.""" CONFUSED: Image - """Confused face image.""" - + """Verwirrtes Gesichtsbild.""" ANGRY: Image - """Angry face image.""" - + """Wütendes Gesichtsbild.""" ASLEEP: Image - """Sleeping face image.""" - + """Schlafendes Gesichtsbild.""" SURPRISED: Image - """Surprised face image.""" - + """Überraschtes Gesichtsbild.""" SILLY: Image - """Silly face image.""" - + """Albernes Gesichtsbild.""" FABULOUS: Image - """Sunglasses face image.""" - + """Bild mit Sonnenbrillengesicht. (fabelhaft)""" MEH: Image - """Unimpressed face image.""" - + """Gleichgültiges Gesicht Bild.""" YES: Image - """Tick image.""" - + """abgehakt-Bild""" NO: Image - """Cross image.""" - + """angekreuzt-Bild""" CLOCK12: Image - """Image with line pointing to 12 o'clock.""" - + """Bild mit Linie, die auf 12 Uhr zeigt.""" CLOCK11: Image - """Image with line pointing to 11 o'clock.""" - + """Bild mit Linie, die auf 11 Uhr zeigt.""" CLOCK10: Image - """Image with line pointing to 10 o'clock.""" - + """Bild mit Linie, die auf 10 Uhr zeigt.""" CLOCK9: Image - """Image with line pointing to 9 o'clock.""" - + """Bild mit Linie, die auf 9 Uhr zeigt.""" CLOCK8: Image - """Image with line pointing to 8 o'clock.""" - + """Bild mit Linie, die auf 8 Uhr zeigt.""" CLOCK7: Image - """Image with line pointing to 7 o'clock.""" - + """Bild mit Linie, die auf 7 Uhr zeigt.""" CLOCK6: Image - """Image with line pointing to 6 o'clock.""" - + """Bild mit Linie, die auf 6 Uhr zeigt.""" CLOCK5: Image - """Image with line pointing to 5 o'clock.""" - + """Bild mit Linie, die auf 5 Uhr zeigt.""" CLOCK4: Image - """Image with line pointing to 4 o'clock.""" - + """Bild mit Linie, die auf 4 Uhr zeigt.""" CLOCK3: Image - """Image with line pointing to 3 o'clock.""" - + """Bild mit Linie, die auf 3 Uhr zeigt.""" CLOCK2: Image - """Image with line pointing to 2 o'clock.""" - + """Bild mit Linie, die auf 2 Uhr zeigt.""" CLOCK1: Image - """Image with line pointing to 1 o'clock.""" - + """Bild mit Linie, die auf 1 Uhr zeigt.""" ARROW_N: Image - """Image of arrow pointing north.""" - + """Bild eines Pfeils, der nach Norden zeigt.""" ARROW_NE: Image - """Image of arrow pointing north east.""" - + """Bild eines Pfeils, der nach Nordosten zeigt.""" ARROW_E: Image - """Image of arrow pointing east.""" - + """Bild eines Pfeils, der nach Osten zeigt.""" ARROW_SE: Image - """Image of arrow pointing south east.""" - + """Bild eines Pfeils, der nach Südosten zeigt.""" ARROW_S: Image - """Image of arrow pointing south.""" - + """Bild eines Pfeils, der nach Süden zeigt.""" ARROW_SW: Image - """Image of arrow pointing south west.""" - + """Bild eines Pfeils, der nach Südwesten zeigt.""" ARROW_W: Image - """Image of arrow pointing west.""" - + """Bild eines Pfeils, der nach Westen zeigt.""" ARROW_NW: Image - """Image of arrow pointing north west.""" - + """Bild eines Pfeils, der nach Nordwesten zeigt.""" TRIANGLE: Image - """Image of a triangle pointing up.""" - + """Bild eines Dreiecks, das nach oben zeigt.""" TRIANGLE_LEFT: Image - """Image of a triangle in the left corner.""" - + """Bild eines Dreiecks in der linken Ecke.""" CHESSBOARD: Image - """Alternate LEDs lit in a chessboard pattern.""" - + """Abwechselnd leuchtende LEDs in einem Schachbrettmuster.""" DIAMOND: Image - """Diamond image.""" - + """Diamant-Bild.""" DIAMOND_SMALL: Image - """Small diamond image.""" - + """Kleines Diamant-Bild.""" SQUARE: Image - """Square image.""" - + """Quadrat-Bild""" SQUARE_SMALL: Image - """Small square image.""" - + """Kleines Quadrat-Bild.""" RABBIT: Image - """Rabbit image.""" - + """Kaninchen-Bild.""" COW: Image - """Cow image.""" - + """Kuh-Bild.""" MUSIC_CROTCHET: Image - """Crotchet note image.""" - + """Viertelnoten-Bild.""" MUSIC_QUAVER: Image - """Quaver note image.""" - + """Achtelnoten-Bild.""" MUSIC_QUAVERS: Image - """Pair of quavers note image.""" - + """Achtelnotenpaar-Bild.""" PITCHFORK: Image - """Pitchfork image.""" - + """Heugabel-Bild""" XMAS: Image - """Christmas tree image.""" - + """Weihnachtsbaum-Bild.""" PACMAN: Image - """Pac-Man arcade character image.""" - + """Pac-Man Spielfigurenbild.""" TARGET: Image - """Target image.""" - + """Ziel-Bild""" TSHIRT: Image - """T-shirt image.""" - + """T-Shirt-Bild.""" ROLLERSKATE: Image - """Rollerskate image.""" - + """Rollerskate-Bild.""" DUCK: Image - """Duck image.""" - + """Ente-Bild""" HOUSE: Image - """House image.""" - + """Haus-Bild""" TORTOISE: Image - """Tortoise image.""" - + """Schildkröte-Bild""" BUTTERFLY: Image - """Butterfly image.""" - + """Schmetterling-Bild.""" STICKFIGURE: Image - """Stick figure image.""" - + """Strichmännchen-Bild.""" GHOST: Image - """Ghost image.""" - + """Geist-Bild.""" SWORD: Image - """Sword image.""" - + """Schwert-Bild""" GIRAFFE: Image - """Giraffe image.""" - + """Giraffe-Bild.""" SKULL: Image - """Skull image.""" - + """Schädel-Bild.""" UMBRELLA: Image - """Umbrella image.""" - + """Bild eines Schirms.""" SNAKE: Image - """Snake image.""" - + """Bild einer Schlange. (Schlange)""" SCISSORS: Image - """Scissors image.""" - + """BIld einer Schere. (Schere)""" ALL_CLOCKS: List[Image] - """A list containing all the CLOCK_ images in sequence.""" - + """Eine Liste mit allen CLOCK_ Bildern. (alle Uhren)""" ALL_ARROWS: List[Image] - """A list containing all the ARROW_ images in sequence.""" + """Eine Liste mit allen ARROW_ Bildern. (alle Pfeile)""" + @overload def __init__(self, string: str) -> None: - """Create an image from a string describing which LEDs are lit. + """Erstellt ein Bild aus einer Zeichenkette, die beschreibt, welche LEDs leuchten. - ``string`` has to consist of digits 0-9 arranged into lines, - describing the image, for example:: +``string`` has to consist of digits 0-9 arranged into lines, +describing the image, for example:: - image = Image("90009:" - "09090:" - "00900:" - "09090:" - "90009") + 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 newlines (\\n) insead of the colons. +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 newlines (\\n) insead of the colons. - :param string: The string describing the image. - """ +:param string: (Zeichenkette) Eine Zeichenkette, die das Bild beschreibt.""" ... + @overload - def __init__( - self, width: int = 5, height: int = 5, buffer: ReadableBuffer = None - ) -> None: - """Create an empty image with ``width`` columns and ``height`` rows. + def __init__(self, width: int=5, height: int=5, buffer: ReadableBuffer=None) -> None: + """Erstelle ein leeres Bild mit ``width`` Spalten und ``height`` Zeilen. - :param width: Optional width of the image - :param height: Optional height of the image - :param buffer: Optional array or bytes of ``width``×``height`` integers in range 0-9 to initialize the image +:param width: (Breite) Optionale Breite des Bildes +:param height: (Höhe) Optionale Höhe des Bildes +:param buffer: (Puffer) Optionales Array oder Bytes von ``width``×``height`` Ganzzahlen im Bereich 0-9 um das Bild zu initialisieren - Examples:: +Examples:: - Image(2, 2, b'\x08\x08\x08\x08') - Image(2, 2, bytearray([9,9,9,9])) + Image(2, 2, b'\x08\x08\x08\x08') + Image(2, 2, bytearray([9,9,9,9])) - These create 2 x 2 pixel images at full brightness. - """ +These create 2 x 2 pixel images at full brightness.""" ... + def width(self) -> int: - """Get the number of columns. + """Ermittelt die Anzahl der Spalten. (Breite) - :return: The number of columns in the image - """ +:return: The number of columns in the image""" ... + def height(self) -> int: - """Get the number of rows. + """Ermittelt die Anzahl der Zeilen. (Höhe) - :return: The number of rows in the image - """ +:return: The number of rows in the image""" ... + def set_pixel(self, x: int, y: int, value: int) -> None: - """Set the brightness of a pixel. + """Legt die Helligkeit eines Pixels fest. (Pixelwerte setzen) - Example: ``my_image.set_pixel(0, 0, 9)`` +Example: ``my_image.set_pixel(0, 0, 9)`` - :param x: The column number - :param y: The row number - :param value: The brightness as an integer between 0 (dark) and 9 (bright) +:param x: Die Spaltennummer +:param y: Die Zeilennummer +:param value: (wert) Die Helligkeit als Ganzzahl zwischen 0 (dunkel) und 9 (hell) - This method will raise an exception when called on any of the built-in - read-only images, like ``Image.HEART``. - """ +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: - """Get the brightness of a pixel. + """Ermittle die Helligkeit eines Pixels. (Pixelwerte holen) - Example: ``my_image.get_pixel(0, 0)`` +Example: ``my_image.get_pixel(0, 0)`` - :param x: The column number - :param y: The row number - :return: The brightness as an integer between 0 and 9. - """ +:param x: Die Spaltennummer +:param y: Die Zeilennummer +:return: The brightness as an integer between 0 and 9.""" ... + def shift_left(self, n: int) -> Image: - """Create a new image by shifting the picture left. + """Erstellt ein neues Bild, indem das Bild nach links verschoben wird. (links verschieben) - Example: ``Image.HEART_SMALL.shift_left(1)`` +Example: ``Image.HEART_SMALL.shift_left(1)`` - :param n: The number of columns to shift by - :return: The shifted image - """ +:param n: Die Anzahl der Spalten um die verschoben wird +:return: The shifted image""" ... + def shift_right(self, n: int) -> Image: - """Create a new image by shifting the picture right. + """Erstellt ein neues Bild, indem das Bild nach rechts verschoben wird. (rechts verschieben) - Example: ``Image.HEART_SMALL.shift_right(1)`` +Example: ``Image.HEART_SMALL.shift_right(1)`` - :param n: The number of columns to shift by - :return: The shifted image - """ +:param n: Die Anzahl der Spalten um die verschoben wird +:return: The shifted image""" ... + def shift_up(self, n: int) -> Image: - """Create a new image by shifting the picture up. + """Erstellt ein neues Bild, indem das Bild nach oben verschoben wird. (nach oben verschieben) - Example: ``Image.HEART_SMALL.shift_up(1)`` +Example: ``Image.HEART_SMALL.shift_up(1)`` - :param n: The number of rows to shift by - :return: The shifted image - """ +:param n: Die Anzahl der Zeilen um die verschoben wird +:return: The shifted image""" ... + def shift_down(self, n: int) -> Image: - """Create a new image by shifting the picture down. + """Erstellt ein neues Bild, indem das Bild nach unten verschoben wird. (nach unten verschieben) - Example: ``Image.HEART_SMALL.shift_down(1)`` +Example: ``Image.HEART_SMALL.shift_down(1)`` - :param n: The number of rows to shift by - :return: The shifted image - """ +:param n: Die Anzahl der Zeilen um die verschoben wird +:return: The shifted image""" ... + def crop(self, x: int, y: int, w: int, h: int) -> Image: - """Create a new image by cropping the picture. + """Erstellen Sie ein neues Bild, indem das Bild zugeschnitten wird. - Example: ``Image.HEART.crop(1, 1, 3, 3)`` +Example: ``Image.HEART.crop(1, 1, 3, 3)`` - :param x: The crop offset column - :param y: The crop offset row - :param w: The crop width - :param h: The crop height - :return: The new image - """ +:param x: Die Offset-Spalte des Zuschneidens +:param y: Die Offset-Zeile des Zuschneidens +:param w: Die Zuschneide-Breite +:param h: Die Zuschneide-Höhe +:return: The new image""" ... + def copy(self) -> Image: - """Create an exact copy of the image. + """Erstellt eine exakte Kopie des Bildes. (kopieren) - Example: ``Image.HEART.copy()`` +Example: ``Image.HEART.copy()`` - :return: The new image - """ +:return: The new image""" ... + def invert(self) -> Image: - """Create a new image by inverting the brightness of the pixels in the - source image. + """Erstellt ein neues Bild, indem es die Helligkeit der Pixel des Ausgangsbildes invertiert. - Example: ``Image.SMALL_HEART.invert()`` +Example: ``Image.SMALL_HEART.invert()`` - :return: The new image. - """ +:return: The new image.""" ... + def fill(self, value: int) -> None: - """Set the brightness of all the pixels in the image. + """Legt die Helligkeit für alle Pixel des Bildes fest. - Example: ``my_image.fill(5)`` +Example: ``my_image.fill(5)`` - :param value: The new brightness as a number between 0 (dark) and 9 (bright). +:param value: Die neue Helligkeit als Zahl zwischen 0 (dunkel) und 9 (hell). - This method will raise an exception when called on any of the built-in - read-only images, like ``Image.HEART``. - """ +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 an area from another image into this image. - - Example: ``my_image.blit(Image.HEART, 1, 1, 3, 3, 1, 1)`` - - :param src: The source image - :param x: The starting column offset in the source image - :param y: The starting row offset in the source image - :param w: The number of columns to copy - :param h: The number of rows to copy - :param xdest: The column offset to modify in this image - :param ydest: The row offset to modify in this image - - Pixels outside the source image are treated as having a brightness 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 blit(self, src: Image, x: int, y: int, w: int, h: int, xdest: int=0, ydest: int=0) -> None: + """Kopiert einen Bereich aus einem anderen Bild in dieses Bild. + +Example: ``my_image.blit(Image.HEART, 1, 1, 3, 3, 1, 1)`` + +:param src: Das Ausgangsbild +:param x: Der Anfangsspalten-Offset im Ausgangsbild +:param y: Der Anfangszeilen-Offset im Ausgangsbild +:param w: Die Anzahl der zu kopierenden Spalten +:param h: Die Anzahl der zu kopierenden Zeilen +:param xdest: Der Spalten-Offset, der in diesem Bild geändert werden soll +:param ydest: Der Zeilen-Offset, der in diesem Bild geändert werden soll + +Pixels outside the source image are treated as having a brightness 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.""" + """Liefert eine kompakte Stringrepräsentation des Bildes.""" ... + def __str__(self) -> str: - """Get a readable string representation of the image.""" + """Liefert eine lesbare String-Repräsentation des Bildes.""" ... + def __add__(self, other: Image) -> Image: - """Create a new image by adding the brightness values from the two - images for each pixel. + """Erstellt ein neues Bild, indem für jedes Pixel die Helligkeitswerte der beiden Bilder addiert werden. - Example: ``Image.HEART + Image.HAPPY`` +Example: ``Image.HEART + Image.HAPPY`` - :param other: The image to add. - """ +:param other: Das zu addierende Bild.""" ... + def __sub__(self, other: Image) -> Image: - """Create a new image by subtracting the brightness values of the - other image from this image. + """Erstellt ein neues Bild, indem für jedes Pixel die Helligkeitswerte der beiden Bilder subtrahiert werden. - Example: ``Image.HEART - Image.HEART_SMALL`` +Example: ``Image.HEART - Image.HEART_SMALL`` - :param other: The image to subtract. - """ +:param other: Das zu subtrahierende Bild.""" ... + def __mul__(self, n: float) -> Image: - """Create a new image by multiplying the brightness of each pixel by - ``n``. + """Erstellt ein neues Bild, indem der Helligkeitswert jedes Pixels mit ``n`` multipliziert wird. - Example: ``Image.HEART * 0.5`` +Example: ``Image.HEART * 0.5`` - :param n: The value to multiply by. - """ +:param n: Der Wert, mit dem multipliziert werden soll.""" ... + def __truediv__(self, n: float) -> Image: - """Create a new image by dividing the brightness of each pixel by - ``n``. + """Erstellt ein neues Bild, indem der Helligkeitswert jedes Pixels durch ``n`` dividiert wird. - Example: ``Image.HEART / 2`` +Example: ``Image.HEART / 2`` - :param n: The value to divide by. - """ +:param n: Der Wert, durch den dividiert werden soll.""" ... class SoundEvent: LOUD: SoundEvent - """Represents the transition of sound events, from ``quiet`` to ``loud`` like clapping or shouting.""" - + """Stellt den Übergang von Klangereignissen von ``quiet`` auf ``loud`` dar; wie beim Klatschen oder Rufen.""" QUIET: SoundEvent - """Represents the transition of sound events, from ``loud`` to ``quiet`` like speaking or background music.""" + """Stellt den Übergang von akustischen Ereignissen, wie Sprechen oder Hintergrundmusik, von ``loud`` zu ``quiet`` dar. (stumm)""" class Sound: - """The built-in sounds can be called using ``audio.play(Sound.NAME)``.""" - + """Die eingebauten Klänge können mit ``audio.play(Sound.NAME)`` aufgerufen werden.""" GIGGLE: Sound - """Giggling sound.""" - + """Kichern-Sound.""" HAPPY: Sound - """Happy sound.""" - + """Happy-Sound.""" HELLO: Sound - """Greeting sound.""" - + """Begrüßung-Sound""" MYSTERIOUS: Sound - """Mysterious sound.""" - + """Geheimnisvoll-Sound""" SAD: Sound - """Sad sound.""" - + """Traurig-Sound.""" SLIDE: Sound - """Sliding sound.""" - + """Gleitender Ton.""" SOARING: Sound - """Soaring sound.""" - + """Aufsteigender Klang. (aufsteigend)""" SPRING: Sound - """Spring sound.""" - + """Springfeder Klang (Sppringfeder)""" TWINKLE: Sound - """Twinkling sound.""" - + """Funkeln Klang (Funkeln)""" YAWN: Sound - """Yawning sound.""" + """Gähnen Klang""" \ No newline at end of file diff --git a/lang/de/typeshed/stdlib/microbit/accelerometer.pyi b/lang/de/typeshed/stdlib/microbit/accelerometer.pyi index bac82c0..1d9f5d3 100644 --- a/lang/de/typeshed/stdlib/microbit/accelerometer.pyi +++ b/lang/de/typeshed/stdlib/microbit/accelerometer.pyi @@ -1,115 +1,103 @@ -"""Measure the acceleration of the micro:bit and recognise gestures. -""" - +"""Messen Sie die Beschleunigung des micro:bit und erkennen Sie Gesten. (Beschleunigungssensor)""" from typing import Tuple def get_x() -> int: - """Get the acceleration measurement in the ``x`` axis in milli-g. + """Erhalte die Beschleunigungsmessung in der ``x`` -Achse in Milli-g. - Example: ``accelerometer.get_x()`` +Example: ``accelerometer.get_x()`` - :return: A positive or negative integer depending on direction in the range +/- 2000mg. - """ +:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" ... def get_y() -> int: - """Get the acceleration measurement in the ``y`` axis in milli-g. + """Erhalte die Beschleunigungsmessung in der ``y`` -Achse in Milli-g. - Example: ``accelerometer.get_y()`` +Example: ``accelerometer.get_y()`` - :return: A positive or negative integer depending on direction in the range +/- 2000mg. - """ +:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" ... def get_z() -> int: - """Get the acceleration measurement in the ``z`` axis in milli-g. + """Erhalte die Beschleunigungsmessung in der ``z`` -Achse in Milli-g. - Example: ``accelerometer.get_z()`` +Example: ``accelerometer.get_z()`` - :return: A positive or negative integer depending on direction in the range +/- 2000mg. - """ +:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" ... def get_values() -> Tuple[int, int, int]: - """Get the acceleration measurements in all axes at once as a tuple. + """Erhalte die Beschleunigungsmessung in allen Achsen auf einmal als Tupel. - Example: ``x, y, z = accelerometer.get_values()`` +Example: ``x, y, z = accelerometer.get_values()`` - :return: a three-element tuple of integers ordered as X, Y, Z, each value a positive or negative integer depending on direction in the range +/- 2000mg - """ +:return: a three-element tuple of integers ordered as X, Y, Z, each value a positive or negative integer depending on direction in the range +/- 2000mg""" ... def get_strength() -> int: - """Get the acceleration measurement of all axes combined, as a positive integer. This is the Pythagorean sum of the X, Y and Z axes. + """Erhalte die Beschleunigungsmessung aller Achsen als positive Ganzzahl. Dies ist die euklidische Summe der x-, y- und z-Achsen. - Example: ``accelerometer.get_strength()`` +Example: ``accelerometer.get_strength()`` - :return: The combined acceleration strength of all the axes, in milli-g. - """ +:return: The combined acceleration strength of all the axes, in milli-g.""" ... def current_gesture() -> str: - """Get the name of the current gesture. + """Erhalte den Namen der aktuellen Geste. (derzeitige Geste) - Example: ``accelerometer.current_gesture()`` +Example: ``accelerometer.current_gesture()`` - 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. +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. - :return: The current gesture - """ +:return: The current gesture""" ... def is_gesture(name: str) -> bool: - """Check if the named gesture is currently active. + """Überprüft, ob die benannte Geste derzeit aktiv ist. (ist Geste) - Example: ``accelerometer.is_gesture('shake')`` +Example: ``accelerometer.is_gesture('shake')`` - 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. +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. - :param name: The gesture name. - :return: ``True`` if the gesture is active, ``False`` otherwise. - """ +:param name: Der Name der Geste. +:return: ``True`` if the gesture is active, ``False`` otherwise.""" ... def was_gesture(name: str) -> bool: - """Check if the named gesture was active since the last call. + """Überprüft, ob die benannte Geste seit dem letzten Aufruf aktiv war. (war Geste) - Example: ``accelerometer.was_gesture('shake')`` +Example: ``accelerometer.was_gesture('shake')`` - 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. +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. - :param name: The gesture name. - :return: ``True`` if the gesture was active since the last call, ``False`` otherwise. - """ +:param name: Der Name der Geste. +:return: ``True`` if the gesture was active since the last call, ``False`` otherwise.""" def get_gestures() -> Tuple[str, ...]: - """Return a tuple of the gesture history. + """Gibt ein Tupel der vergangenen Gesten zurück. - Example: ``accelerometer.get_gestures()`` +Example: ``accelerometer.get_gestures()`` - Clears the gesture history before returning. +Clears the gesture history before returning. - Gestures are not updated in the background so there needs to be constant - calls to some accelerometer method to do the gesture detection. Usually - gestures can be detected using a loop with a small :func:`microbit.sleep` delay. +Gestures are not updated in the background so there needs to be constant +calls to some accelerometer method to do the gesture detection. Usually +gestures can be detected using a loop with a small :func:`microbit.sleep` delay. - :return: The history as a tuple, most recent last. - """ +:return: The history as a tuple, most recent last.""" ... def set_range(value: int) -> None: - """Set the accelerometer sensitivity range, in g (standard gravity), to the closest values supported by the hardware, so it rounds to either ``2``, ``4``, or ``8`` g. + """Legt den Bereich des Beschleunigungsmessers in g (Fallbeschleunigung) auf den nächstgelegenen Wert fest, welcher von der Hardware unterstützt wird. Diese sind ``2``, ``4``oder ``8`` g. (Bereich einstellen) - Example: ``accelerometer.set_range(8)`` +Example: ``accelerometer.set_range(8)`` - :param value: New range for the accelerometer, an integer in ``g``. - """ +:param value: (wert) Neuer Bereich für den Beschleunigungssensor, eine Ganzzahl in ``g``.""" \ No newline at end of file diff --git a/lang/de/typeshed/stdlib/microbit/audio.pyi b/lang/de/typeshed/stdlib/microbit/audio.pyi index 3b1e327..fceaf91 100644 --- a/lang/de/typeshed/stdlib/microbit/audio.pyi +++ b/lang/de/typeshed/stdlib/microbit/audio.pyi @@ -1,160 +1,124 @@ -"""Play sounds using the micro:bit (import ``audio`` for V1 compatibility). -""" - +"""Töne mit dem micro:bit abspielen (Importiere ``audio`` für V1-Kompatibilität). (Audio)""" from ..microbit import MicroBitDigitalPin, Sound, pin0 from typing import ClassVar, Iterable, Union -def play( - source: Union[Iterable[AudioFrame], Sound, SoundEffect], - wait: bool = True, - pin: MicroBitDigitalPin = pin0, - return_pin: Union[MicroBitDigitalPin, None] = None, -) -> None: - """Play a built-in sound, sound effect or custom audio frames. +def play(source: Union[Iterable[AudioFrame], Sound, SoundEffect], wait: bool=True, pin: MicroBitDigitalPin=pin0, return_pin: Union[MicroBitDigitalPin, None]=None) -> None: + """Wiedergeben eines eingebauten Sounds, Soundeffekts oder benutzerdefinierten Aufnahme . - Example: ``audio.play(Sound.GIGGLE)`` +Example: ``audio.play(Sound.GIGGLE)`` - :param source: A built-in ``Sound`` such as ``Sound.GIGGLE``, a ``SoundEffect`` or sample data as an iterable of ``AudioFrame`` objects. - :param wait: If ``wait`` is ``True``, this function will block until the sound is complete. - :param pin: An optional argument to specify the output pin can be used to override the default of ``pin0``. If we do not want any sound to play we can use ``pin=None``. - :param return_pin: Specifies a differential edge connector pin to connect to an external speaker instead of ground. This is ignored for the **V2** revision. - """ +:param source: (Quelle) Ein eingebauter ``Sound`` wie ``Sound.GIGGLE``, ein ``SoundEffect`` oder Beispieldaten als Teil eines ``AudioFrame`` Objekts. +:param wait: Wenn ``wait`` ``True`` ist, wird diese Funktion blockiert, bis der Klang abgeschlossen ist. +:param pin: Ein optionales Argument für den Ausgabepin kann angegeben werden, um die Standardeinstellung von ``pin0``zu überschreiben. Wenn kein Ton wiedergegeben werden soll, kann ``pin=None`` verwendet werden. +:param return_pin: Bestimmt einen Pin, mit dem der externen Lautsprecher anstatt mit Ground verbunden wird. Dies wird bei der **V2** Revision ignoriert.""" def is_playing() -> bool: - """Check whether a sound is playing. + """Überprüft, ob ein Ton abgespielt wird. (spielt gerade) - Example: ``audio.is_playing()`` +Example: ``audio.is_playing()`` - :return: ``True`` if audio is playing, otherwise ``False``.""" +:return: ``True`` if audio is playing, otherwise ``False``.""" ... def stop() -> None: - """Stop all audio playback. + """Stoppt jede Audio-Wiedergabe. (Stop) - Example: ``audio.stop()`` - """ +Example: ``audio.stop()``""" ... class SoundEffect: - """A sound effect, composed by a set of parameters configured via the constructor or attributes.""" - + """Ein Soundeffekt, zusammengestellt aus einer Reihe von Parametern, die über den Konstruktor oder durch Attribute konfiguriert werden.""" WAVEFORM_SINE: ClassVar[int] - """Sine wave option used for the ``waveform`` parameter.""" - + """Sinuswelle als Parameter für ``waveform``. (Sinuswelle)""" WAVEFORM_SAWTOOTH: ClassVar[int] - """Sawtooth wave option used for the ``waveform`` parameter.""" - + """Sägezahnkurve als Parameter für ``waveform``. (Sägezahnkurve)""" WAVEFORM_TRIANGLE: ClassVar[int] - """Triangle wave option used for the ``waveform`` parameter.""" - + """Dreiecksignal als Parameter für ``waveform``. (Dreiecksignal)""" WAVEFORM_SQUARE: ClassVar[int] - """Square wave option used for the ``waveform`` parameter.""" - + """Rechtecksignal als Parameter für ``waveform``. (Rechtecksignal)""" WAVEFORM_NOISE: ClassVar[int] - """Noise option used for the ``waveform`` parameter.""" - + """Rauschsignal als Parameter für ``waveform``. (Rauschsignal)""" SHAPE_LINEAR: ClassVar[int] - """Linear interpolation option used for the ``shape`` parameter.""" - + """Lineare Interpolation als Parameter für ``shape``. (lineare Interpolation)""" SHAPE_CURVE: ClassVar[int] - """Curve interpolation option used for the ``shape`` parameter.""" - + """Kurven-Interpolation als Parameter für ``shape``. (geschwungene Kurve)""" SHAPE_LOG: ClassVar[int] - """Logarithmic interpolation option used for the ``shape`` parameter.""" - + """Logarithmische Interpolation als Parameter für ``shape``. (logarithmische Interpolation)""" FX_NONE: ClassVar[int] - """No effect option used for the ``fx`` parameter.""" - + """Kein Effekt für ``fx`` verwendet. (kein fx)""" FX_TREMOLO: ClassVar[int] - """Tremolo effect option used for the ``fx`` parameter.""" - + """Tremelo-Effekt als Parameter für ``fx``. (fx Tremolo)""" FX_VIBRATO: ClassVar[int] - """Vibrato effect option used for the ``fx`` parameter.""" - + """Vibrato-Effekt als Parameter für ``fx``. (fx Vibrato)""" FX_WARBLE: ClassVar[int] - """Warble effect option used for the ``fx`` parameter.""" - + """Triller-Effekt als Parameter für ``fx``. (fx Trillereffekt)""" freq_start: int - """Start frequency in Hertz (Hz), a number between ``0`` and ``9999``""" - + """Startfrequenz in Hertz (Hz), eine Zahl zwischen ``0`` und ``9999`` (Startfrequenz)""" freq_end: int - """End frequency in Hertz (Hz), a number between ``0`` and ``9999``""" - + """Endfrequenz in Hertz (Hz), eine Zahl zwischen ``0`` und ``9999`` (Endfrequenz)""" duration: int - """Duration of the sound in milliseconds, a number between ``0`` and ``9999``""" - + """Dauer des Klangs in Millisekunden, eine Zahl zwischen ``0`` und ``9999`` (Dauer)""" vol_start: int - """Start volume value, a number between ``0`` and ``255``""" - + """Startlautstärke, eine Zahl zwischen ``0`` und ``255`` (vol Start)""" vol_end: int - """End volume value, a number between ``0`` and ``255``""" - + """Endlautstärke, eine Nummer zwischen ``0`` und ``255`` (vol Ende)""" waveform: int - """Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise)""" - + """Typ der Sinuswelle, einer dieser Werte: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (zufällig generiertes Geräusch)""" fx: int - """Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``""" - + """Effekt, der dem Sound hinzugefügt werden soll. Mögliche Werte: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE`` oder ``FX_NONE``""" shape: int - """The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``""" - - def __init__( - self, - freq_start: int = 500, - freq_end: int = 2500, - duration: int = 500, - vol_start: int = 255, - vol_end: int = 0, - waveform: int = WAVEFORM_SQUARE, - fx: int = FX_NONE, - shape: int = SHAPE_LOG, - ): - """Create a new sound effect. - - Example: ``my_effect = SoundEffect(duration=1000)`` - - All the parameters are optional, with default values as shown above, and - they can all be modified via attributes of the same name. For example, we - can first create an effect ``my_effect = SoundEffect(duration=1000)``, - and then change its attributes ``my_effect.duration = 500``. - - :param freq_start: Start frequency in Hertz (Hz), a number between ``0`` and ``9999``. - :param freq_end: End frequency in Hertz (Hz), a number between ``0`` and ``9999``. - :param duration: Duration of the sound in milliseconds, a number between ``0`` and ``9999``. - :param vol_start: Start volume value, a number between ``0`` and ``255``. - :param vol_end: End volume value, a number between ``0`` and ``255``. - :param waveform: Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise). - :param fx: Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``. - :param shape: The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``. - """ + """Die Art der Interpolationskurve zwischen der Anfangs- und der Endfrequenz. Verschiedene Wellenformen haben unterschiedliche Frequenzänderungsraten. In Frage kommende Werte: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``""" + + def __init__(self, freq_start: int=500, freq_end: int=2500, duration: int=500, vol_start: int=255, vol_end: int=0, waveform: int=WAVEFORM_SQUARE, fx: int=FX_NONE, shape: int=SHAPE_LOG): + """Erstellt einen neuen Soundeffekt. + +Example: ``my_effect = SoundEffect(duration=1000)`` + +All the parameters are optional, with default values as shown above, and +they can all be modified via attributes of the same name. For example, we +can first create an effect ``my_effect = SoundEffect(duration=1000)``, +and then change its attributes ``my_effect.duration = 500``. + +:param freq_start: (Startfrequenz) Startfrequenz in Hertz (Hz), eine Zahl zwischen ``0`` und ``9999``. +:param freq_end: (Endfrequenz) Endfrequenz in Hertz (Hz), eine Zahl zwischen ``0`` und ``9999``. +:param duration: (Dauer) Dauer des Tons in Millisekunden, eine Zahl zwischen ``0`` und ``9999``. +:param vol_start: (vol Start) Startlautstärke, eine Zahl zwischen ``0`` und ``255``. +:param vol_end: (vol Ende) Endlautstärke, eine Nummer zwischen ``0`` und ``255``. +:param waveform: Typ der Sinuswelle, einer dieser Werte: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (zufällig generiertes Geräusch). +:param fx: Effekt, der dem Sound hinzugefügt werden soll, in Frage kommende Werte: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, oder ``FX_NONE``. +:param shape: Die Art der Interpolationskurve zwischen der Anfangs- und der Endfrequenz. Verschiedene Wellenformen haben unterschiedliche Frequenzänderungsraten. In Frage kommende Werte: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``.""" + def copy(self) -> SoundEffect: - """Create a copy of this ``SoundEffect``. + """Erstellt eine Kopie dieses ``SoundEffect``. (kopieren) - Example: ``sound_2 = sound_1.copy()`` +Example: ``sound_2 = sound_1.copy()`` - :return: A copy of the SoundEffect. - """ +:return: A copy of the SoundEffect.""" class AudioFrame: - """An ``AudioFrame`` object is a list of 32 samples each of which is a unsigned byte - (whole number between 0 and 255). + """Ein ``AudioFrame``-Objekt ist eine Liste von 32 Samples, von denen jedes ein vorzeichenloses Byte ist +(ganze Zahl zwischen 0 und 255). - It takes just over 4 ms to play a single frame. +It takes just over 4 ms to play a single frame. - Example:: +Example:: - frame = AudioFrame() - for i in range(len(frame)): - frame[i] = 252 - i * 8 - """ + frame = AudioFrame() + for i in range(len(frame)): + frame[i] = 252 - i * 8""" def copyfrom(self, other: AudioFrame) -> None: - """Overwrite the data in this ``AudioFrame`` with the data from another ``AudioFrame`` instance. + """Überschreibt die Daten in diesem ``AudioFrame`` mit den Daten einer anderen ``AudioFrame``-Instanz. + +Example: ``my_frame.copyfrom(source_frame)`` + +:param other: ``AudioFrame`` Instanz von der die Daten kopiert werden sollen.""" + + def __len__(self) -> int: + ... - Example: ``my_frame.copyfrom(source_frame)`` + def __setitem__(self, key: int, value: int) -> None: + ... - :param other: ``AudioFrame`` instance from which to copy the data. - """ - def __len__(self) -> int: ... - def __setitem__(self, key: int, value: int) -> None: ... - def __getitem__(self, key: int) -> int: ... + def __getitem__(self, key: int) -> int: + ... \ No newline at end of file diff --git a/lang/de/typeshed/stdlib/microbit/compass.pyi b/lang/de/typeshed/stdlib/microbit/compass.pyi index c74a47b..9e25ff0 100644 --- a/lang/de/typeshed/stdlib/microbit/compass.pyi +++ b/lang/de/typeshed/stdlib/microbit/compass.pyi @@ -1,78 +1,70 @@ -"""Use the built-in compass. -""" +"""Benutze den eingebauten Kompass. (Kompass)""" def calibrate() -> None: - """Starts the calibration process. + """Startet den Kalibrierungsprozess. - Example: ``compass.calibrate()`` +Example: ``compass.calibrate()`` - 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. - """ +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: - """Check is the compass is calibrated. + """Überprüft, dass der Kompass kalibriert ist. (ist kalibriert) - Example: ``compass.is_calibrated()`` +Example: ``compass.is_calibrated()`` - :return: ``True`` if the compass has been successfully calibrated, ``False`` otherwise. - """ +:return: ``True`` if the compass has been successfully calibrated, ``False`` otherwise.""" ... def clear_calibration() -> None: - """Undoes the calibration, making the compass uncalibrated again. + """Setzt die Kalibrierung zurück, sodass der Kompass nicht mehr kalibriert ist. - Example: ``compass.clear_calibration()`` - """ +Example: ``compass.clear_calibration()``""" ... def get_x() -> int: - """Get the magnetic field strength on the ``x`` axis. + """Liefert die Magnetfeldstärke der ``x``-Achse. - Example: ``compass.get_x()`` +Example: ``compass.get_x()`` - Call ``calibrate`` first or the results will be inaccurate. +Call ``calibrate`` first or the results will be inaccurate. - :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. - """ +:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" ... def get_y() -> int: - """Get the magnetic field strength on the ``y`` axis. + """Liefert die Magnetfeldstärke der ``y``-Achse. - Example: ``compass.get_y()`` +Example: ``compass.get_y()`` - Call ``calibrate`` first or the results will be inaccurate. +Call ``calibrate`` first or the results will be inaccurate. - :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. - """ +:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" ... def get_z() -> int: - """Get the magnetic field strength on the ``z`` axis. + """Liefert die Magnetfeldstärke der ``z``-Achse. - Example: ``compass.get_z()`` +Example: ``compass.get_z()`` - Call ``calibrate`` first or the results will be inaccurate. +Call ``calibrate`` first or the results will be inaccurate. - :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. - """ +:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" ... def heading() -> int: - """Get the compass heading. + """Ermittelt die Kompassrichtung. (Ausrichtung) - Example: ``compass.heading()`` +Example: ``compass.heading()`` - :return: An integer in the range from 0 to 360, representing the angle in degrees, clockwise, with north as 0. - """ +:return: An integer in the range from 0 to 360, representing the angle in degrees, clockwise, with north as 0.""" ... def get_field_strength() -> int: - """Get the magnitude of the magnetic field around the device. + """Ermittelt die Größe des Magnetfelds um das Gerät herum. - Example: ``compass.get_field_strength()`` +Example: ``compass.get_field_strength()`` - :return: An integer indication of the magnitude of the magnetic field in nano tesla.""" - ... +:return: An integer indication of the magnitude of the magnetic field in nano tesla.""" + ... \ No newline at end of file diff --git a/lang/de/typeshed/stdlib/microbit/display.pyi b/lang/de/typeshed/stdlib/microbit/display.pyi index aa4013e..ad66782 100644 --- a/lang/de/typeshed/stdlib/microbit/display.pyi +++ b/lang/de/typeshed/stdlib/microbit/display.pyi @@ -1,115 +1,92 @@ -"""Show text, images and animations on the 5×5 LED display. -""" - +"""Texte, Bilder und Animationen auf dem 5x5 LED-Display anzeigen. (Display)""" from ..microbit import Image from typing import Union, overload, Iterable def get_pixel(x: int, y: int) -> int: - """Get the brightness of the LED at column ``x`` and row ``y``. + """Ermittelt die Helligkeit der LED in Spalte ``x`` und Zeile ``y``. - Example: ``display.get_pixel(0, 0)`` +Example: ``display.get_pixel(0, 0)`` - :param x: The display column (0..4) - :param y: The display row (0..4) - :return: A number between 0 (off) and 9 (bright) - """ +:param x: Die Anzeige-Spalte (0..4) +:param y: Die Anzeigezeile (0..4) +:return: A number 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``. + """Stellt die Helligkeit der LED in Spalte ``x`` und Zeile ``y`` ein. - Example: ``display.set_pixel(0, 0, 9)`` +Example: ``display.set_pixel(0, 0, 9)`` - :param x: The display column (0..4) - :param y: The display row (0..4) - :param value: The brightness between 0 (off) and 9 (bright) - """ +:param x: Die Anzeige-Spalte (0..4) +:param y: Die Anzeigezeile (0..4) +:param value: Die Helligkeit zwischen 0 (aus) und 9 (am hellsten)""" ... def clear() -> None: - """Set the brightness of all LEDs to 0 (off). + """Setzt die Helligkeit aller LEDs auf 0 (aus). - Example: ``display.clear()`` - """ +Example: ``display.clear()``""" ... -def show( - image: Union[str, float, int, Image, Iterable[Image]], - delay: int = 400, - wait: bool = True, - loop: bool = False, - clear: bool = False, -) -> None: - """Shows images, letters or digits on the LED display. +def show(image: Union[str, float, int, Image, Iterable[Image]], delay: int=400, wait: bool=True, loop: bool=False, clear: bool=False) -> None: + """Zeigt Bilder, Buchstaben oder Ziffern auf der LED-Anzeige an. - Example: ``display.show(Image.HEART)`` +Example: ``display.show(Image.HEART)`` - When ``image`` is an image or a list of images then each image is displayed in turn. - If ``image`` is a string or number, each letter or digit is displayed in turn. +When ``image`` is an image or a list of images then each image is displayed in turn. +If ``image`` is a string or number, each letter or digit is displayed in turn. - :param image: A string, number, image or list of images to show. - :param delay: Each letter, digit or image is shown with ``delay`` milliseconds between them. - :param wait: If ``wait`` is ``True``, this function will block until the animation is finished, otherwise the animation will happen in the background. - :param loop: If ``loop`` is ``True``, the animation will repeat forever. - :param clear: If ``clear`` is ``True``, the display will be cleared after the sequence has finished. +:param image: Eine Zeichenkette, eine Zahl, ein Bild oder eine Liste von Bildern, die angezeigt werden sollen. +:param delay: Jeder Buchstabe, jede Ziffer oder jedes Bild wird mit einer Verzögerung von ``delay`` Millisekunden angezeigt. +:param wait: Wenn ``wait`` ``True`` ist, wird diese Funktion das Programm so lange anhalten, bis die Animation beendet ist, andernfalls wird die Animation im Hintergrund ausgeführt. +:param loop: Wenn ``loop`` ``True`` ist, wird die Animation endlos wiederholt. +:param clear: Wenn ``clear`` ``True`` ist, wird die Anzeige nach Beendigung der Sequenz gelöscht. - The ``wait``, ``loop`` and ``clear`` arguments must be specified using their keyword. - """ +The ``wait``, ``loop`` and ``clear`` arguments must be specified using their keyword.""" ... -def scroll( - text: Union[str, float, int], - delay: int = 150, - wait: bool = True, - loop: bool = False, - monospace: bool = False, -) -> None: - """Scrolls a number or text on the LED display. - - Example: ``display.scroll('micro:bit')`` - - :param text: The string to scroll. If ``text`` is an integer or float it is first converted to a string using ``str()``. - :param delay: The ``delay`` parameter controls how fast the text is scrolling. - :param wait: If ``wait`` is ``True``, this function will block until the animation is finished, otherwise the animation will happen in the background. - :param loop: If ``loop`` is ``True``, the animation will repeat forever. - :param monospace: 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. - - The ``wait``, ``loop`` and ``monospace`` arguments must be specified - using their keyword. - """ +def scroll(text: Union[str, float, int], delay: int=150, wait: bool=True, loop: bool=False, monospace: bool=False) -> None: + """Scrollt eine Zahl oder einen Text auf dem LED-Display. + +Example: ``display.scroll('micro:bit')`` + +:param text: Die zu scrollende Zeichenkette. Wenn ``text`` ein Integer oder Float ist, wird der Text vorher mit ``str()`` in einen String umgewandelt. +:param delay: Der Parameter ``delay`` bestimmt, wie schnell der Text gescrollt wird. +:param wait: Wenn ``wait`` ``True`` ist, wird diese Funktion das Programm anhalten, bis die Animation beendet ist, andernfalls läuft die Animation im Hintergrund ab. +:param loop: Wenn ``loop`` ``True`` ist, wird die Animation endlos wiederholt. +:param monospace: Wenn ``monospace`` ``True``ist, werden alle Zeichen 5 Pixel breit sein. Zwischen den Zeichen gibt es beim scrollen genau 1 leere Pixelspalte. + +The ``wait``, ``loop`` and ``monospace`` arguments must be specified +using their keyword.""" ... def on() -> None: - """Turn on the LED display. + """Schaltet das LED-Display ein. - Example: ``display.on()`` - """ +Example: ``display.on()``""" ... def off() -> None: - """Turn off the LED display (disabling the display allows you to re-use the GPIO pins for other purposes). + """Schaltet das LED-Display aus (Deaktivieren des Displays ermöglicht es dir, die GPIO-Pins für andere Zwecke zu verwenden). - Example: ``display.off()`` - """ +Example: ``display.off()``""" ... def is_on() -> bool: - """Check whether the LED display is enabled. + """Überprüft, ob die LED-Anzeige aktiviert ist. - Example: ``display.is_on()`` +Example: ``display.is_on()`` - :return: ``True`` if the display is on, otherwise returns ``False``. - """ +:return: ``True`` if the display is on, otherwise returns ``False``.""" ... def read_light_level() -> int: - """Read the light level. + """Bestimmt die Lichtintensität. - Example: ``display.read_light_level()`` +Example: ``display.read_light_level()`` - Uses the display's LEDs in reverse-bias mode to sense the amount of light - falling on the display. +Uses the display's LEDs in reverse-bias mode to sense the amount of light +falling on the display. - :return: An integer between 0 and 255 representing the light level, with larger meaning more light. - """ - ... +:return: An integer between 0 and 255 representing the light level, with larger meaning more light.""" + ... \ No newline at end of file diff --git a/lang/de/typeshed/stdlib/microbit/i2c.pyi b/lang/de/typeshed/stdlib/microbit/i2c.pyi index df26efa..401e1a3 100644 --- a/lang/de/typeshed/stdlib/microbit/i2c.pyi +++ b/lang/de/typeshed/stdlib/microbit/i2c.pyi @@ -1,57 +1,49 @@ -"""Communicate with devices using the I²C bus protocol. -""" - +"""Kommunikation mit Geräten über das I2C-Busprotokoll.""" from _typeshed import ReadableBuffer from ..microbit import MicroBitDigitalPin, pin19, pin20 from typing import List -def init( - freq: int = 100000, sda: MicroBitDigitalPin = pin20, scl: MicroBitDigitalPin = pin19 -) -> None: - """Re-initialize a peripheral. +def init(freq: int=100000, sda: MicroBitDigitalPin=pin20, scl: MicroBitDigitalPin=pin19) -> None: + """Eine Peripherie neu initialisieren. - Example: ``i2c.init()`` +Example: ``i2c.init()`` - :param freq: clock frequency - :param sda: ``sda`` pin (default 20) - :param scl: ``scl`` pin (default 19) +:param freq: Taktfrequenz +:param sda: ``sda`` Pin (standardmäßig 20) +:param scl: ``scl`` Pin (standardmäßig 19) - On a micro:bit V1 board, changing the I²C pins from defaults will make - the accelerometer and compass stop working, as they are connected - internally to those pins. This warning does not apply to the **V2** - revision of the micro:bit as this has `separate I²C lines `_ - for the motion sensors and the edge connector. - """ +On a micro:bit V1 board, changing the I²C pins from defaults will make +the accelerometer and compass stop working, as they are connected +internally to those pins. This warning does not apply to the **V2** +revision of the micro:bit as this has `separate I²C lines `_ +for the motion sensors and the edge connector.""" ... def scan() -> List[int]: - """Scan the bus for devices. + """Scannt den Bus nach Geräten. - Example: ``i2c.scan()`` +Example: ``i2c.scan()`` - :return: A list of 7-bit addresses corresponding to those devices that responded to the scan. - """ +:return: A list of 7-bit addresses corresponding to those devices that responded to the scan.""" ... -def read(addr: int, n: int, repeat: bool = False) -> bytes: - """Read bytes from a device. +def read(addr: int, n: int, repeat: bool=False) -> bytes: + """Liest Bytes von einem Gerät.. - Example: ``i2c.read(0x50, 64)`` +Example: ``i2c.read(0x50, 64)`` - :param addr: The 7-bit address of the device - :param n: The number of bytes to read - :param repeat: If ``True``, no stop bit will be sent - :return: The bytes read - """ +:param addr: Die 7-Bit-Adresse des Geräts +:param n: Die Anzahl der zu lesenden Bytes +:param repeat: (wiederholen) Wenn ``True``wird kein Stop-Bit gesendet +:return: The bytes read""" ... -def write(addr: int, buf: ReadableBuffer, repeat: bool = False) -> None: - """Write bytes to a device. +def write(addr: int, buf: ReadableBuffer, repeat: bool=False) -> None: + """Schreibt Bytes auf ein Gerät. (schreiben) - Example: ``i2c.write(0x50, bytes([1, 2, 3]))`` +Example: ``i2c.write(0x50, bytes([1, 2, 3]))`` - :param addr: The 7-bit address of the device - :param buf: A buffer containing the bytes to write - :param repeat: If ``True``, no stop bit will be sent - """ - ... +:param addr: Die 7-Bit-Adresse des Geräts +:param buf: Ein Puffer mit den zu schreibenden Bytes +:param repeat: (wiederholen) Wenn ``True``wird kein Stop-Bit gesendet""" + ... \ No newline at end of file diff --git a/lang/de/typeshed/stdlib/microbit/microphone.pyi b/lang/de/typeshed/stdlib/microbit/microphone.pyi index 68e8f3a..e932ee3 100644 --- a/lang/de/typeshed/stdlib/microbit/microphone.pyi +++ b/lang/de/typeshed/stdlib/microbit/microphone.pyi @@ -1,70 +1,62 @@ -"""Respond to sound using the built-in microphone (V2 only). -""" - +"""Reagiere auf Ton mithilfe des integrierten Mikrofons (nur V2). (Mikrofon)""" from typing import Optional, Tuple from ..microbit import SoundEvent def current_event() -> Optional[SoundEvent]: - """Get the last recorded sound event + """Abrufen des letzten aufgezeichneten Sound-Ereignisses - Example: ``microphone.current_event()`` +Example: ``microphone.current_event()`` - :return: The event, ``SoundEvent('loud')`` or ``SoundEvent('quiet')``. - """ +:return: The event, ``SoundEvent('loud')`` or ``SoundEvent('quiet')``.""" ... def was_event(event: SoundEvent) -> bool: - """Check if a sound was heard at least once since the last call. + """Überprüft, ob seit dem letzten Anruf mindestens einmal ein Geräusch gehört wurde. - Example: ``microphone.was_event(SoundEvent.LOUD)`` +Example: ``microphone.was_event(SoundEvent.LOUD)`` - This call clears the sound history before returning. +This call clears the sound history before returning. - :param event: The event to check for, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET`` - :return: ``True`` if sound was heard at least once since the last call, otherwise ``False``. - """ +:param event: Das Ereignis, auf das geprüft werden soll, z. B. ``SoundEvent.LOUD`` oder ``SoundEvent.QUIET`` +:return: ``True`` if sound was heard at least once since the last call, otherwise ``False``.""" ... def is_event(event: SoundEvent) -> bool: - """Check the most recent sound event detected. + """Überprüft das zuletzt erkannte Sound-Ereignis. - Example: ``microphone.is_event(SoundEvent.LOUD)`` +Example: ``microphone.is_event(SoundEvent.LOUD)`` - This call does not clear the sound event history. +This call does not clear the sound event history. - :param event: The event to check for, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET`` - :return: ``True`` if sound was the most recent heard, ``False`` otherwise. - """ +:param event: Das Ereignis, auf das geprüft werden soll, z. B. ``SoundEvent.LOUD`` oder ``SoundEvent.QUIET`` +:return: ``True`` if sound was the most recent heard, ``False`` otherwise.""" ... def get_events() -> Tuple[SoundEvent, ...]: - """Get the sound event history as a tuple. + """Liefert den Verlauf der Sound-Ereignisse in Form eines Tupels. - Example: ``microphone.get_events()`` +Example: ``microphone.get_events()`` - This call clears the sound history before returning. +This call clears the sound history before returning. - :return: A tuple of the event history with the most recent event last. - """ +:return: A tuple of the event history with the most recent event last.""" ... def set_threshold(event: SoundEvent, value: int) -> None: - """Set the threshold for a sound event. + """Legt den Schwellenwert für ein Sound-Ereignis fest. - Example: ``microphone.set_threshold(SoundEvent.LOUD, 250)`` +Example: ``microphone.set_threshold(SoundEvent.LOUD, 250)`` - A high threshold means the event will only trigger if the sound is very loud (>= 250 in the example). +A high threshold means the event will only trigger if the sound is very loud (>= 250 in the example). - :param event: A sound event, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET``. - :param value: The threshold level in the range 0-255. - """ +:param event: Ein Sound-Ereignis, wie ``SoundEvent.LOUD`` oder ``SoundEvent.QUIET``. +:param value: (wert) Der Schwellenwert im Bereich 0-255.""" ... def sound_level() -> int: - """Get the sound pressure level. + """Ermittelt den Schalldruckpegel. (Lautstärke) - Example: ``microphone.sound_level()`` +Example: ``microphone.sound_level()`` - :return: A representation of the sound pressure level in the range 0 to 255. - """ - ... +:return: A representation of the sound pressure level in the range 0 to 255.""" + ... \ No newline at end of file diff --git a/lang/de/typeshed/stdlib/microbit/speaker.pyi b/lang/de/typeshed/stdlib/microbit/speaker.pyi index 5a74a4d..228cef0 100644 --- a/lang/de/typeshed/stdlib/microbit/speaker.pyi +++ b/lang/de/typeshed/stdlib/microbit/speaker.pyi @@ -1,18 +1,15 @@ -"""Control the built-in speaker (V2 only). -""" +"""Steuere den integrierten Lautsprecher (nur V2). (Lautsprecher)""" def off() -> None: - """Turn the speaker off. + """Schaltet den Lautsprecher aus. - Example: ``speaker.off()`` +Example: ``speaker.off()`` - This does not disable sound output to an edge connector pin. - """ +This does not disable sound output to an edge connector pin.""" ... def on() -> None: - """Turn the speaker on. + """Schaltet den Lautsprecher ein. - Example: ``speaker.on()`` - """ - ... +Example: ``speaker.on()``""" + ... \ No newline at end of file diff --git a/lang/de/typeshed/stdlib/microbit/spi.pyi b/lang/de/typeshed/stdlib/microbit/spi.pyi index 09c4046..d5342ea 100644 --- a/lang/de/typeshed/stdlib/microbit/spi.pyi +++ b/lang/de/typeshed/stdlib/microbit/spi.pyi @@ -1,60 +1,47 @@ -"""Communicate with devices using the serial peripheral interface (SPI) bus. -""" - +"""Kommunikation mit Geräten über die serielle Schnittstelle (SPI).""" from _typeshed import ReadableBuffer, WriteableBuffer from ..microbit import pin13, pin14, pin15, MicroBitDigitalPin -def init( - baudrate: int = 1000000, - bits: int = 8, - mode: int = 0, - sclk: MicroBitDigitalPin = pin13, - mosi: MicroBitDigitalPin = pin15, - miso: MicroBitDigitalPin = pin14, -) -> None: - """Initialize SPI communication. - - Example: ``spi.init()`` - - For correct communication, the parameters have to be the same on both communicating devices. - - :param baudrate: The speed of communication. - :param bits: The width in bits of each transfer. Currently only ``bits=8`` is supported. However, this may change in the future. - :param mode: Determines the combination of clock polarity and phase - `see online table `_. - :param sclk: sclk pin (default 13) - :param mosi: mosi pin (default 15) - :param miso: miso pin (default 14) - """ +def init(baudrate: int=1000000, bits: int=8, mode: int=0, sclk: MicroBitDigitalPin=pin13, mosi: MicroBitDigitalPin=pin15, miso: MicroBitDigitalPin=pin14) -> None: + """SPI-Kommunikation initialisieren. + +Example: ``spi.init()`` + +For correct communication, the parameters have to be the same on both communicating devices. + +:param baudrate: Die Übertragungsgeschwindigkeit. +:param bits: Die Breite in Bits jeder Übertragung. Derzeit wird nur ``bits=8`` unterstützt. Dies kann sich jedoch in Zukunft ändern. +:param mode: Legt die Kombination aus Taktpolarität und Phase fest - `siehe Online-Tabelle `_. +:param sclk: SCLK Pin (standardmäßig 13) +:param mosi: MOSI Pin (standardmäßig 15) +:param miso: miso pin (Voreinstellung 14)""" ... -def read(nbytes: int, out: int = 0) -> bytes: - """Read at most ``nbytes`` while continuously writing the single byte given by ``out``. +def read(nbytes: int, out: int=0) -> bytes: + """Bytes lesen. - Example: ``spi.read(64)`` +Example: ``spi.read(64)`` - :param nbytes: Maximum number of bytes to read. - :param out: The byte value to write (default 0). - :return: The bytes read. - """ +:param nbytes: Maximum der zu lesenden Bytes. +:param out: The byte value to write (default 0). +:return: The bytes read.""" ... def write(buffer: ReadableBuffer) -> None: - """Write bytes to the bus. + """Schreibt Bytes auf den Bus. (schreiben) - Example: ``spi.write(bytes([1, 2, 3]))`` +Example: ``spi.write(bytes([1, 2, 3]))`` - :param buffer: A buffer to read data from. - """ +:param buffer: (Puffer) Ein Puffer, von dem Daten gelesen werden.""" ... def write_readinto(out: WriteableBuffer, in_: ReadableBuffer) -> None: - """Write the ``out`` buffer to the bus and read any response into the ``in_`` buffer. + """Schreibe den ``out`` Zwischenspeicher (Buffer) auf den Bus und lies jede Antwort in den ``in_`` Buffer. - Example: ``spi.write_readinto(out_buffer, in_buffer)`` +Example: ``spi.write_readinto(out_buffer, in_buffer)`` - The length of the buffers should be the same. The buffers can be the same object. +The length of the buffers should be the same. The buffers can be the same object. - :param out: The buffer to write any response to. - :param in_: The buffer to read data from. - """ - ... +:param out: Der Puffer, in den eine Antwort geschrieben werden soll. +:param in_: Der Puffer, von dem Daten gelesen werden.""" + ... \ No newline at end of file diff --git a/lang/de/typeshed/stdlib/microbit/uart.pyi b/lang/de/typeshed/stdlib/microbit/uart.pyi index 2ab650f..0545494 100644 --- a/lang/de/typeshed/stdlib/microbit/uart.pyi +++ b/lang/de/typeshed/stdlib/microbit/uart.pyi @@ -1,96 +1,79 @@ -"""Communicate with a device using a serial interface. -""" - +"""Kommunikation mit einem Gerät über eine serielle Schnittstelle.""" from _typeshed import WriteableBuffer from ..microbit import MicroBitDigitalPin from typing import Optional, Union - ODD: int -"""Odd parity""" - +"""Ungerade Parität""" EVEN: int -"""Even parity""" - -def init( - baudrate: int = 9600, - bits: int = 8, - parity: Optional[int] = None, - stop: int = 1, - tx: Optional[MicroBitDigitalPin] = None, - rx: Optional[MicroBitDigitalPin] = None, -) -> None: - """Initialize serial communication. - - Example: ``uart.init(115200, tx=pin0, rx=pin1)`` - - :param baudrate: The speed of communication. - :param bits: The size of bytes being transmitted. micro:bit only supports 8. - :param parity: How parity is checked, ``None``, ``uart.ODD`` or ``uart.EVEN``. - :param stop: The number of stop bits, has to be 1 for micro:bit. - :param tx: Transmitting pin. - :param rx: Receiving pin. - - 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. - - For more details see `the online documentation `_. - """ +"""Gerade Parität (gerade)""" + +def init(baudrate: int=9600, bits: int=8, parity: Optional[int]=None, stop: int=1, tx: Optional[MicroBitDigitalPin]=None, rx: Optional[MicroBitDigitalPin]=None) -> None: + """Initialisiert die serielle Kommunikation. + +Example: ``uart.init(115200, tx=pin0, rx=pin1)`` + +:param baudrate: (Baudrate) Die Übertragungsgeschwindigkeit. +:param bits: (Bits) Die Größe der Bytes die übertragen werden. micro:bit unterstützt nur 8. +:param parity: (Parität) Wie Parität geprüft wird, ``None``, ``uart.ODD`` oder ``uart.EVEN``. +:param stop: (Stop) Die Anzahl der Stopbits, muss 1 für micro:bit sein. +:param tx: Sendepin. +:param rx: Empfangspin. + +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. + +For more details see `the online documentation `_.""" ... def any() -> bool: - """Check if any data is waiting. + """Überprüft, ob irgendwelche Daten warten. - Example: ``uart.any()`` +Example: ``uart.any()`` - :return: ``True`` if any data is waiting, else ``False``. - """ +:return: ``True`` if any data is waiting, else ``False``.""" ... -def read(nbytes: Optional[int] = None) -> Optional[bytes]: - """Read bytes. +def read(nbytes: Optional[int]=None) -> Optional[bytes]: + """Bytes lesen. - Example: ``uart.read()`` +Example: ``uart.read()`` - :param nbytes: If ``nbytes`` is specified then read at most that many bytes, otherwise read as many bytes as possible - :return: A bytes object or ``None`` on timeout - """ +:param nbytes: Wenn ``nbytes`` angegeben ist, werden höchstens so viele Bytes gelesen. Andernfalls werden so viele Bytes wie möglich gelesen. +:return: A bytes object or ``None`` on timeout""" ... -def readinto(buf: WriteableBuffer, nbytes: Optional[int] = None) -> Optional[int]: - """Read bytes into the ``buf``. +def readinto(buf: WriteableBuffer, nbytes: Optional[int]=None) -> Optional[int]: + """Liest Bytes in ``buf``. - Example: ``uart.readinto(input_buffer)`` +Example: ``uart.readinto(input_buffer)`` - :param buf: The buffer to write to. - :param nbytes: If ``nbytes`` is specified then read at most that many bytes, otherwise read ``len(buf)`` bytes. - :return: number of bytes read and stored into ``buf`` or ``None`` on timeout. - """ +:param buf: Der Puffer, in den geschrieben werden soll. +:param nbytes: Wenn ``nbytes`` angegeben ist, werden höchstens so viele Bytes gelesen. Andernfalls werden ``len(buf)`` Bytes gelesen. +:return: number of bytes read and stored into ``buf`` or ``None`` on timeout.""" ... def readline() -> Optional[bytes]: - """Read a line, ending in a newline character. + """Liest eine Zeile bis zu einem Zeilenumbruch. - Example: ``uart.readline()`` +Example: ``uart.readline()`` - :return: The line read or ``None`` on timeout. The newline character is included in the returned bytes. - """ +:return: The line read or ``None`` on timeout. The newline character is included in the returned bytes.""" ... def write(buf: Union[bytes, str]) -> Optional[int]: - """Write a buffer to the bus. + """Schreibt einen Puffer auf den Bus. (schreiben) - Example: ``uart.write('hello world')`` +Example: ``uart.write('hello world')`` - :param buf: A bytes object or a string. - :return: The number of bytes written, or ``None`` on timeout. +:param buf: Ein Byte-Objekt oder ein String. +:return: The number of bytes written, or ``None`` on timeout. - Examples:: +Examples:: - uart.write('hello world') - uart.write(b'hello world') - uart.write(bytes([1, 2, 3])) - """ - ... + uart.write('hello world') + uart.write(b'hello world') + uart.write(bytes([1, 2, 3]))""" + ... \ No newline at end of file diff --git a/lang/de/typeshed/stdlib/micropython.pyi b/lang/de/typeshed/stdlib/micropython.pyi index 7a6079f..3273c46 100644 --- a/lang/de/typeshed/stdlib/micropython.pyi +++ b/lang/de/typeshed/stdlib/micropython.pyi @@ -1,144 +1,131 @@ -"""MicroPython internals.""" - +"""MicroPython Grundlagen.""" from typing import Any, TypeVar, overload - -_T = TypeVar("_T") +_T = TypeVar('_T') def const(expr: _T) -> _T: - """Used to declare that the expression is a constant so that the compiler can - optimise it. + """Wird verwendet, um zu deklarieren, dass der Ausdruck eine Konstante ist, damit der Compiler ihn optimieren kann. - The use of this function should be as follows:: +The use of this function should be as follows:: - from micropython import const - CONST_X = const(123) - CONST_Y = const(2 * CONST_X + 1) + from micropython import const + CONST_X = const(123) + CONST_Y = const(2 * CONST_X + 1) - Constants declared this way are still accessible as global variables from - outside the module they are declared in. On the other hand, if a constant - begins with an underscore then it is hidden, it is not available as a - global variable, and does not take up any memory during execution. +Constants declared this way are still accessible as global variables from +outside the module they are declared in. On the other hand, if a constant +begins with an underscore then it is hidden, it is not available as a +global variable, and does not take up any memory during execution. - :param expr: A constant expression. - """ +:param expr: Ein konstant bleibender Ausdruck.""" ... @overload def opt_level() -> int: - """Get the current optimisation level for the compilation of scripts. + """Ermittelt die aktuelle Optimierungsstufe für die Kompilierung von Skripten. - Example: ``micropython.opt_level()`` +Example: ``micropython.opt_level()`` - The optimisation level controls the following compilation features: +The optimisation level controls the following compilation features: - - Assertions: at level 0 assertion statements are enabled and compiled - into the bytecode; at levels 1 and higher assertions are not compiled. +- Assertions: at level 0 assertion statements are enabled and compiled + into the bytecode; at levels 1 and higher assertions are not compiled. - - Built-in ``__debug__`` variable: at level 0 this variable expands to - True; at levels 1 and higher it expands to False. +- Built-in ``__debug__`` variable: at level 0 this variable expands to + True; at levels 1 and higher it expands to False. - - Source-code line numbers: at levels 0, 1 and 2 source-code line number - are stored along with the bytecode so that exceptions can report the - line number they occurred at; at levels 3 and higher line numbers are - not stored. +- Source-code line numbers: at levels 0, 1 and 2 source-code line number + are stored along with the bytecode so that exceptions can report the + line number they occurred at; at levels 3 and higher line numbers are + not stored. - :return: An integer representing the current level. - """ +:return: An integer representing the current level.""" ... @overload def opt_level(level: int) -> None: - """Sets the optimisation level for subsequent compilation of scripts. + """Legt die Optimierungsstufe für die nachfolgende Kompilierung von Skripten fest. - Example: ``micropython.opt_level(1)`` +Example: ``micropython.opt_level(1)`` - The optimisation level controls the following compilation features: +The optimisation level controls the following compilation features: - - Assertions: at level 0 assertion statements are enabled and compiled - into the bytecode; at levels 1 and higher assertions are not compiled. +- Assertions: at level 0 assertion statements are enabled and compiled + into the bytecode; at levels 1 and higher assertions are not compiled. - - Built-in ``__debug__`` variable: at level 0 this variable expands to - True; at levels 1 and higher it expands to False. +- Built-in ``__debug__`` variable: at level 0 this variable expands to + True; at levels 1 and higher it expands to False. - - Source-code line numbers: at levels 0, 1 and 2 source-code line number - are stored along with the bytecode so that exceptions can report the - line number they occurred at; at levels 3 and higher line numbers are - not stored. +- Source-code line numbers: at levels 0, 1 and 2 source-code line number + are stored along with the bytecode so that exceptions can report the + line number they occurred at; at levels 3 and higher line numbers are + not stored. - The default optimisation level is usually level 0. +The default optimisation level is usually level 0. - :param level: An integer optimisation level. - """ +:param level: Eine ganzzahlige Optimierungsstufe.""" ... -def mem_info(verbose: Any = None) -> None: - """Print information about currently used memory. +def mem_info(verbose: Any=None) -> None: + """Gibt Informationen über den aktuell verwendeten Speicher zurück. - Example: ``micropython.mem_info()`` +Example: ``micropython.mem_info()`` - :param verbose: If the ``verbose`` argument is given then extra information is printed. - """ +:param verbose: Wenn das Argument ``verbose`` angegeben wird, werden zusätzliche Informationen ausgegeben.""" ... -def qstr_info(verbose: Any = None) -> None: - """Print information about currently interned strings. +def qstr_info(verbose: Any=None) -> None: + """Gibt Informationen zu aktuell eingebetteten Strings zurück. - Example: ``micropython.qstr_info()`` +Example: ``micropython.qstr_info()`` - :param verbose: If the ``verbose`` argument is given then extra information is printed. +:param verbose: Wenn das Argument ``verbose`` angegeben wird, werden zusätzliche Informationen ausgegeben. - The information that is printed is implementation dependent, but currently - includes the number of interned strings and the amount of RAM they use. In - verbose mode it prints out the names of all RAM-interned strings. - """ +The information that is printed is implementation dependent, but currently +includes the number of interned strings and the amount of RAM they use. In +verbose mode it prints out the names of all RAM-interned strings.""" ... def stack_use() -> int: - """Return an integer representing the current amount of stack that is being - used. + """Gibt einen Integerwert zurück, der dem aktuell verwendeten Stack-Speicher entspricht. - Example: ``micropython.stack_use()`` +Example: ``micropython.stack_use()`` - The absolute value of this is not particularly useful, rather it - should be used to compute differences in stack usage at different points. +The absolute value of this is not particularly useful, rather it +should be used to compute differences in stack usage at different points. - :return: An integer representing current stack use. - """ +:return: An integer representing current stack use.""" ... def heap_lock() -> None: - """Lock the heap. + """Sperrt den Heap-Speicher. - Example: ``micropython.heap_lock()`` +Example: ``micropython.heap_lock()`` - When locked no memory allocation can occur and a ``MemoryError`` will be - raised if any heap allocation is attempted. - """ +When locked no memory allocation can occur and a ``MemoryError`` will be +raised if any heap allocation is attempted.""" ... def heap_unlock() -> None: - """Unlock the heap. + """Entsperrt den Heap-Speicher. - Example: ``micropython.heap_unlock()`` +Example: ``micropython.heap_unlock()`` - When locked no memory allocation can occur and a ``MemoryError`` will be - raised if any heap allocation is attempted. - """ +When locked no memory allocation can occur and a ``MemoryError`` will be +raised if any heap allocation is attempted.""" ... def kbd_intr(chr: int) -> None: - """Set the character that will raise a ``KeyboardInterrupt`` exception. + """Zeichen festlegen, das eine ``KeyboardInterrupt``-Exception auslöst. - Example: ``micropython.kbd_intr(-1)`` +Example: ``micropython.kbd_intr(-1)`` - :param chr: Character code to raise the interrupt or -1 to disable capture of Ctrl-C. +:param chr: Zeichencode, um den Interrupt auszulösen, oder -1, um die Erfassung von Ctrl-C zu deaktivieren. - By default this is set to 3 during script execution, corresponding to Ctrl-C. - Passing -1 to this function will disable capture of Ctrl-C, and passing 3 - will restore it. +By default this is set to 3 during script execution, corresponding to Ctrl-C. +Passing -1 to this function will disable capture of Ctrl-C, and passing 3 +will restore it. - This function can be used to prevent the capturing of Ctrl-C on the - incoming stream of characters that is usually used for the REPL, in case - that stream is used for other purposes. - """ - ... +This function can be used to prevent the capturing of Ctrl-C on the +incoming stream of characters that is usually used for the REPL, in case +that stream is used for other purposes.""" + ... \ No newline at end of file diff --git a/lang/de/typeshed/stdlib/music.pyi b/lang/de/typeshed/stdlib/music.pyi index 5f4778b..6578875 100644 --- a/lang/de/typeshed/stdlib/music.pyi +++ b/lang/de/typeshed/stdlib/music.pyi @@ -1,167 +1,128 @@ -"""Create and play melodies. -""" +"""Erstelle und spiele Lieder. (Musik)""" from typing import Optional, Tuple, Union, List - from .microbit import MicroBitDigitalPin, pin0 - DADADADUM: Tuple[str, ...] -"""Melody: the opening to Beethoven’s 5th Symphony in C minor.""" - +"""Melodie: Der Anfang von Beethovens 5. Symphonie in c-Moll. (dadadadaam)""" ENTERTAINER: Tuple[str, ...] -"""Melody: the opening fragment of Scott Joplin’s Ragtime classic “The Entertainer”.""" - +"""Melodie: Die ersten Takte des Ragtime-Klassikers „The Entertainer“ von Scott Joplin. (Entertainer)""" PRELUDE: Tuple[str, ...] -"""Melody: the opening of the first Prelude in C Major of J.S.Bach’s 48 Preludes and Fugues.""" - +"""Melodie: Beginn des ersten Präludiums in C-Dur der 48 Präludien und Fugen von J.S. Bach.""" ODE: Tuple[str, ...] -"""Melody: the “Ode to Joy” theme from Beethoven’s 9th Symphony in D minor.""" - +"""Melodie: Die „Ode an die Freude“ von Beethovens neunter Symphonie in d-Moll. (Ode)""" NYAN: Tuple[str, ...] -"""Melody: the Nyan Cat theme (http://www.nyan.cat/). +"""Melodie: Nyan-Katze (http://www.nyan.cat/). (Nyan) The composer is unknown. This is fair use for educational porpoises (as they say in New York).""" - RINGTONE: Tuple[str, ...] -"""Melody: something that sounds like a mobile phone ringtone. +"""Melodie: Etwas, das wie ein Handy-Klingelton klingt. (Klingelton) To be used to indicate an incoming message. """ - FUNK: Tuple[str, ...] -"""Melody: a funky bass line for secret agents and criminal masterminds.""" - +"""Melodie: eine funkige Basslinie für Geheimagenten und Superschurken. (Funk)""" BLUES: Tuple[str, ...] -"""Melody: a boogie-woogie 12-bar blues walking bass.""" - +"""Melodie: ein 12-taktiger Boogie-Woogie-Blues mit Walking Bass. (Blues)""" BIRTHDAY: Tuple[str, ...] -"""Melody: “Happy Birthday to You…” +"""Melodie: „Alles Gute zum Geburtstag\xa0…“ (Geburtstag) For copyright status see: http://www.bbc.co.uk/news/world-us-canada-34332853 """ - WEDDING: Tuple[str, ...] -"""Melody: the bridal chorus from Wagner’s opera “Lohengrin”.""" - +"""Melodie: der Hochzeitschor aus Wagners Oper „Lohengrin“. (Hochzeit)""" FUNERAL: Tuple[str, ...] -"""Melody: the “funeral march” otherwise known as Frédéric Chopin’s Piano Sonata No. 2 in B♭ minor, Op. 35.""" - +"""Melodie: Der „Trauermarsch“, auch bekannt als Frédéric Chopins Klaviersonate Nr. 2 in b-Moll, op. 35. (Beerdigung)""" PUNCHLINE: Tuple[str, ...] -"""Melody: a fun fragment that signifies a joke has been made.""" - +"""Melodie: ein lustiges Fragment, das anzeigt, dass ein Scherz gemacht worden ist.""" PYTHON: Tuple[str, ...] -"""Melody: John Philip Sousa’s march “Liberty Bell” aka, the theme for “Monty Python’s Flying Circus” (after which the Python programming language is named).""" - +"""Melodie: John Philip Sousas Marsch „Liberty Bell“, auch bekannt als die Titelmusik von „Monty Python's Flying Circus“ (nach dem die Programmiersprache Python benannt ist).""" BADDY: Tuple[str, ...] -"""Melody: silent movie era entrance of a baddy.""" - +"""Melodie: Auftritt eines Stummfilm-Bösewichts.""" CHASE: Tuple[str, ...] -"""Melody: silent movie era chase scene.""" - +"""Melodie: Stummfilm-Verfolgungsszene.""" BA_DING: Tuple[str, ...] -"""Melody: a short signal to indicate something has happened.""" - +"""Melodie: ein kurzes Signal, um anzuzeigen, dass etwas passiert ist.""" WAWAWAWAA: Tuple[str, ...] -"""Melody: a very sad trombone.""" - +"""Melody: Eine sehr traurige Posaune.""" JUMP_UP: Tuple[str, ...] -"""Melody: for use in a game, indicating upward movement.""" - +"""Melodie: zur Verwendung in einem Spiel, um eine Aufwärtsbewegung zu untermalen.""" JUMP_DOWN: Tuple[str, ...] -"""Melody: for use in a game, indicating downward movement.""" - +"""Melodie: zur Verwendung in einem Spiel, um eine Abwärtsbewegung zu untermalen.""" POWER_UP: Tuple[str, ...] -"""Melody: a fanfare to indicate an achievement unlocked.""" - +"""Melodie: eine Fanfare, die einen Erfolg anzeigt oder dass etwas freigeschalten wurde.""" POWER_DOWN: Tuple[str, ...] -"""Melody: a sad fanfare to indicate an achievement lost.""" +"""Melodie: eine traurige Fanfare, wenn etwas nicht geklappt hat.""" -def set_tempo(ticks: int = 4, bpm: int = 120) -> None: - """Sets the approximate tempo for playback. +def set_tempo(ticks: int=4, bpm: int=120) -> None: + """Legt das ungefähre Tempo für die Wiedergabe fest. - Example: ``music.set_tempo(bpm=120)`` +Example: ``music.set_tempo(bpm=120)`` - :param ticks: The number of ticks constituting a beat. - :param bpm: An integer determining how many beats per minute. +:param ticks: Die Anzahl der Ticks in einem Beat. +:param bpm: Ein Integerwert, der die Beats pro Minute angibt. - Suggested default values allow the following useful behaviour: +Suggested default values allow the following useful behaviour: - - music.set_tempo() – reset the tempo to default of ticks = 4, bpm = 120 - - music.set_tempo(ticks=8) – change the “definition” of a beat - - music.set_tempo(bpm=180) – just change the tempo +- music.set_tempo() – reset the tempo to default of ticks = 4, bpm = 120 +- music.set_tempo(ticks=8) – change the “definition” of a beat +- music.set_tempo(bpm=180) – just change the tempo - To work out the length of a tick in milliseconds is very simple arithmetic: - 60000/bpm/ticks_per_beat. For the default values that’s - 60000/120/4 = 125 milliseconds or 1 beat = 500 milliseconds. - """ +To work out the length of a tick in milliseconds is very simple arithmetic: +60000/bpm/ticks_per_beat. For the default values that’s +60000/120/4 = 125 milliseconds or 1 beat = 500 milliseconds.""" ... def get_tempo() -> Tuple[int, int]: - """Gets the current tempo as a tuple of integers: ``(ticks, bpm)``. + """Gibt das aktuelle Tempo als Tupel von Integerwerten zurück: ``(ticks, bpm)``. - Example: ``ticks, beats = music.get_tempo()`` +Example: ``ticks, beats = music.get_tempo()`` - :return: The temp as a tuple with two integer values, the ticks then the beats per minute. - """ +:return: The temp as a tuple with two integer values, the ticks then the beats per minute.""" ... -def play( - music: Union[str, List[str], Tuple[str, ...]], - pin: Optional[MicroBitDigitalPin] = pin0, - wait: bool = True, - loop: bool = False, -) -> None: - """Plays music. +def play(music: Union[str, List[str], Tuple[str, ...]], pin: Optional[MicroBitDigitalPin]=pin0, wait: bool=True, loop: bool=False) -> None: + """Spielt Musik. - Example: ``music.play(music.NYAN)`` +Example: ``music.play(music.NYAN)`` - :param music: music specified in `a special notation `_ - :param pin: the output pin for use with an external speaker (default ``pin0``), ``None`` for no sound. - :param wait: If ``wait`` is set to ``True``, this function is blocking. - :param loop: If ``loop`` is set to ``True``, the tune repeats until ``stop`` is called or the blocking call is interrupted. +:param music: (Musik) Musik, die in `einer speziellen Notation `_ angegeben ist +:param pin: der Ausgangspin zur Verwendung mit einem externen Lautsprecher (Voreinstellung ``pin0``), ``None`` für keinen Ton. +:param wait: Wenn ``wait`` auf ``True`` gesetzt ist, stoppt diese Funktion die weitere Codeausführung. +:param loop: Wenn ``loop`` auf ``True`` gesetzt ist, wird die Melodie wiederholt, bis ``stop`` aufgerufen oder der blockierende Aufruf unterbrochen wird. - Many built-in melodies are defined in this module. - """ +Many built-in melodies are defined in this module.""" ... -def pitch( - frequency: int, - duration: int = -1, - pin: Optional[MicroBitDigitalPin] = pin0, - wait: bool = True, -) -> None: - """Play a note. +def pitch(frequency: int, duration: int=-1, pin: Optional[MicroBitDigitalPin]=pin0, wait: bool=True) -> None: + """Musiknoten spielen (Tonhöhe) - Example: ``music.pitch(185, 1000)`` +Example: ``music.pitch(185, 1000)`` - :param frequency: An integer frequency - :param duration: A millisecond duration. If negative then sound is continuous until the next call or a call to ``stop``. - :param pin: Optional output pin (default ``pin0``). - :param wait: If ``wait`` is set to ``True``, this function is blocking. +:param frequency: (Frequenz) Eine ganzzahlige Frequenz +:param duration: (Dauer) Eine Dauer in Millisekunden. Bei negativem Wert erhält man bis zum nächsten Aufruf oder einem Aufruf von ``stop`` einen Dauerton. +:param pin: Optionaler Ausgabepin (Standard ``pin0``). +:param wait: Wenn ``wait`` auf ``True`` gesetzt ist, stoppt diese Funktion die weitere Codeausführung. - For example, if the frequency is set to 440 and the length to - 1000 then we hear a standard concert A for one second. +For example, if the frequency is set to 440 and the length to +1000 then we hear a standard concert A for one second. - You can only play one pitch on one pin at any one time. - """ +You can only play one pitch on one pin at any one time.""" ... -def stop(pin: Optional[MicroBitDigitalPin] = pin0) -> None: - """Stops all music playback on the built-in speaker and any pin outputting sound. +def stop(pin: Optional[MicroBitDigitalPin]=pin0) -> None: + """Stoppt die Musikwiedergabe über den eingebauten Lautsprecher sowie jeden Pin, der Sound ausgibt. - Example: ``music.stop()`` +Example: ``music.stop()`` - :param pin: An optional argument can be provided to specify a pin, e.g. ``music.stop(pin1)``. - """ +:param pin: Ein optionales Argument kann zur Angabe eines Pins angegeben werden, z. B. ``music.stop(pin1)``.""" def reset() -> None: - """Resets ticks, bpm, duration and octave to their default values. + """Setzt Ticks, bpm, Dauer und Oktave auf ihre Standardwerte zurück. (zurücksetzen) - Example: ``music.reset()`` +Example: ``music.reset()`` - Values: - - ``ticks = 4`` - - ``bpm = 120`` - - ``duration = 4`` - - ``octave = 4`` - """ - ... +Values: +- ``ticks = 4`` +- ``bpm = 120`` +- ``duration = 4`` +- ``octave = 4``""" + ... \ No newline at end of file diff --git a/lang/de/typeshed/stdlib/neopixel.pyi b/lang/de/typeshed/stdlib/neopixel.pyi index 2d5a749..3d9915f 100644 --- a/lang/de/typeshed/stdlib/neopixel.pyi +++ b/lang/de/typeshed/stdlib/neopixel.pyi @@ -1,82 +1,81 @@ -"""Individually addressable RGB and RGBW LED strips. -""" +"""Individuell adressierbare RGB- und RGBW-LED-Streifen.""" from .microbit import MicroBitDigitalPin from typing import Tuple class NeoPixel: - def __init__(self, pin: MicroBitDigitalPin, n: int, bpp: int = 3) -> None: - """Initialise a new strip of neopixel LEDs controlled via a pin. - Example: ``np = neopixel.NeoPixel(pin0, 8)`` + def __init__(self, pin: MicroBitDigitalPin, n: int, bpp: int=3) -> None: + """Initialisiert einen neuen Streifen von Neopixel-LEDs, die über einen Pin gesteuert werden. - To support RGBW neopixels, a third argument can be passed to - ``NeoPixel`` to indicate the number of bytes per pixel (``bpp``). - For RGBW, this is is 4 rather than the default of 3 for RGB and GRB. +Example: ``np = neopixel.NeoPixel(pin0, 8)`` - Each pixel is addressed by a position (starting from 0). Neopixels are - given RGB (red, green, blue) / RGBW (red, green, blue, white) values - between 0-255 as a tuple. For example, in RGB, ``(255,255,255)`` is - white. In RGBW, ``(255,255,255,0)`` or ``(0,0,0,255)`` is white. +To support RGBW neopixels, a third argument can be passed to +``NeoPixel`` to indicate the number of bytes per pixel (``bpp``). +For RGBW, this is is 4 rather than the default of 3 for RGB and GRB. - See `the online docs `_ for warnings and other advice. +Each pixel is addressed by a position (starting from 0). Neopixels are +given RGB (red, green, blue) / RGBW (red, green, blue, white) values +between 0-255 as a tuple. For example, in RGB, ``(255,255,255)`` is +white. In RGBW, ``(255,255,255,0)`` or ``(0,0,0,255)`` is white. - :param pin: The pin controlling the neopixel strip. - :param n: The number of neopixels in the strip. - :param bpp: Bytes per pixel. For RGBW neopixel support, pass 4 rather than the default of 3 for RGB and GRB. - """ +See `the online docs `_ for warnings and other advice. + +:param pin: Der Pin, der den Neopixelstreifen steuert. +:param n: Die Anzahl der Neopixel auf dem Streifen. +:param bpp: Bytes pro Pixel. Für die RGBW Neopixel-Unterstützung, müssen 4 statt der standardmäßigen 3 Bytes pro Pixel für RGB und GRB übergeben werden.""" ... + def clear(self) -> None: - """Clear all the pixels. + """Löscht alle Pixel. - Example: ``np.clear()`` - """ +Example: ``np.clear()``""" ... + def show(self) -> None: - """Show the pixels. + """Die Pixel anzeigen. - Example: ``np.show()`` +Example: ``np.show()`` - Must be called for any updates to become visible. - """ +Must be called for any updates to become visible.""" ... + def write(self) -> None: - """Show the pixels (micro:bit V2 only). + """Pixel anzeigen (nur micro:bit V2) (schreiben) - Example: ``np.write()`` +Example: ``np.write()`` - Must be called for any updates to become visible. +Must be called for any updates to become visible. - Equivalent to ``show``. - """ +Equivalent to ``show``.""" ... + def fill(self, colour: Tuple[int, ...]) -> None: - """Colour all pixels a given RGB/RGBW value (micro:bit V2 only). + """Färbt alle Pixel mit einem bestimmten RGB/RGBW-Wert (nur micro:bit\xa0V2). - Example: ``np.fill((0, 0, 255))`` +Example: ``np.fill((0, 0, 255))`` - :param colour: A tuple of the same length as the number of bytes per pixel (bpp). +:param colour: (Farbe) Ein Tupel mit der gleichen Länge wie die Anzahl der Bytes pro Pixel (bpp). - Use in conjunction with ``show()`` to update the neopixels. - """ +Use in conjunction with ``show()`` to update the neopixels.""" ... + def __setitem__(self, key: int, value: Tuple[int, ...]) -> None: - """Set a pixel colour. + """Eine Pixelfarbe festlegen. - Example: ``np[0] = (255, 0, 0)`` +Example: ``np[0] = (255, 0, 0)`` + +:param key: Die Pixelnummer. +:param value: (wert) Die Farbe.""" - :param key: The pixel number. - :param value: The colour. - """ def __getitem__(self, key: int) -> Tuple[int, ...]: - """Get a pixel colour. + """Eine Pixelfarbe erfassen. + +Example: ``r, g, b = np[0]`` - Example: ``r, g, b = np[0]`` +:param key: Die Pixelnummer. +:return: The colour tuple.""" - :param key: The pixel number. - :return: The colour tuple. - """ def __len__(self) -> int: - """Get length of this pixel strip. + """Liefert die Länge des Pixelstreifens. - Example: ``len(np)`` - """ +Example: ``len(np)``""" \ No newline at end of file diff --git a/lang/de/typeshed/stdlib/os.pyi b/lang/de/typeshed/stdlib/os.pyi index 2f2db77..d44a449 100644 --- a/lang/de/typeshed/stdlib/os.pyi +++ b/lang/de/typeshed/stdlib/os.pyi @@ -1,73 +1,63 @@ -"""Access the file system. -""" - +"""Auf das Dateisystem zugreifen.""" from typing import Tuple from typing import List def listdir() -> List[str]: - """List files. + """Dateien auflisten. - Example: ``os.listdir()`` +Example: ``os.listdir()`` - :return: A list of the names of all the files contained within the local - persistent on-device file system. - """ +:return: A list of the names of all the files contained within the local +persistent on-device file system.""" ... def remove(filename: str) -> None: - """Remove (delete) a file. + """Entfernt\xa0/ Löscht eine Datei. (Entfernen) - Example: ``os.remove('data.txt')`` +Example: ``os.remove('data.txt')`` - :param filename: The file to delete. +:param filename: (Dateiname) Die zu löschende Datei. - If the file does not exist an ``OSError`` exception will occur. - """ +If the file does not exist an ``OSError`` exception will occur.""" ... def size(filename: str) -> int: - """Returns the size of a file. + """Gibt die Größe einer Datei zurück - Example: ``os.size('data.txt')`` +Example: ``os.size('data.txt')`` - :param filename: The file - :return: The size in bytes. +:param filename: (Dateiname) Die Datei +:return: The size in bytes. - If the file does not exist an ``OSError`` exception will occur. - """ +If the file does not exist an ``OSError`` exception will occur.""" class uname_result(Tuple[str, str, str, str, str]): - """Result of ``os.uname()``""" + """Ergebnis von ``os.uname()``""" sysname: str - """Operating system name.""" - + """Name des Betriebssystems.""" nodename: str - """Name of machine on network (implementation-defined).""" - + """Name des Rechners im Netz (durch die Implementierung definiert). (Knotenname)""" release: str - """Operating system release.""" - + """Betriebssystemveröffentlichung. (Veröffentlichung)""" version: str - """Operating system version.""" - + """Betriebssystemversion. (Version)""" machine: str - """Hardware identifier.""" + """Hardware-Kennung. (maschine)""" def uname() -> uname_result: - """Returns information identifying the current operating system. + """Gibt Informationen zum aktuellen Betriebssystem zurück. - Example: ``os.uname()`` +Example: ``os.uname()`` - The return value is an object with five attributes: +The return value is an object with five attributes: - - ``sysname`` - operating system name - - ``nodename`` - name of machine on network (implementation-defined) - - ``release`` - operating system release - - ``version`` - operating system version - - ``machine`` - hardware identifier +- ``sysname`` - operating system name +- ``nodename`` - name of machine on network (implementation-defined) +- ``release`` - operating system release +- ``version`` - operating system version +- ``machine`` - hardware identifier - There is no underlying operating system in MicroPython. As a result the - information returned by the ``uname`` function is mostly useful for - versioning details. - """ - ... +There is no underlying operating system in MicroPython. As a result the +information returned by the ``uname`` function is mostly useful for +versioning details.""" + ... \ No newline at end of file diff --git a/lang/de/typeshed/stdlib/radio.pyi b/lang/de/typeshed/stdlib/radio.pyi index 8dd0267..99d5d61 100644 --- a/lang/de/typeshed/stdlib/radio.pyi +++ b/lang/de/typeshed/stdlib/radio.pyi @@ -1,152 +1,126 @@ -"""Communicate between micro:bits with the built-in radio. -""" - +"""Kommunikation zwischen micro:bits mit dem integrierten Funk.""" from _typeshed import WriteableBuffer from typing import Optional, Tuple - RATE_1MBIT: int -"""Constant used to indicate a throughput of 1 MBit a second.""" - +"""Konstante zur Angabe eines Durchsatzes von 1\xa0MBit pro Sekunde.""" RATE_2MBIT: int -"""Constant used to indicate a throughput of 2 MBit a second.""" +"""Konstante zur Angabe eines Durchsatzes von 2\xa0MBit pro Sekunde.""" def on() -> None: - """Turns the radio on. + """Schaltet den Funk ein. - Example: ``radio.on()`` +Example: ``radio.on()`` - This needs to be explicitly called since the radio draws power and takes - up memory that you may otherwise need. - """ +This needs to be explicitly called since the radio draws power and takes +up memory that you may otherwise need.""" ... def off() -> None: - """Turns off the radio, saving power and memory. + """Schaltet den Funk aus, um Strom und Speicherplatz zu sparen. - Example: ``radio.off()`` - """ +Example: ``radio.off()``""" ... -def config( - length: int = 32, - queue: int = 3, - channel: int = 7, - power: int = 6, - address: int = 0x75626974, - group: int = 0, - data_rate: int = RATE_1MBIT, -) -> None: - """Configures the radio. - - Example: ``radio.config(group=42)`` - - The default configuration is suitable for most use. - - :param length: (default=32) defines the maximum length, in bytes, of a message sent via the radio. - It can be up to 251 bytes long (254 - 3 bytes for S0, LENGTH and S1 preamble). - :param queue: (default=3) specifies the number of messages that can be stored on the incoming message queue. - If there are no spaces left on the queue for incoming messages, then the incoming message is dropped. - :param channel: (default=7) an integer value from 0 to 83 (inclusive) that defines an arbitrary "channel" to which the radio is tuned. - Messages will be sent via this channel and only messages received via this channel will be put onto the incoming message queue. Each step is 1MHz wide, based at 2400MHz. - :param power: (default=6) is an integer value from 0 to 7 (inclusive) to indicate the strength of signal used when broadcasting a message. - The higher the value the stronger the signal, but the more power is consumed by the device. The numbering translates to positions in the following list of dBm (decibel milliwatt) values: -30, -20, -16, -12, -8, -4, 0, 4. - :param address: (default=0x75626974) an arbitrary name, expressed as a 32-bit address, that's used to filter incoming packets at the hardware level, keeping only those that match the address you set. - The default used by other micro:bit related platforms is the default setting used here. - :param group: (default=0) an 8-bit value (0-255) used with the ``address`` when filtering messages. - Conceptually, "address" is like a house/office address and "group" is like the person at that address to which you want to send your message. - :param data_rate: (default=``radio.RATE_1MBIT``) indicates the speed at which data throughput takes place. - Can be one of the following constants defined in the ``radio`` module: ``RATE_250KBIT``, ``RATE_1MBIT`` or ``RATE_2MBIT``. - - If ``config`` is not called then the defaults described above are assumed. - """ +def config(length: int=32, queue: int=3, channel: int=7, power: int=6, address: int=1969383796, group: int=0, data_rate: int=RATE_1MBIT) -> None: + """Konfiguriert den Funk. + +Example: ``radio.config(group=42)`` + +The default configuration is suitable for most use. + +:param length: (default=32) legt die maximale Länge einer über Funk gesendeten Nachricht in Bytes fest. Sie kann bis zu 251 Bytes lang sein (254 - 3 Bytes für S0, LENGTH und S1-Präambel). +:param queue: (default=3) gibt die Anzahl der Nachrichten an, die in der Warteschlange für eingehende Nachrichten gespeichert werden können. Wenn in der Warteschlange kein Platz mehr für eingehende Nachrichten ist, wird die eingehende Nachricht verworfen. +:param channel: (default=7) ein Integer-Wert zwischen 0 und 83 (einschließlich), der einen beliebigen "Kanal" definiert, auf den der Funk eingestellt ist. +Nachrichten werden über diesen Kanal gesendet und nur Nachrichten, die über diesen Kanal empfangen werden, werden in die Warteschlange der eingehenden Nachricht aufgenommen. Jeder Schritt ist 1MHz breit, beginnend mit 2400MHz. +:param power: (default=6) ist ein ganzzahliger Wert von 0 bis 7 (einschließlich), der die Stärke des Signals angibt, das beim Senden einer Nachricht verwendet wird. Je höher der Wert, desto stärker ist das Signal, aber desto mehr Strom wird vom Gerät verbraucht. Die Nummerierung entspricht den Positionen in der folgenden Liste von dBm-Werten (Dezibel Milliwatt): -30, -20, -16, -12, -8, -4, 0, 4. +:param address: (adresse) (default=0x75626974) ein beliebiger Name, ausgedrückt als 32-Bit-Adresse, der verwendet wird, um eingehende Pakete auf der Hardware-Ebene zu filtern und nur diejenigen zu behalten, die mit der eingestellten Adresse übereinstimmen. +Die Standardeinstellung, die von anderen micro:bit-verwandten Plattformen verwendet wird, wird auch hier verwendet. +:param group: (default=0) ein 8-Bit-Wert (0-255), der zusammen mit ``address`` beim Filtern von Nachrichten verwendet wird. "address" ist wie eine Haus-/Büroadresse und "group" ist wie die Person an dieser Adresse, an die die Nachricht gesendet werden soll. +:param data_rate: (default=``radio.RATE_1MBIT``) zeigt die Geschwindigkeit an, mit der der Datendurchsatz stattfindet. +Kann eine der folgenden Konstanten sein, die im Modul ``radio`` definiert sind: ``RATE_250KBIT``, ``RATE_1MBIT`` oder ``RATE_2MBIT``. + +If ``config`` is not called then the defaults described above are assumed.""" ... def reset() -> None: - """Reset the settings to their default values. + """Setzt die Einstellungen auf ihre Standardwerte zurück. (zurücksetzen) - Example: ``radio.reset()`` +Example: ``radio.reset()`` - The defaults as as per the ``config`` function above. - """ +The defaults as as per the ``config`` function above.""" ... def send_bytes(message: bytes) -> None: - """Sends a message containing bytes. + """Sendet eine Nachricht bestehend aus Bytes. - Example: ``radio.send_bytes(b'hello')`` +Example: ``radio.send_bytes(b'hello')`` - :param message: The bytes to send. - """ +:param message: Die zu sendenden Bytes.""" ... def receive_bytes() -> Optional[bytes]: - """Receive the next incoming message on the message queue. + """Empfängt die nächste eingehende Nachricht in der Nachrichtenwarteschlange. - Example: ``radio.receive_bytes()`` +Example: ``radio.receive_bytes()`` - :return: The message bytes if any, otherwise ``None``. - """ +:return: The message bytes if any, otherwise ``None``.""" ... def receive_bytes_into(buffer: WriteableBuffer) -> Optional[int]: - """Copy the next incoming message on the message queue into a buffer. + """Kopiert die nächste eingehende Nachricht in der Nachrichtenwarteschlange in einen Puffer. - Example: ``radio.receive_bytes_info(buffer)`` +Example: ``radio.receive_bytes_info(buffer)`` - :param buffer: The target buffer. The message is truncated if larger than the buffer. - :return: ``None`` if there are no pending messages, otherwise it returns the length of the message (which might be more than the length of the buffer). - """ +:param buffer: (Puffer) Der Zielpuffer. Die Nachricht wird abgeschnitten, wenn sie größer als der Puffer ist. +:return: ``None`` if there are no pending messages, otherwise it returns the length of the message (which might be more than the length of the buffer).""" ... def send(message: str) -> None: - """Sends a message string. + """Sendet eine Nachricht als String. - Example: ``radio.send('hello')`` +Example: ``radio.send('hello')`` - This is the equivalent of ``radio.send_bytes(bytes(message, 'utf8'))`` but with ``b'\x01\x00\x01'`` - prepended to the front (to make it compatible with other platforms that target the micro:bit). +This is the equivalent of ``radio.send_bytes(bytes(message, 'utf8'))`` but with ``b'\x01\x00\x01'`` +prepended to the front (to make it compatible with other platforms that target the micro:bit). - :param message: The string to send. - """ +:param message: Der zu sendende String.""" ... def receive() -> Optional[str]: - """Works in exactly the same way as ``receive_bytes`` but returns whatever was sent. + """Funktioniert genauso wie ``receive_bytes``, gibt aber zurück, was gesendet wurde. - Example: ``radio.receive()`` +Example: ``radio.receive()`` - Equivalent to ``str(receive_bytes(), 'utf8')`` but with a check that the the first - three bytes are ``b'\x01\x00\x01'`` (to make it compatible with other platforms that - may target the micro:bit). +Equivalent to ``str(receive_bytes(), 'utf8')`` but with a check that the the first +three bytes are ``b'\x01\x00\x01'`` (to make it compatible with other platforms that +may target the micro:bit). - :return: The message with the prepended bytes stripped and converted to a string. +:return: The message with the prepended bytes stripped and converted to a string. - A ``ValueError`` exception is raised if conversion to string fails. - """ +A ``ValueError`` exception is raised if conversion to string fails.""" ... def receive_full() -> Optional[Tuple[bytes, int, int]]: - """Returns a tuple containing three values representing the next incoming message on the message queue. + """Gibt ein Tupel mit drei Werten zurück, die die nächste eingehende Nachricht in der Nachrichtenwarteschlange darstellen. - Example: ``radio.receive_full()`` +Example: ``radio.receive_full()`` - If there are no pending messages then ``None`` is returned. +If there are no pending messages then ``None`` is returned. - The three values in the tuple represent: +The three values in the tuple represent: - - the next incoming message on the message queue as bytes. - - the RSSI (signal strength): a value between 0 (strongest) and -255 (weakest) as measured in dBm. - - a microsecond timestamp: the value returned by ``time.ticks_us()`` when the message was received. +- the next incoming message on the message queue as bytes. +- the RSSI (signal strength): a value between 0 (strongest) and -255 (weakest) as measured in dBm. +- a microsecond timestamp: the value returned by ``time.ticks_us()`` when the message was received. - For example:: +For example:: - details = radio.receive_full() - if details: - msg, rssi, timestamp = details + details = radio.receive_full() + if details: + msg, rssi, timestamp = details - This function is useful for providing information needed for triangulation - and/or trilateration with other micro:bit devices. +This function is useful for providing information needed for triangulation +and/or trilateration with other micro:bit devices. - :return: ``None`` if there is no message, otherwise a tuple of length three with the bytes, strength and timestamp values. - """ - ... +:return: ``None`` if there is no message, otherwise a tuple of length three with the bytes, strength and timestamp values.""" + ... \ No newline at end of file diff --git a/lang/de/typeshed/stdlib/random.pyi b/lang/de/typeshed/stdlib/random.pyi index a2c2ef3..bf675d2 100644 --- a/lang/de/typeshed/stdlib/random.pyi +++ b/lang/de/typeshed/stdlib/random.pyi @@ -1,93 +1,80 @@ -"""Generate random numbers. -""" +"""Zufallszahlen generieren.""" from typing import TypeVar, Sequence, Union, overload def getrandbits(n: int) -> int: - """Generate an integer with ``n`` random bits. + """Erzeugt einen Integerwert mit ``n`` zufälligen Bits. - Example: ``random.getrandbits(1)`` +Example: ``random.getrandbits(1)`` - :param n: A value between 1-30 (inclusive). - """ +:param n: Ein Wert zwischen 1-30 (einschließlich).""" ... def seed(n: int) -> None: - """Initialize the random number generator. + """Initialisiert den Zufallszahlengenerator. - Example: ``random.seed(0)`` +Example: ``random.seed(0)`` - :param n: The integer seed +:param n: Der Integer-Seed - This will give you reproducibly deterministic randomness from a given starting - state (``n``). - """ +This will give you reproducibly deterministic randomness from a given starting +state (``n``).""" ... def randint(a: int, b: int) -> int: - """Choose a random integer between ``a`` and ``b`` inclusive. + """Wählt eine zufällige Ganzzahl zwischen ``a`` und ``b`` (einschließlich) aus. - Example: ``random.randint(0, 9)`` +Example: ``random.randint(0, 9)`` - :param a: Start value for the range (inclusive) - :param b: End value for the range (inclusive) +:param a: Anfangswert für den Bereich (inklusiv) +:param b: Endwert für den Bereich (inklusiv) - Alias for ``randrange(a, b + 1)``. - """ +Alias for ``randrange(a, b + 1)``.""" ... @overload def randrange(stop: int) -> int: - """Choose a randomly selected integer between zero and up to (but not - including) ``stop``. + """Wählt eine zufällige Ganzzahl zwischen Null und ``stop`` (exklusiv) aus. - Example: ``random.randrange(10)`` +Example: ``random.randrange(10)`` - :param stop: End value for the range (exclusive) - """ +:param stop: Endwert für den Bereich (exklusiv)""" ... @overload -def randrange(start: int, stop: int, step: int = 1) -> int: - """ - Choose a randomly selected element from ``range(start, stop, step)``. +def randrange(start: int, stop: int, step: int=1) -> int: + """Wählt ein zufälliges Element aus ``range(start, stop, step)``. - Example: ``random.randrange(0, 10)`` +Example: ``random.randrange(0, 10)`` - :param start: The start of the range (inclusive) - :param stop: The end of the range (exclusive) - :param step: The step. - """ +:param start: Anfang des Bereichs (inklusiv) +:param stop: Das Ende des Bereichs (exklusiv) +:param step: Schrittweite""" ... - -_T = TypeVar("_T") +_T = TypeVar('_T') def choice(seq: Sequence[_T]) -> _T: - """Choose a random element from the non-empty sequence ``seq``. + """Wählt ein zufälliges Element aus der nicht leeren Sequenz ``seq``. - Example: ``random.choice([Image.HAPPY, Image.SAD])`` +Example: ``random.choice([Image.HAPPY, Image.SAD])`` - :param seq: A sequence. +:param seq: Eine Sequenz. - If ``seq`` is empty, raises ``IndexError``. - """ +If ``seq`` is empty, raises ``IndexError``.""" ... def random() -> float: - """Generate a random floating point number in the range [0.0, 1.0). + """Erzeugt eine zufällige Fließkommazahl im Bereich [0.0, 1.0). - Example: ``random.random()`` +Example: ``random.random()`` - :return: The random floating point number - """ +:return: The random floating point number""" ... def uniform(a: float, b: float) -> float: - """ - Return a random floating point number between ``a`` and ``b`` inclusive. + """Gibt eine zufällige Fließkommazahl zwischen ``a`` und ``b`` inklusiv aus. - Example: ``random.uniform(0, 9)`` +Example: ``random.uniform(0, 9)`` - :param a: Start value for the range (inclusive) - :param b: End value for the range (inclusive) - """ - ... +:param a: Anfangswert für den Bereich (inklusiv) +:param b: Endwert für den Bereich (inklusiv)""" + ... \ No newline at end of file diff --git a/lang/de/typeshed/stdlib/speech.pyi b/lang/de/typeshed/stdlib/speech.pyi index 349d188..7f0c979 100644 --- a/lang/de/typeshed/stdlib/speech.pyi +++ b/lang/de/typeshed/stdlib/speech.pyi @@ -1,106 +1,76 @@ -"""Make the micro:bit talk, sing and make other speech like sounds. -""" - +"""Bringe den micro:bit zum Sprechen, singen und dazu, andere sprachähnliche Geräusche zu machen.""" from typing import Optional from .microbit import MicroBitDigitalPin, pin0 def translate(words: str) -> str: - """Translate English words to phonemes. + """Übersetzt englische Wörter in Sprache. - Example: ``speech.translate('hello world')`` +Example: ``speech.translate('hello world')`` - :param words: A string of English words. - :return: A string containing a best guess at the appropriate phonemes to pronounce. - The output is generated from this `text to phoneme translation table `_. +:param words: (Wörter) Ein String englischer Wörter. +:return: A string containing a best guess at the appropriate phonemes to pronounce. +The output is generated from this `text to phoneme translation table `_. - This function should be used to generate a first approximation of phonemes - that can be further hand-edited to improve accuracy, inflection and - emphasis. +This function should be used to generate a first approximation of phonemes +that can be further hand-edited to improve accuracy, inflection and +emphasis. - See `the online documentation `_ for detailed information. - """ +See `the online documentation `_ for detailed information.""" ... -def pronounce( - phonemes: str, - pitch: int = 64, - speed: int = 72, - mouth: int = 128, - throat: int = 128, - pin: Optional[MicroBitDigitalPin] = pin0, -) -> None: - """Pronounce phonemes. - - Example: ``speech.pronounce(' /HEHLOW WERLD')`` - - :param phonemes: The string of phonemes to pronounce - :param pitch: A number representing the pitch of the voice - :param speed: A number representing the speed of the voice - :param mouth: A number representing the mouth of the voice - :param throat: A number representing the throat of the voice - :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. - If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. - - Override the optional pitch, speed, mouth and throat settings to change the - timbre (quality) of the voice. - - See `the online documentation `_ for detailed information. - """ - ... +def pronounce(phonemes: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: Optional[MicroBitDigitalPin]=pin0) -> None: + """Spricht Laute aus. + +Example: ``speech.pronounce(' /HEHLOW WERLD')`` + +:param phonemes: (Phoneme) Die auszusprechende Laut als Zeichenkette. +:param pitch: (Tonhöhe) Eine Zahl, die die Tonhöhe der Stimme angibt. +:param speed: (tempo) Eine Zahl, die die Geschwindigkeit der Stimme angibt. +:param mouth: (Mund) Eine Zahl, die den Mund der Stimme repräsentiert. +:param throat: (klang) Eine Zahl, die den Klang der Stimme angibt. +:param pin: Optionales Argument, um den Ausgangspin anzugeben, kann verwendet werden, um den Standardwert von ``pin0`` zu überschreiben. Wenn wir keinen Ton über die Pins abspielen wollen, können wir ``pin=None`` verwenden. nur micro:bit V2. -def say( - words: str, - pitch: int = 64, - speed: int = 72, - mouth: int = 128, - throat: int = 128, - pin: MicroBitDigitalPin = pin0, -) -> None: - """Say English words. - - Example: ``speech.say('hello world')`` - - :param words: The string of words to say. - :param pitch: A number representing the pitch of the voice - :param speed: A number representing the speed of the voice - :param mouth: A number representing the mouth of the voice - :param throat: A number representing the throat of the voice - :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. - If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. - - The result is semi-accurate for English. Override the optional pitch, speed, - mouth and throat settings to change the timbre (quality) of the voice. - - This is a short-hand equivalent of: - ``speech.pronounce(speech.translate(words))`` - - See `the online documentation `_ for detailed information. - """ +Override the optional pitch, speed, mouth and throat settings to change the +timbre (quality) of the voice. + +See `the online documentation `_ for detailed information.""" ... -def sing( - phonemes: str, - pitch: int = 64, - speed: int = 72, - mouth: int = 128, - throat: int = 128, - pin: MicroBitDigitalPin = pin0, -) -> None: - """Sing phonemes. - - Example: ``speech.sing(' /HEHLOW WERLD')`` - - :param phonemes: The string of words to sing. - :param pitch: A number representing the pitch of the voice - :param speed: A number representing the speed of the voice - :param mouth: A number representing the mouth of the voice - :param throat: A number representing the throat of the voice - :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. - If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. - - Override the optional pitch, speed, mouth and throat settings to change - the timbre (quality) of the voice. - - See `the online documentation `_ for detailed information. - """ +def say(words: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: MicroBitDigitalPin=pin0) -> None: + """Sage englische Wörter (sage) + +Example: ``speech.say('hello world')`` + +:param words: (Wörter) Der zu sagene String +:param pitch: (Tonhöhe) Eine Zahl, die die Tonhöhe der Stimme angibt. +:param speed: (tempo) Eine Zahl, die die Geschwindigkeit der Stimme angibt. +:param mouth: (Mund) Eine Zahl, die den Mund der Stimme repräsentiert. +:param throat: (klang) Eine Zahl, die den Klang der Stimme angibt. +:param pin: Optionales Argument, um den Ausgangspin anzugeben, kann verwendet werden, um den Standardwert von ``pin0`` zu überschreiben. Wenn wir keinen Ton über die Pins abspielen wollen, können wir ``pin=None`` verwenden. nur micro:bit V2. + +The result is semi-accurate for English. Override the optional pitch, speed, +mouth and throat settings to change the timbre (quality) of the voice. + +This is a short-hand equivalent of: +``speech.pronounce(speech.translate(words))`` + +See `the online documentation `_ for detailed information.""" ... + +def sing(phonemes: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: MicroBitDigitalPin=pin0) -> None: + """Singt Laute. + +Example: ``speech.sing(' /HEHLOW WERLD')`` + +:param phonemes: (Phoneme) Der zu singende String. +:param pitch: (Tonhöhe) Eine Zahl, die die Tonhöhe der Stimme angibt. +:param speed: (tempo) Eine Zahl, die die Geschwindigkeit der Stimme angibt. +:param mouth: (Mund) Eine Zahl, die den Mund der Stimme repräsentiert. +:param throat: (klang) Eine Zahl, die den Klang der Stimme angibt. +:param pin: Optionales Argument, um den Ausgangspin anzugeben, kann verwendet werden, um den Standardwert von ``pin0`` zu überschreiben. Wenn wir keinen Ton über die Pins abspielen wollen, können wir ``pin=None`` verwenden. nur micro:bit V2. + +Override the optional pitch, speed, mouth and throat settings to change +the timbre (quality) of the voice. + +See `the online documentation `_ for detailed information.""" + ... \ No newline at end of file diff --git a/lang/de/typeshed/stdlib/struct.pyi b/lang/de/typeshed/stdlib/struct.pyi index 53b3e0b..143f24c 100644 --- a/lang/de/typeshed/stdlib/struct.pyi +++ b/lang/de/typeshed/stdlib/struct.pyi @@ -1,65 +1,56 @@ -"""Pack and unpack primitive data types. -""" - +"""Packe und entpacke primitive Datentypen. (struktur)""" from _typeshed import ReadableBuffer, WriteableBuffer from typing import Any, Tuple, Union def calcsize(fmt: str) -> int: - """Get the number of bytes needed to store the given ``fmt``. + """Rufe die Anzahl der benötigten Bytes ab, um den angegebenen ``fmt`` zu speichern. - Example: ``struct.calcsize('hf')`` +Example: ``struct.calcsize('hf')`` - :param fmt: A format string. - :return The number of bytes needed to store such a value. - """ +:param fmt: Ein Format-String. +:return The number of bytes needed to store such a value.""" ... def pack(fmt: str, v1: Any, *vn: Any) -> bytes: - """Pack values according to a format string. + """Werte nach einem Format-String packen. (packen) - Example: ``struct.pack('hf', 1, 3.1415)`` +Example: ``struct.pack('hf', 1, 3.1415)`` - :param fmt: The format string. - :param v1: The first value. - :param *vn: The remaining values. - :return A bytes object encoding the values. - """ +:param fmt: Der Formatstring +:param v1: Der erste Wert. +:param *vn: Die verbleibenden Werte. +:return A bytes object encoding the values.""" ... -def pack_into( - fmt: str, buffer: WriteableBuffer, offset: int, v1: Any, *vn: Any -) -> None: - """Pack values according to a format string. +def pack_into(fmt: str, buffer: WriteableBuffer, offset: int, v1: Any, *vn: Any) -> None: + """Werte nach einem Format-String packen. (packen in) - Example: ``struct.pack_info('hf', buffer, 1, 3.1415)`` +Example: ``struct.pack_info('hf', buffer, 1, 3.1415)`` - :param fmt: The format string. - :param buffer: The target buffer to write into. - :param offset: The offset into the buffer. May be negative to count from the end of the buffer. - :param v1: The first value. - :param *vn: The remaining values. - """ +:param fmt: Der Formatstring +:param buffer: (Puffer) Der Buffer, in den geschrieben werden soll. +:param offset: Der Offset in den Puffer. Kann negativ sein, um vom Ende des Puffers aus zu zählen. +:param v1: Der erste Wert. +:param *vn: Die verbleibenden Werte.""" ... def unpack(fmt: str, data: ReadableBuffer) -> Tuple[Any, ...]: - """Unpack data according to a format string. + """Daten nach einem Format-String entpacken. - Example: ``v1, v2 = struct.unpack('hf', buffer)`` +Example: ``v1, v2 = struct.unpack('hf', buffer)`` - :param fmt: The format string. - :param data: The data. - :return: A tuple of the unpacked values. - """ +:param fmt: Der Formatstring +:param data: (Daten) Die Daten. +:return: A tuple of the unpacked values.""" ... -def unpack_from(fmt: str, buffer: ReadableBuffer, offset: int = 0) -> Tuple: - """Unpack data from a buffer according to a format string. +def unpack_from(fmt: str, buffer: ReadableBuffer, offset: int=0) -> Tuple: + """Daten aus einem Puffer nach einem Format-String entpacken. (entpacken von) - Example: ``v1, v2 = struct.unpack_from('hf', buffer)`` +Example: ``v1, v2 = struct.unpack_from('hf', buffer)`` - :param fmt: The format string. - :param buffer: The source buffer to read from. - :param offset: The offset into the buffer. May be negative to count from the end of the buffer. - :return: A tuple of the unpacked values. - """ - ... +:param fmt: Der Formatstring +:param buffer: (Puffer) Der Quellpuffer, von dem gelesen werden soll. +:param offset: Der Offset in den Puffer. Kann negativ sein, um vom Ende des Puffers aus zu zählen. +:return: A tuple of the unpacked values.""" + ... \ No newline at end of file diff --git a/lang/de/typeshed/stdlib/sys.pyi b/lang/de/typeshed/stdlib/sys.pyi index 320bac9..de796e0 100644 --- a/lang/de/typeshed/stdlib/sys.pyi +++ b/lang/de/typeshed/stdlib/sys.pyi @@ -1,43 +1,36 @@ -"""System specific functions""" - +"""Systemspezifische Funktionen""" from typing import Any, Dict, List, NoReturn, TextIO, Tuple -def exit(retval: object = ...) -> NoReturn: - """Terminate current program with a given exit code. +def exit(retval: object=...) -> NoReturn: + """Beendet ein Programm mit dem gegeneben Exit-Code. - Example: ``sys.exit(1)`` +Example: ``sys.exit(1)`` - This function raises a ``SystemExit`` exception. If an argument is given, its - value given as an argument to ``SystemExit``. +This function raises a ``SystemExit`` exception. If an argument is given, its +value given as an argument to ``SystemExit``. - :param retval: The exit code or message. - """ +:param retval: Der Exit-Code oder die Nachricht.""" ... def print_exception(exc: Exception) -> None: - """ - Print an exception with a traceback. - - Example: ``sys.print_exception(e)`` + """Eine Ausnahme mit einem Traceback ausgeben. (Ausnahme ausgeben) - :param exc: The exception to print +Example: ``sys.print_exception(e)`` - This is simplified version of a function which appears in the - ``traceback`` module in CPython. - """ +:param exc: Die auszugebende Ausnahme +This is simplified version of a function which appears in the +``traceback`` module in CPython.""" argv: List[str] -"""A mutable list of arguments the current program was started with.""" - +"""Eine veränderbare Liste von Argumenten, mit denen das aktuelle Programm gestartet wurde.""" byteorder: str -"""The byte order of the system (``"little"`` or ``"big"``).""" +"""Die Byte-Reihenfolge des Systems (``"little"`` oder ``"big"``).""" class _implementation: name: str version: Tuple[int, int, int] - implementation: _implementation -"""Object with information about the current Python implementation. +"""Objekt mit Informationen über die aktuelle Python-Implementierung. (Implementierung) For MicroPython, it has following attributes: @@ -51,13 +44,9 @@ minimal ports). CPython mandates more attributes for this object, but the actual useful bare minimum is implemented in MicroPython. """ - maxsize: int """ -Maximum value which a native integer type can hold on the current platform, -or maximum value representable by MicroPython integer type, if it's smaller -than platform max value (that is the case for MicroPython ports without -long int support). +Maximaler Wert, den ein nativer Integer-Typ auf der aktuellen Plattform halten kann, oder maximaler Wert, der durch den MicroPython-Integer-Typ darstellbar ist, wenn er kleiner ist als der maximale Plattformwert (das ist der Fall bei MicroPython-Ports ohne "long int"-Unterstützung). This attribute is useful for detecting "bitness" of a platform (32-bit vs 64-bit, etc.). It's recommended to not compare this attribute to some @@ -77,17 +66,14 @@ value directly, but instead count number of bits in it:: # (e.g. 31) due to peculiarities described above, so use "> 16", # "> 32", "> 64" style of comparisons. """ - modules: Dict[str, Any] -"""Dictionary of loaded modules. +"""Wörterbuch der geladenen Module. (module) On some ports, it may not include builtin modules.""" - path: List[str] -"""A mutable list of directories to search for imported modules.""" - +"""Eine veränderbare Liste von Verzeichnissen zum Suchen nach importierten Modulen.""" platform: str -"""The platform that MicroPython is running on. +"""Die Plattform, auf der MicroPython läuft. (plattform) For OS/RTOS ports, this is usually an identifier of the OS, e.g. ``"linux"``. For baremetal ports it is an identifier of a board, e.g. ``"pyboard"`` for @@ -97,13 +83,11 @@ distinguish one board from another. If you need to check whether your program runs on MicroPython (vs other Python implementation), use ``sys.implementation`` instead. """ - version: str -"""Python language version that this implementation conforms to, as a string.""" - +"""Python-Sprachversion, der diese Implementierung als String entspricht. (Version)""" version_info: Tuple[int, int, int] -"""Python language version that this implementation conforms to, as a tuple of ints. +"""Python-Sprachversion, der diese Implementierung als Tuple mit Ints entspricht. (Versionsinformationen) Only the first three version numbers (major, minor, micro) are supported and they can be referenced only by index, not by name. -""" +""" \ No newline at end of file diff --git a/lang/de/typeshed/stdlib/time.pyi b/lang/de/typeshed/stdlib/time.pyi index 598c483..aa32a98 100644 --- a/lang/de/typeshed/stdlib/time.pyi +++ b/lang/de/typeshed/stdlib/time.pyi @@ -1,132 +1,111 @@ -"""Measure time and add delays to programs. -""" - +"""Miss Zeit und füge Verzögerung zu Programmen hinzu. (Zeit)""" from typing import Union def sleep(seconds: Union[int, float]) -> None: - """ - Delay a number of seconds. + """Warte eine bestimmte Zahl in Sekunden. - Example: ``time.sleep(1)`` +Example: ``time.sleep(1)`` - :param seconds: The number of seconds to sleep for. - Use a floating-point number to sleep for a fractional number of seconds. - """ +:param seconds: (sekunden) Die Anzahl der Sekunden für die der Ruhezustand angezeigt wird. +Benutze eine Gleitkommazahl für eine Bruchzahl von Sekunden.""" ... def sleep_ms(ms: int) -> None: - """ - Delay for given number of milliseconds. + """Verzögerung für die angegebene Anzahl von Millisekunden. (schlafe ms) - Example: ``time.sleep_ms(1_000_000)`` +Example: ``time.sleep_ms(1_000_000)`` - :param ms: The number of milliseconds delay (>= 0). - """ +:param ms: Die Anzahl der zu wartenden Millisekunden (>= 0).""" ... def sleep_us(us: int) -> None: - """ - Delay for given number of microseconds. + """Verzögerung für die angegebene Anzahl von Mikrosekunden. - Example: ``time.sleep_us(1000)`` +Example: ``time.sleep_us(1000)`` - :param us: The number of microseconds delay (>= 0). - """ +:param us: Die Anzahl der zu wartenden Mikrosekunden (>= 0).""" ... def ticks_ms() -> int: - """ - Get an increasing, millisecond counter with an arbitrary reference point, - that wraps around after some value. + """Holt einen ansteigenden Millisekunden-Zähler mit einem beliebigen Referenzpunkt, der nach einem bestimmten Wert weiterläuft. - Example: ``time.ticks_ms()`` +Example: ``time.ticks_ms()`` - :return: The counter value in milliseconds. - """ +:return: The counter value in milliseconds.""" ... def ticks_us() -> int: - """ - Get an increasing, microsecond counter with an arbitrary reference point, - that wraps around after some value. + """Holt einen ansteigenden Mikrosekunden-Zähler mit einem beliebigen Referenzpunkt, der nach einem bestimmten Wert weiterläuft. - Example: ``time.ticks_us()`` +Example: ``time.ticks_us()`` - :return: The counter value in microseconds. - """ +:return: The counter value in microseconds.""" ... def ticks_add(ticks: int, delta: int) -> int: - """ - Offset ticks value by a given number, which can be either positive or - negative. + """Versetzt den Tick-Wert um eine bestimmte Zahl, die entweder positiv oder negativ sein kann. - Example: ``time.ticks_add(time.ticks_ms(), 200)`` +Example: ``time.ticks_add(time.ticks_ms(), 200)`` - Given a ticks value, this function allows to calculate ticks - value delta ticks before or after it, following modular-arithmetic - definition of tick values. +Given a ticks value, this function allows to calculate ticks +value delta ticks before or after it, following modular-arithmetic +definition of tick values. - :param ticks: A ticks value - :param delta: An integer offset +:param ticks: Ein Tick-Wert +:param delta: Ein ganzzahliger Offset - Example:: +Example:: - # Find out what ticks value there was 100ms ago - print(ticks_add(time.ticks_ms(), -100)) + # Find out what ticks value there was 100ms ago + print(ticks_add(time.ticks_ms(), -100)) - # Calculate deadline for operation and test for it - deadline = ticks_add(time.ticks_ms(), 200) - while ticks_diff(deadline, time.ticks_ms()) > 0: - do_a_little_of_something() + # Calculate deadline for operation and test for it + deadline = ticks_add(time.ticks_ms(), 200) + while ticks_diff(deadline, time.ticks_ms()) > 0: + do_a_little_of_something() - # Find out TICKS_MAX used by this port - print(ticks_add(0, -1)) - """ + # Find out TICKS_MAX used by this port + print(ticks_add(0, -1))""" ... def ticks_diff(ticks1: int, ticks2: int) -> int: - """ - Measure ticks difference between values returned from - ``time.ticks_ms()`` or ``ticks_us()``, as a signed value - which may wrap around. - - Example: ``time.ticks_diff(scheduled_time, now)`` - - :param ticks1: The value to subtract from - :param ticks2: The value to subtract - - The argument order is the same as for subtraction operator, - ``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. - - ``ticks_diff()`` is designed to accommodate various usage - patterns, among them: - - Polling with timeout. In this case, the order of events is known, and you - will deal only with positive results of :func:`time.ticks_diff()`:: - - # Wait for GPIO pin to be asserted, but at most 500us - start = time.ticks_us() - while pin.value() == 0: - if time.ticks_diff(time.ticks_us(), start) > 500: - raise TimeoutError - - - Scheduling events. In this case, :func:`time.ticks_diff()` result may be - negative if an event is overdue:: - - # This code snippet is not optimized - now = time.ticks_ms() - scheduled_time = task.scheduled_time() - if ticks_diff(scheduled_time, now) > 0: - print("Too early, let's nap") - sleep_ms(ticks_diff(scheduled_time, now)) - task.run() - elif ticks_diff(scheduled_time, now) == 0: - print("Right at time!") - task.run() - elif ticks_diff(scheduled_time, now) < 0: - print("Oops, running late, tell task to run faster!") - task.run(run_faster=True) - """ - ... + """Messung der Ticks-Differenz zwischen den Werten, die von ``time.ticks_ms()`` oder ``ticks_us()`` zurückgegeben werden, als vorzeichenbehafteter Wert der umgeschlagen werden kann. + +Example: ``time.ticks_diff(scheduled_time, now)`` + +:param ticks1: Der zu subtrahierende Wert von +:param ticks2: Der zu subtrahierende Wert + +The argument order is the same as for subtraction operator, +``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. + +``ticks_diff()`` is designed to accommodate various usage +patterns, among them: + +Polling with timeout. In this case, the order of events is known, and you +will deal only with positive results of :func:`time.ticks_diff()`:: + + # Wait for GPIO pin to be asserted, but at most 500us + start = time.ticks_us() + while pin.value() == 0: + if time.ticks_diff(time.ticks_us(), start) > 500: + raise TimeoutError + + +Scheduling events. In this case, :func:`time.ticks_diff()` result may be +negative if an event is overdue:: + + # This code snippet is not optimized + now = time.ticks_ms() + scheduled_time = task.scheduled_time() + if ticks_diff(scheduled_time, now) > 0: + print("Too early, let's nap") + sleep_ms(ticks_diff(scheduled_time, now)) + task.run() + elif ticks_diff(scheduled_time, now) == 0: + print("Right at time!") + task.run() + elif ticks_diff(scheduled_time, now) < 0: + print("Oops, running late, tell task to run faster!") + task.run(run_faster=True)""" + ... \ No newline at end of file diff --git a/lang/es-es/typeshed/stdlib/gc.pyi b/lang/es-es/typeshed/stdlib/gc.pyi index 1370abf..2eb95df 100644 --- a/lang/es-es/typeshed/stdlib/gc.pyi +++ b/lang/es-es/typeshed/stdlib/gc.pyi @@ -1,73 +1,68 @@ -"""Control the garbage collector""" - +"""Controlar el recolector de basura (rb)""" from typing import overload def enable() -> None: - """Enable automatic garbage collection.""" + """Activar la recolección automática de basura. (habilitado)""" ... def disable() -> None: - """Disable automatic garbage collection. + """Desactiva la recolección automática de basura. (deshabilitar) - Heap memory can still be allocated, - and garbage collection can still be initiated manually using ``gc.collect``.""" +Heap memory can still be allocated, +and garbage collection can still be initiated manually using ``gc.collect``.""" def collect() -> None: - """Run a garbage collection.""" + """Ejecuta una recolección de basura. (recoger)""" ... def mem_alloc() -> int: - """Get the number of bytes of heap RAM that are allocated. + """Obtiene el número de bytes asignados a la RAM dinámica. (memoria asignada) - :return: The number of bytes allocated. +:return: The number of bytes allocated. - This function is MicroPython extension. - """ +This function is MicroPython extension.""" ... def mem_free() -> int: - """Get the number of bytes of available heap RAM, or -1 if this amount is not known. + """Obtiene el número de bytes de la RAM dinámica disponible o -1 si se desconoce esta cantidad. (memoria libre) - :return: The number of bytes free. +:return: The number of bytes free. - This function is MicroPython extension. - """ +This function is MicroPython extension.""" ... @overload def threshold() -> int: - """Query the additional GC allocation threshold. + """Consulta el umbral de asignación de GC (recolector de basura) adicional. (límite) - :return: The GC allocation threshold. +:return: The GC allocation threshold. - This function is a MicroPython extension. CPython has a similar - function - ``set_threshold()``, but due to different GC - implementations, its signature and semantics are different. - """ +This function is a MicroPython extension. CPython has a similar +function - ``set_threshold()``, but due to different GC +implementations, its signature and semantics are different.""" ... @overload def threshold(amount: int) -> None: - """Set the additional GC allocation threshold. - - Normally, a collection is triggered only when a new allocation - cannot be satisfied, i.e. on an out-of-memory (OOM) condition. - If this function is called, in addition to OOM, a collection - will be triggered each time after ``amount`` bytes have been - allocated (in total, since the previous time such an amount of bytes - have been allocated). ``amount`` is usually specified as less than the - full heap size, with the intention to trigger a collection earlier than when the - heap becomes exhausted, and in the hope that an early collection will prevent - excessive memory fragmentation. This is a heuristic measure, the effect - of which will vary from application to application, as well as - the optimal value of the ``amount`` parameter. - - A value of -1 means a disabled allocation threshold. - - This function is a MicroPython extension. CPython has a similar - function - ``set_threshold()``, but due to different GC - implementations, its signature and semantics are different. - - :param amount: The number of bytes after which a garbage collection should be triggered. - """ - ... + """Establece el umbral de asignación de GC (recolector de basura) adicional. (límite) + +Normally, a collection is triggered only when a new allocation +cannot be satisfied, i.e. on an out-of-memory (OOM) condition. +If this function is called, in addition to OOM, a collection +will be triggered each time after ``amount`` bytes have been +allocated (in total, since the previous time such an amount of bytes +have been allocated). ``amount`` is usually specified as less than the +full heap size, with the intention to trigger a collection earlier than when the +heap becomes exhausted, and in the hope that an early collection will prevent +excessive memory fragmentation. This is a heuristic measure, the effect +of which will vary from application to application, as well as +the optimal value of the ``amount`` parameter. + +A value of -1 means a disabled allocation threshold. + +This function is a MicroPython extension. CPython has a similar +function - ``set_threshold()``, but due to different GC +implementations, its signature and semantics are different. + +:param amount: (cantidad) Número de bytes después de los cuales se debe activar una recolección de basura.""" + ... \ No newline at end of file diff --git a/lang/es-es/typeshed/stdlib/log.pyi b/lang/es-es/typeshed/stdlib/log.pyi index c9870fa..d416a70 100644 --- a/lang/es-es/typeshed/stdlib/log.pyi +++ b/lang/es-es/typeshed/stdlib/log.pyi @@ -1,104 +1,89 @@ -"""Log data to your micro:bit V2.""" - +"""Registra datos en el micro:bit V2. (registrar)""" from typing import Literal, Mapping, Optional, Union, overload - MILLISECONDS = 1 -"""Milliseconds timestamp format.""" - +"""Formato de marca temporal en milisegundos. (milisegundos)""" SECONDS = 10 -"""Seconds timestamp format.""" - +"""Formato de marca temporal en segundos. (segundos)""" MINUTES = 600 -"""Minutes timestamp format.""" - +"""Formato de marca temporal en minutos. (minutos)""" HOURS = 36000 -"""Hours timestamp format.""" - +"""Formato de marca temporal en horas. (horas)""" DAYS = 864000 -"""Days timestamp format.""" +"""Formato de marca temporal en días. (días)""" -def set_labels( - *labels: str, timestamp: Optional[Literal[1, 10, 36000, 864000]] = SECONDS -) -> None: - """Set up the log file header. +def set_labels(*labels: str, timestamp: Optional[Literal[1, 10, 36000, 864000]]=SECONDS) -> None: + """Configura la cabecera del archivo de registro. (configurar etiquetas) - Example: ``log.set_labels('X', 'Y', 'Z', timestamp=log.MINUTES)`` +Example: ``log.set_labels('X', 'Y', 'Z', timestamp=log.MINUTES)`` - Ideally this function should be called a single time, before any data is - logged, to configure the data table header once. +Ideally this function should be called a single time, before any data is +logged, to configure the data table header once. - If a log file already exists when the program starts, or if this function - is called multiple times, it will check the labels already defined in the - log file. If this function call contains any new labels not already - present, it will generate a new header row with the additional columns. +If a log file already exists when the program starts, or if this function +is called multiple times, it will check the labels already defined in the +log file. If this function call contains any new labels not already +present, it will generate a new header row with the additional columns. - By default the first column contains a timestamp for each row. The time - unit can be selected via the timestamp argument. +By default the first column contains a timestamp for each row. The time +unit can be selected via the timestamp argument. - :param *labels: Any number of positional arguments, each corresponding to an entry in the log header. - :param timestamp: Select the timestamp unit that will be automatically added as the first column in every row. Timestamp values can be one of ``log.MILLISECONDS``, ``log.SECONDS``, ``log.MINUTES``, ``log.HOURS``, ``log.DAYS`` or ``None`` to disable the timestamp. The default value is ``log.SECONDS``. - """ +:param *labels: (*Etiquetas) Cualquier número de argumentos posicionales, cada uno correspondiente a una entrada en el encabezado del registro. +:param timestamp: (marca de tiempo) Selecciona la unidad de marca de tiempo que se añadirá automáticamente como la primera columna de cada fila. Los valores de la marca de tiempo pueden ser ``log.MILLISECONDS``, ``log.SECONDS``, ``log.MINUTES``, ``log.HOURS``, ``log.DAYS`` o ``None`` para desactivar la marca de tiempo. El valor por defecto es ``log.SECONDS``.""" ... @overload -def add( - data_dictionary: Optional[Mapping[str, Union[str, int, float]]], -) -> None: - """Add a data row to the log by passing a dictionary of headers and values. +def add(data_dictionary: Optional[Mapping[str, Union[str, int, float]]]) -> None: + """Añade una fila de datos al registro pasando un diccionario de cabeceras y valores. (añadir) - Example: ``log.add({ 'temp': temperature() })`` +Example: ``log.add({ 'temp': temperature() })`` - Each call to this function adds a row to the log. +Each call to this function adds a row to the log. - New labels not previously specified via the set_labels function, or by a - previous call to this function, will trigger a new header entry to be added - to the log with the extra labels. +New labels not previously specified via the set_labels function, or by a +previous call to this function, will trigger a new header entry to be added +to the log with the extra labels. - Labels previously specified and not present in a call to this function will - be skipped with an empty value in the log row. +Labels previously specified and not present in a call to this function will +be skipped with an empty value in the log row. - :param data_dictionary: The data to log as a dictionary with a key for each header. - """ +:param data_dictionary: (diccionario de datos) Los datos que se registrarán como un diccionario con una clave para cada cabecera.""" ... @overload def add(**kwargs: Union[str, int, float]) -> None: - """Add a data row to the log using keyword arguments. + """Añade una fila de datos al registro usando argumentos de palabra clave. (añadir) - Example: ``log.add(temp=temperature())`` +Example: ``log.add(temp=temperature())`` - Each call to this function adds a row to the log. +Each call to this function adds a row to the log. - New labels not previously specified via the set_labels function, or by a - previous call to this function, will trigger a new header entry to be added - to the log with the extra labels. +New labels not previously specified via the set_labels function, or by a +previous call to this function, will trigger a new header entry to be added +to the log with the extra labels. - Labels previously specified and not present in a call to this function will - be skipped with an empty value in the log row. - """ +Labels previously specified and not present in a call to this function will +be skipped with an empty value in the log row.""" ... def delete(full=False): - """Deletes the contents of the log, including headers. + """Elimina el contenido del registro, incluyendo las cabeceras. (eliminar) - Example: ``log.delete()`` +Example: ``log.delete()`` - To add the log headers again the ``set_labels`` function should to be called after this function. +To add the log headers again the ``set_labels`` function should to be called after this function. - There are two erase modes; “full” completely removes the data from the physical storage, - and “fast” invalidates the data without removing it. +There are two erase modes; “full” completely removes the data from the physical storage, +and “fast” invalidates the data without removing it. - :param full: ``True`` selects a “full” erase and ``False`` selects the “fast” erase method. - """ +:param full: (completo) ``True`` selecciona un borrador “completo” y ``False`` selecciona el método de borrado “rápido”.""" ... def set_mirroring(serial: bool): - """Configure mirroring of the data logging activity to the serial output. + """Configura la duplicación de la actividad de registro de datos en la salida serie. (configurar replicación) - Example: ``log.set_mirroring(True)`` +Example: ``log.set_mirroring(True)`` - Serial mirroring is disabled by default. When enabled, it will print to serial each row logged into the log file. +Serial mirroring is disabled by default. When enabled, it will print to serial each row logged into the log file. - :param serial: ``True`` enables mirroring data to the serial output. - """ - ... +:param serial: (serie) ``True`` habilita la reproducción de datos en la salida de serie.""" + ... \ No newline at end of file diff --git a/lang/es-es/typeshed/stdlib/machine.pyi b/lang/es-es/typeshed/stdlib/machine.pyi index 2e82f5b..fc0afb9 100644 --- a/lang/es-es/typeshed/stdlib/machine.pyi +++ b/lang/es-es/typeshed/stdlib/machine.pyi @@ -1,97 +1,84 @@ -"""Low-level utilities. -""" +"""Utilidades de bajo nivel. (máquina)""" from typing import Any from .microbit import MicroBitDigitalPin def unique_id() -> bytes: - """Get a byte string with a unique identifier of a board. + """Obtiene una cadena de bytes con un identificador único de una placa. (id único) - Example: ``machine.unique_id()`` +Example: ``machine.unique_id()`` - :return: An identifier that varies from one board instance to another. - """ +:return: An identifier that varies from one board instance to another.""" ... def reset() -> None: - """Reset the device in a manner similar to pushing the external RESET button. + """Restablece el dispositivo de una forma similar a pulsar el botón externo RESET. (restablecer) - Example: ``machine.reset()`` - """ +Example: ``machine.reset()``""" ... def freq() -> int: - """Get the CPU frequency in hertz. + """Obtiene la frecuencia de la CPU en hercios. (frec) - Example: ``machine.freq()`` +Example: ``machine.freq()`` - :return: The CPU frequency. - """ +:return: The CPU frequency.""" ... def disable_irq() -> Any: - """Disable interrupt requests. + """Desactiva las solicitudes de interrupción. (desactivar irq) - Example: ``interrupt_state = machine.disable_irq()`` +Example: ``interrupt_state = machine.disable_irq()`` - :return: the previous IRQ state which should be considered an opaque value +:return: the previous IRQ state which should be considered an opaque value - The return value should be passed to the ``enable_irq`` function to restore - interrupts to their original state. - """ +The return value should be passed to the ``enable_irq`` function to restore +interrupts to their original state.""" ... def enable_irq(state: Any) -> None: - """Re-enable interrupt requests. + """Reactiva las solicitudes de interrupción. (activar irq) - Example: ``machine.enable_irq(interrupt_state)`` +Example: ``machine.enable_irq(interrupt_state)`` - :param state: The value that was returned from the most recent call to the ``disable_irq`` function. - """ +:param state: (estado) Valor devuelto por la llamada más reciente a la función ``disable_irq``.""" ... -def time_pulse_us( - pin: MicroBitDigitalPin, pulse_level: int, timeout_us: int = 1000000 -) -> int: - """Time a pulse on a pin. +def time_pulse_us(pin: MicroBitDigitalPin, pulse_level: int, timeout_us: int=1000000) -> int: + """Cronometra el estado de un pin. (cronometrar estado us) - Example: ``time_pulse_us(pin0, 1)`` +Example: ``time_pulse_us(pin0, 1)`` - If the current input value of the pin is different to ``pulse_level``, the - function first waits until the pin input becomes equal to - ``pulse_level``, then times the duration that the pin is equal to - ``pulse_level``. If the pin is already equal to ``pulse_level`` then timing - starts straight away. +If the current input value of the pin is different to ``pulse_level``, the +function first waits until the pin input becomes equal to +``pulse_level``, then times the duration that the pin is equal to +``pulse_level``. If the pin is already equal to ``pulse_level`` then timing +starts straight away. - :param pin: The pin to use - :param pulse_level: 0 to time a low pulse or 1 to time a high pulse - :param timeout_us: A microsecond timeout - :return: The duration of the pulse in microseconds, or -1 for a timeout waiting for the level to match ``pulse_level``, or -2 on timeout waiting for the pulse to end - """ +:param pin: Pin a usar +:param pulse_level: (nivel de estado) 0 para cronometrar un estado bajo o 1 para un estado alto +:param timeout_us: (tiempo de espera us) Tiempo de espera en microsegundos +:return: The duration of the pulse in microseconds, or -1 for a timeout waiting for the level to match ``pulse_level``, or -2 on timeout waiting for the pulse to end""" ... class mem: - """The class for the ``mem8``, ``mem16`` and ``mem32`` memory views.""" + """Clase para las vistas de memoria ``mem8``, ``mem16`` y ``mem32``.""" def __getitem__(self, address: int) -> int: - """Access a value from memory. + """Accede a un valor de la memoria. (obtener elemento) - :param address: The memory address. - :return: The value at that address as an integer. - """ +:param address: (dirección) La dirección de memoria. +:return: The value at that address as an integer.""" ... + def __setitem__(self, address: int, value: int) -> None: - """Set a value at the given address. + """Establece un valor en la dirección dada. (configurar elemento) - :param address: The memory address. - :param value: The integer value to set. - """ +:param address: (dirección) La dirección de memoria. +:param value: (valor) El valor entero a establecer.""" ... - mem8: mem -"""8-bit (byte) view of memory.""" - +"""Vista de memoria de 8 bits (byte).""" mem16: mem -"""16-bit view of memory.""" - +"""Vista de memoria de 16 bits.""" mem32: mem -"""32-bit view of memory.""" +"""Vista de memoria de 32 bits.""" \ No newline at end of file diff --git a/lang/es-es/typeshed/stdlib/math.pyi b/lang/es-es/typeshed/stdlib/math.pyi index f82d4de..f76eef8 100644 --- a/lang/es-es/typeshed/stdlib/math.pyi +++ b/lang/es-es/typeshed/stdlib/math.pyi @@ -1,273 +1,246 @@ -"""Mathematical functions. -""" - +"""Funciones matemáticas. (matemáticas)""" from typing import Tuple def acos(x: float) -> float: - """Calculate the inverse cosine. + """Calcula el inverso del coseno. - Example: ``math.acos(1)`` +Example: ``math.acos(1)`` - :param x: A number - :return: The inverse cosine of ``x`` - """ +:param x: Un número +:return: The inverse cosine of ``x``""" ... def asin(x: float) -> float: - """Calculate the inverse sine. + """Calcula el inverso del seno. (asen) - Example: ``math.asin(0)`` +Example: ``math.asin(0)`` - :param x: A number - :return: The inverse sine of ``x`` - """ +:param x: Un número +:return: The inverse sine of ``x``""" ... def atan(x: float) -> float: - """Calculate the inverse tangent. + """Calcula el inverso de la tangente. - Example: ``math.atan(0)`` +Example: ``math.atan(0)`` - :param x: A number - :return: The inverse tangent of ``x`` - """ +:param x: Un número +:return: The inverse tangent of ``x``""" ... def atan2(y: float, x: float) -> float: - """Calculate the principal value of the inverse tangent of ``y/x``. + """Calcula el valor principal del inverso de la tangente de ``y/x``. - Example: ``math.atan2(0, -1)`` +Example: ``math.atan2(0, -1)`` - :param y: A number - :param x: A number - :return: The principal value of the inverse tangent of ``y/x`` - """ +:param y: Un número +:param x: Un número +:return: The principal value of the inverse tangent of ``y/x``""" ... def ceil(x: float) -> float: - """Round a number towards positive infinity. + """Redondea un número hacia el infinito positivo. (hacia arriba) - Example: ``math.ceil(0.1)`` +Example: ``math.ceil(0.1)`` - :param x: A number - :return: ``x`` rounded towards positive infinity. - """ +:param x: Un número +:return: ``x`` rounded towards positive infinity.""" ... def copysign(x: float, y: float) -> float: - """Calculate ``x`` with the sign of ``y``. + """Calcula ``x`` con el signo de ``y``. - Example: ``math.copysign(1, -1)`` +Example: ``math.copysign(1, -1)`` - :param x: A number - :param y: The source of the sign for the return value - :return: ``x`` with the sign of ``y`` - """ +:param x: Un número +:param y: Procedencia del signo para el valor que devuelve +:return: ``x`` with the sign of ``y``""" ... def cos(x: float) -> float: - """Calculate the cosine of ``x``. + """Calcula el coseno de ``x``. - Example: ``math.cos(0)`` +Example: ``math.cos(0)`` - :param x: A number - :return: The cosine of ``x`` - """ +:param x: Un número +:return: The cosine of ``x``""" ... def degrees(x: float) -> float: - """Convert radians to degrees. + """Convierte radianes a grados. (grados) - Example: ``math.degrees(2 * math.pi)`` +Example: ``math.degrees(2 * math.pi)`` - :param x: A value in radians - :return: The value converted to degrees""" +:param x: Un valor en radianes +:return: The value converted to degrees""" ... def exp(x: float) -> float: - """Calculate the exponential of ``x``. + """Calcular el exponencial de ``x``. - Example: ``math.exp(1)`` +Example: ``math.exp(1)`` - :param x: A number - :return: The exponential of ``x``. - """ +:param x: Un número +:return: The exponential of ``x``.""" ... def fabs(x: float) -> float: - """Return the absolute value of ``x``. + """Devuelve el valor absoluto de ``x``. - Example: ``math.fabs(-0.1)`` +Example: ``math.fabs(-0.1)`` - :param x: A number - :return: The absolute value of ``x`` - """ +:param x: Un número +:return: The absolute value of ``x``""" ... def floor(x: float) -> int: - """Round a number towards negative infinity. + """Redondea un número hacia el infinito negativo. (hacia abajo) - Example: ``math.floor(0.9)`` +Example: ``math.floor(0.9)`` - :param x: A number - :return: ``x`` rounded towards negative infinity. - """ +:param x: Un número +:return: ``x`` rounded towards negative infinity.""" ... def fmod(x: float, y: float) -> float: - """Calculate the remainder of ``x/y``. + """Calcula el resto de ``x/y``. - Example: ``math.fmod(10, 3)`` +Example: ``math.fmod(10, 3)`` - :param x: The numerator - :param y: The denominator - """ +:param x: El numerador +:param y: El denominador""" ... def frexp(x: float) -> Tuple[float, int]: - """Decomposes a floating-point number into its mantissa and exponent. + """Descompone un número de coma flotante en su mantisa y exponente. - Example: ``mantissa, exponent = math.frexp(2)`` +Example: ``mantissa, exponent = math.frexp(2)`` - The returned value is the tuple ``(m, e)`` such that ``x == m * 2**e`` - exactly. If ``x == 0`` then the function returns ``(0.0, 0)``, otherwise - the relation ``0.5 <= abs(m) < 1`` holds. +The returned value is the tuple ``(m, e)`` such that ``x == m * 2**e`` +exactly. If ``x == 0`` then the function returns ``(0.0, 0)``, otherwise +the relation ``0.5 <= abs(m) < 1`` holds. - :param x: A floating-point number - :return: A tuple of length two containing its mantissa then exponent - """ +:param x: Un número de coma flotante +:return: A tuple of length two containing its mantissa then exponent""" ... def isfinite(x: float) -> bool: - """Check if a value is finite. + """Comprueba si un valor es finito. (esfinito) - Example: ``math.isfinite(float('inf'))`` +Example: ``math.isfinite(float('inf'))`` - :param x: A number. - :return: ``True`` if ``x`` is finite, ``False`` otherwise. - """ +:param x: Un número. +:return: ``True`` if ``x`` is finite, ``False`` otherwise.""" ... def isinf(x: float) -> bool: - """Check if a value is infinite. + """Compruebe si un valor es infinito. (esinf) - Example: ``math.isinf(float('-inf'))`` +Example: ``math.isinf(float('-inf'))`` - :param x: A number. - :return: ``True`` if ``x`` is infinite, ``False`` otherwise. - """ +:param x: Un número. +:return: ``True`` if ``x`` is infinite, ``False`` otherwise.""" ... def isnan(x: float) -> bool: - """Check if a value is not-a-number (NaN). + """Comprueba si un valor no es un número (NaN, not-a-number en inglés). (esnan) - Example: ``math.isnan(float('nan'))`` +Example: ``math.isnan(float('nan'))`` - :param x: A number - :return: ``True`` if ``x`` is not-a-number (NaN), ``False`` otherwise.""" +:param x: Un número +:return: ``True`` if ``x`` is not-a-number (NaN), ``False`` otherwise.""" ... def ldexp(x: float, exp: int) -> float: - """Calculate ``x * (2**exp)``. + """Calcula ``x * (2**exp)``. - Example: ``math.ldexp(0.5, 2)`` +Example: ``math.ldexp(0.5, 2)`` - :param x: A number - :param exp: Integer exponent - :return: ``x * (2**exp)`` - """ +:param x: Un número +:param exp: Exponente entero +:return: ``x * (2**exp)``""" ... -def log(x: float, base: float = e) -> float: - """Calculate the logarithm of ``x`` to the given base (defaults to natural logorithm). +def log(x: float, base: float=e) -> float: + """Calcula el logaritmo de ``x`` en la base dada (por defecto, el logaritmo natural). (registrar) - Example: ``math.log(math.e)`` +Example: ``math.log(math.e)`` - With one argument, return the natural logarithm of x (to base e). +With one argument, return the natural logarithm of x (to base e). - With two arguments, return the logarithm of x to the given base, calculated as ``log(x)/log(base)``. +With two arguments, return the logarithm of x to the given base, calculated as ``log(x)/log(base)``. - :param x: A number - :param base: The base to use - :return: The natural logarithm of ``x`` - """ +:param x: Un número +:param base: La base a usar +:return: The natural logarithm of ``x``""" ... def modf(x: float) -> Tuple[float, float]: - """Calculate the fractional and integral parts of ``x``. + """Calcula la parte fraccionaria y entera de ``x``. - Example: ``fractional, integral = math.modf(1.5)`` +Example: ``fractional, integral = math.modf(1.5)`` - :param x: A number - :return: A tuple of two floats representing the fractional then integral parts of ``x``. +:param x: Un número +:return: A tuple of two floats representing the fractional then integral parts of ``x``. - Both the fractional and integral values have the same sign as ``x``. - """ +Both the fractional and integral values have the same sign as ``x``.""" ... def pow(x: float, y: float) -> float: - """Returns ``x`` to the power of ``y``. + """Devuelve ``x`` elevado a ``y``. - Example: ``math.pow(4, 0.5)`` +Example: ``math.pow(4, 0.5)`` - :param x: A number - :param y: The exponent - :return: ``x`` to the power of ``y`` - """ +:param x: Un número +:param y: El exponente +:return: ``x`` to the power of ``y``""" ... def radians(x: float) -> float: - """Convert a degrees to radians. + """Convierte grados a radianes. (radianes) - Example: ``math.radians(360)`` +Example: ``math.radians(360)`` - :param x: A value in degrees - :return: The value converted to radians - """ +:param x: Un valor en grados +:return: The value converted to radians""" ... def sin(x: float) -> float: - """Calculate the sine of ``x``. + """Calcula el seno de ``x``. (sen) - Example: ``math.sin(math.pi/2)`` +Example: ``math.sin(math.pi/2)`` - :param x: A number - :return: The sine of ``x`` - """ +:param x: Un número +:return: The sine of ``x``""" ... def sqrt(x: float) -> float: - """Calculate the square root of ``x``. + """Calcula la raíz cuadrada de ``x``. - Example: ``math.sqrt(4)`` +Example: ``math.sqrt(4)`` - :param x: A number - :return: The square root of ``x`` - """ +:param x: Un número +:return: The square root of ``x``""" ... def tan(x: float) -> float: - """Calculate the tangent of ``x``. + """Calcula la tangente de ``x``. - Example: ``math.tan(0)`` +Example: ``math.tan(0)`` - :param x: A number - :return: The tangent of ``x``. - """ +:param x: Un número +:return: The tangent of ``x``.""" ... def trunc(x: float) -> int: - """Round a number towards 0. + """Redondea un número hacia 0. - Example: ``math.trunc(-0.9)`` +Example: ``math.trunc(-0.9)`` - :param x: A number - :return: ``x`` rounded towards zero. - """ +:param x: Un número +:return: ``x`` rounded towards zero.""" ... - e: float -"""Base of the natural logarithm""" - +"""Base del logaritmo natural""" pi: float -"""The ratio of a circle's circumference to its diameter""" +"""La relación entre la longitud de una circunferencia y su diámetro""" \ No newline at end of file diff --git a/lang/es-es/typeshed/stdlib/microbit/__init__.pyi b/lang/es-es/typeshed/stdlib/microbit/__init__.pyi index f12158f..af9a99d 100644 --- a/lang/es-es/typeshed/stdlib/microbit/__init__.pyi +++ b/lang/es-es/typeshed/stdlib/microbit/__init__.pyi @@ -1,11 +1,6 @@ -"""Pins, images, sounds, temperature and volume. -""" - +"""Pines, imágenes, sonidos, temperatura y volumen.""" from typing import Any, Callable, List, Optional, Tuple, Union, overload - from _typeshed import ReadableBuffer - -# V2 only from . import accelerometer as accelerometer from . import audio as audio from . import compass as compass @@ -16,831 +11,699 @@ from . import speaker as speaker from . import spi as spi from . import uart as uart -def run_every( - callback: Optional[Callable[[], None]] = None, - days: int = 0, - h: int = 0, - min: int = 0, - s: int = 0, - ms: int = 0, -) -> Callable[[Callable[[], None]], Callable[[], None]]: - """Schedule to run a function at the interval specified by the time arguments **V2 only**. +def run_every(callback: Optional[Callable[[], None]]=None, days: int=0, h: int=0, min: int=0, s: int=0, ms: int=0) -> Callable[[Callable[[], None]], Callable[[], None]]: + """Programa la ejecución de una función en el intervalo especificado por los argumentos de tiempo **Sólo V2**. (ejecutar cada) - Example: ``run_every(my_logging, min=5)`` +Example: ``run_every(my_logging, min=5)`` - ``run_every`` can be used in two ways: +``run_every`` can be used in two ways: - As a Decorator - placed on top of the function to schedule. For example:: +As a Decorator - placed on top of the function to schedule. For example:: - @run_every(h=1, min=20, s=30, ms=50) - def my_function(): - # Do something here + @run_every(h=1, min=20, s=30, ms=50) + def my_function(): + # Do something here - As a Function - passing the callback as a positional argument. For example:: +As a Function - passing the callback as a positional argument. For example:: - def my_function(): - # Do something here - run_every(my_function, s=30) + def my_function(): + # Do something here + run_every(my_function, s=30) - Each argument corresponds to a different time unit and they are additive. - So ``run_every(min=1, s=30)`` schedules the callback every minute and a half. +Each argument corresponds to a different time unit and they are additive. +So ``run_every(min=1, s=30)`` schedules the callback every minute and a half. - When an exception is thrown inside the callback function it deschedules the - function. To avoid this you can catch exceptions with ``try/except``. +When an exception is thrown inside the callback function it deschedules the +function. To avoid this you can catch exceptions with ``try/except``. - :param callback: Function to call at the provided interval. Omit when using as a decorator. - :param days: Sets the day mark for the scheduling. - :param h: Sets the hour mark for the scheduling. - :param min: Sets the minute mark for the scheduling. - :param s: Sets the second mark for the scheduling. - :param ms: Sets the millisecond mark for the scheduling. - """ +:param callback: Función a llamar en el intervalo proporcionado. Omitir cuando se utiliza como un decorador. +:param days: (días) Configura la marca del día para la programación. +:param h: Configura la marca de la hora para la programación. +:param min: Configura la marca de los minutos para la programación. +:param s: Configura la segunda marca para la programación. +:param ms: Configura la marca de los milisegundos para la programación.""" def panic(n: int) -> None: - """Enter a panic mode. + """Entra en modo pánico (pánico) - Example: ``panic(127)`` +Example: ``panic(127)`` - :param n: An arbitrary integer <= 255 to indicate a status. +:param n: Un entero arbitrario <= 255 para indicar un estado. - Requires restart. - """ +Requires restart.""" def reset() -> None: - """Restart the board.""" - + """Reiniciar la placa. (restablecer)""" @overload def scale(value: float, from_: Tuple[float, float], to: Tuple[int, int]) -> int: - """Converts a value from a range to an integer range. + """Convierte un valor de un rango a un rango de números enteros. (escala) - Example: ``volume = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255))`` +Example: ``volume = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255))`` - For example, to convert an accelerometer X value to a speaker volume. +For example, to convert an accelerometer X value to a speaker volume. - If one of the numbers in the ``to`` parameter is a floating point - (i.e a decimal number like ``10.0``), this function will return a - floating point number. +If one of the numbers in the ``to`` parameter is a floating point +(i.e a decimal number like ``10.0``), this function will return a +floating point number. - temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0)) + temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0)) - :param value: A number to convert. - :param from_: A tuple to define the range to convert from. - :param to: A tuple to define the range to convert to. - :return: The ``value`` converted to the ``to`` range. - """ +:param value: (valor) Un número a convertir. +:param from_: (de) Una tupla para definir el rango desde el que convertir. +:param to: (a) Una tupla para definir el rango al que convertir. +:return: The ``value`` converted to the ``to`` range.""" @overload def scale(value: float, from_: Tuple[float, float], to: Tuple[float, float]) -> float: - """Converts a value from a range to a floating point range. + """Convierte un valor de un rango a un rango de punto flotante. (escala) - Example: ``temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0))`` +Example: ``temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0))`` - For example, to convert temperature from a Celsius scale to Fahrenheit. +For example, to convert temperature from a Celsius scale to Fahrenheit. - If one of the numbers in the ``to`` parameter is a floating point - (i.e a decimal number like ``10.0``), this function will return a - floating point number. - If they are both integers (i.e ``10``), it will return an integer:: +If one of the numbers in the ``to`` parameter is a floating point +(i.e a decimal number like ``10.0``), this function will return a +floating point number. +If they are both integers (i.e ``10``), it will return an integer:: - returns_int = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255)) + returns_int = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255)) - :param value: A number to convert. - :param from_: A tuple to define the range to convert from. - :param to: A tuple to define the range to convert to. - :return: The ``value`` converted to the ``to`` range. - """ +:param value: (valor) Un número a convertir. +:param from_: (de) Una tupla para definir el rango desde el que convertir. +:param to: (a) Una tupla para definir el rango al que convertir. +:return: The ``value`` converted to the ``to`` range.""" def sleep(n: float) -> None: - """Wait for ``n`` milliseconds. + """Espera ``n`` milisegundos. (dormir) - Example: ``sleep(1000)`` +Example: ``sleep(1000)`` - :param n: The number of milliseconds to wait +:param n: El número de milisegundos a esperar - One second is 1000 milliseconds, so:: +One second is 1000 milliseconds, so:: - microbit.sleep(1000) + microbit.sleep(1000) - will pause the execution for one second. - """ +will pause the execution for one second.""" def running_time() -> int: - """Get the running time of the board. + """Obtiene el tiempo de funcionamiento de la placa. (tiempo de ejecución) - :return: The number of milliseconds since the board was switched on or restarted. - """ +:return: The number of milliseconds since the board was switched on or restarted.""" def temperature() -> int: - """Get the temperature of the micro:bit in degrees Celsius.""" + """Obtiene la temperatura del micro:bit en grados Celsius. (temperatura)""" def set_volume(v: int) -> None: - """Sets the volume. + """Establece el volumen. (configurar volumen) - Example: ``set_volume(127)`` +Example: ``set_volume(127)`` - :param v: a value between 0 (low) and 255 (high). +:param v: un valor entre 0 (bajo) y 255 (alto). - Out of range values will be clamped to 0 or 255. +Out of range values will be clamped to 0 or 255. - **V2** only. - """ +**V2** only.""" ... class Button: - """The class for the buttons ``button_a`` and ``button_b``.""" + """La clase para los botones ``button_a`` y ``button_b``. (botón)""" def is_pressed(self) -> bool: - """Check if the button is pressed. + """Comprueba si el botón está pulsado. (está pulsado) - :return: ``True`` if the specified button ``button`` is pressed, and ``False`` otherwise. - """ +:return: ``True`` if the specified button ``button`` is pressed, and ``False`` otherwise.""" ... + def was_pressed(self) -> bool: - """Check if the button was pressed since the device started or the last time this method was called. + """Comprueba si el botón ha sido pulsado desde que se inció el dispositivo o desde la última vez que se llamó a este método. (ha sido pulsado) - Calling this method will clear the press state so - that the button must be pressed again before this method will return - ``True`` again. +Calling this method will clear the press state so +that the button must be pressed again before this method will return +``True`` again. - :return: ``True`` if the specified button ``button`` was pressed, and ``False`` otherwise - """ +:return: ``True`` if the specified button ``button`` was pressed, and ``False`` otherwise""" ... + def get_presses(self) -> int: - """Get the running total of button presses, and resets this total - to zero before returning. + """Obtiene el total de pulsaciones sucesivas de un botón y restablece este total +a cero. (total de pulsaciones) - :return: The number of presses since the device started or the last time this method was called - """ +:return: The number of presses since the device started or the last time this method was called""" ... - button_a: Button -"""The left button ``Button`` object.""" - +"""Objeto ``Button`` para el botón izquierdo. (botón a)""" button_b: Button -"""The right button ``Button`` object.""" +"""Objeto ``Button`` para el botón derecho. (botón b)""" class MicroBitDigitalPin: - """A digital pin. - - Some pins support analog and touch features using the ``MicroBitAnalogDigitalPin`` and ``MicroBitTouchPin`` subclasses. - """ + """Un pin digital. (pin digital microbit) +Some pins support analog and touch features using the ``MicroBitAnalogDigitalPin`` and ``MicroBitTouchPin`` subclasses.""" NO_PULL: int PULL_UP: int PULL_DOWN: int + def read_digital(self) -> int: - """Get the digital value of the pin. + """Obtiene el valor digital del pin. (lectura digital) - Example: ``value = pin0.read_digital()`` +Example: ``value = pin0.read_digital()`` - :return: 1 if the pin is high, and 0 if it's low. - """ +:return: 1 if the pin is high, and 0 if it's low.""" ... + def write_digital(self, value: int) -> None: - """Set the digital value of the pin. + """Establece el valor digital del pin. (escritura digital) - Example: ``pin0.write_digital(1)`` +Example: ``pin0.write_digital(1)`` - :param value: 1 to set the pin high or 0 to set the pin low""" +:param value: (valor) 1 para establecer valor alto en el pin o 0 para valor bajo""" ... + def set_pull(self, value: int) -> None: - """Set the pull state to one of three possible values: ``PULL_UP``, ``PULL_DOWN`` or ``NO_PULL``. + """Configura el estado "pull" con uno de los tres valores posibles: ``PULL_UP``, ``PULL_DOWN`` o ``NO_PULL``. (configurar pull) - Example: ``pin0.set_pull(pin0.PULL_UP)`` +Example: ``pin0.set_pull(pin0.PULL_UP)`` - :param value: The pull state from the relevant pin, e.g. ``pin0.PULL_UP``. - """ +:param value: (valor) El estado "pull" del pin correspondiente, p. ej., ``pin0.PULL_UP``.""" ... + def get_pull(self) -> int: - """Get the pull state on a pin. + """Obtiene el estado "pull" de un pin. (obtener pull) - Example: ``pin0.get_pull()`` +Example: ``pin0.get_pull()`` - :return: ``NO_PULL``, ``PULL_DOWN``, or ``PULL_UP`` +:return: ``NO_PULL``, ``PULL_DOWN``, or ``PULL_UP`` - These are set using the ``set_pull()`` method or automatically configured - when a pin mode requires it. - """ +These are set using the ``set_pull()`` method or automatically configured +when a pin mode requires it.""" ... + def get_mode(self) -> str: - """Returns the pin mode. + """Devuelve el modo del pin. (obtener modo) - Example: ``pin0.get_mode()`` +Example: ``pin0.get_mode()`` - When a pin is used for a specific function, like - writing a digital value, or reading an analog value, the pin mode - changes. +When a pin is used for a specific function, like +writing a digital value, or reading an analog value, the pin mode +changes. - :return: ``"unused"``, ``"analog"``, ``"read_digital"``, ``"write_digital"``, ``"display"``, ``"button"``, ``"music"``, ``"audio"``, ``"touch"``, ``"i2c"``, or ``"spi"`` - """ +:return: ``"unused"``, ``"analog"``, ``"read_digital"``, ``"write_digital"``, ``"display"``, ``"button"``, ``"music"``, ``"audio"``, ``"touch"``, ``"i2c"``, or ``"spi"``""" ... + def write_analog(self, value: int) -> None: - """Output a PWM signal on the pin, with the duty cycle proportional to ``value``. + """Envía una señal PWM al pin, con el ciclo de trabajo proporcional a ``value``. (escritura analógica) + +Example: ``pin0.write_analog(254)`` - Example: ``pin0.write_analog(254)`` +:param value: (valor) Un número entero o de coma flotante entre 0 (ciclo de trabajo de 0 %) y 1023 (100 %).""" - :param value: 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. + """Establece el período de la señal PWM enviada a ``period`` milisegundos. (configurar periodo analógico) - Example: ``pin0.set_analog_period(10)`` +Example: ``pin0.set_analog_period(10)`` + +:param period: (período) El período en milisegundos con un valor mínimo válido de 1 ms.""" - :param period: The period in milliseconds with a minimum valid value of 1ms. - """ def set_analog_period_microseconds(self, period: int) -> None: - """Set the period of the PWM signal being output to ``period`` in microseconds. + """Establece el período de la señal PWM enviada a ``period`` microsegundos. (configurar periodo analógico en microsegundos) - Example: ``pin0.set_analog_period_microseconds(512)`` +Example: ``pin0.set_analog_period_microseconds(512)`` - :param period: The period in microseconds with a minimum valid value of 256µs. - """ +:param period: (período) El período en microsegundos con un valor mínimo válido de 256 μs.""" class MicroBitAnalogDigitalPin(MicroBitDigitalPin): - """A pin with analog and digital features.""" + """Un pin con características analógicas y digitales. (pin digital y analógico microbit)""" def read_analog(self) -> int: - """Read the voltage applied to the pin. + """Lee el voltaje aplicado al pin. (lectura analógica) - Example: ``pin0.read_analog()`` +Example: ``pin0.read_analog()`` - :return: An integer between 0 (meaning 0V) and 1023 (meaning 3.3V). - """ +:return: An integer between 0 (meaning 0V) and 1023 (meaning 3.3V).""" class MicroBitTouchPin(MicroBitAnalogDigitalPin): - """A pin with analog, digital and touch features.""" - + """Un pin con características analógicas, digitales y táctiles. (pin táctil microbit)""" CAPACITIVE: int RESISTIVE: int + def is_touched(self) -> bool: - """Check if the pin is being touched. + """Comprueba si se está tocando el pin. (está tocado) - Example: ``pin0.is_touched()`` +Example: ``pin0.is_touched()`` - The default touch mode for the pins on the edge connector is ``resistive``. - The default for the logo pin **V2** is ``capacitive``. +The default touch mode for the pins on the edge connector is ``resistive``. +The default for the logo pin **V2** is ``capacitive``. - **Resistive touch** - This test is done by measuring how much resistance there is between the - pin and ground. A low resistance gives a reading of ``True``. To get - a reliable reading using a finger you may need to touch the ground pin - with another part of your body, for example your other hand. +**Resistive touch** +This test is done by measuring how much resistance there is between the +pin and ground. A low resistance gives a reading of ``True``. To get +a reliable reading using a finger you may need to touch the ground pin +with another part of your body, for example your other hand. - **Capacitive touch** - This test is done by interacting with the electric field of a capacitor - using a finger as a conductor. `Capacitive touch - `_ - does not require you to make a ground connection as part of a circuit. +**Capacitive touch** +This test is done by interacting with the electric field of a capacitor +using a finger as a conductor. `Capacitive touch +`_ +does not require you to make a ground connection as part of a circuit. - :return: ``True`` if the pin is being touched with a finger, otherwise return ``False``. - """ +:return: ``True`` if the pin is being touched with a finger, otherwise return ``False``.""" ... + def set_touch_mode(self, value: int) -> None: - """Set the touch mode for the pin. + """Establece el modo táctil del pin. (configurar modo táctil) - Example: ``pin0.set_touch_mode(pin0.CAPACITIVE)`` +Example: ``pin0.set_touch_mode(pin0.CAPACITIVE)`` - The default touch mode for the pins on the edge connector is - ``resistive``. The default for the logo pin **V2** is ``capacitive``. +The default touch mode for the pins on the edge connector is +``resistive``. The default for the logo pin **V2** is ``capacitive``. - :param value: ``CAPACITIVE`` or ``RESISTIVE`` from the relevant pin. - """ +:param value: (valor) ``CAPACITIVE`` o ``RESISTIVE`` del pin correspondiente.""" ... - pin0: MicroBitTouchPin -"""Pin with digital, analog and touch features.""" - +"""Pin con funciones digitales, analógicas y táctiles.""" pin1: MicroBitTouchPin -"""Pin with digital, analog and touch features.""" - +"""Pin con funciones digitales, analógicas y táctiles.""" pin2: MicroBitTouchPin -"""Pin with digital, analog and touch features.""" - +"""Pin con funciones digitales, analógicas y táctiles.""" pin3: MicroBitAnalogDigitalPin -"""Pin with digital and analog features.""" - +"""Pin con funciones digitales y analógicas.""" pin4: MicroBitAnalogDigitalPin -"""Pin with digital and analog features.""" - +"""Pin con funciones digitales y analógicas.""" pin5: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin con funciones digitales.""" pin6: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin con funciones digitales.""" pin7: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin con funciones digitales.""" pin8: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin con funciones digitales.""" pin9: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin con funciones digitales.""" pin10: MicroBitAnalogDigitalPin -"""Pin with digital and analog features.""" - +"""Pin con funciones digitales y analógicas.""" pin11: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin con funciones digitales.""" pin12: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin con funciones digitales.""" pin13: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin con funciones digitales.""" pin14: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin con funciones digitales.""" pin15: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin con funciones digitales.""" pin16: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin con funciones digitales.""" pin19: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin con funciones digitales.""" pin20: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin con funciones digitales.""" pin_logo: MicroBitTouchPin -"""A touch sensitive logo pin on the front of the micro:bit, which by default is set to capacitive touch mode.""" - +"""Un pin táctil sensible en la parte frontal del micro:bit que por defecto está configurado en modo táctil capacitivo. (pin de logo)""" pin_speaker: MicroBitAnalogDigitalPin -"""A pin to address the micro:bit speaker. +"""Un pin para dirigirse al altavoz micro:bit. (pin de altavoz) This API is intended only for use in Pulse-Width Modulation pin operations e.g. pin_speaker.write_analog(128). """ class Image: - """An image to show on the micro:bit LED display. + """Una imagen que se mostrará en la pantalla LED del micro:bit. (imagen) - Given an image object it's possible to display it via the ``display`` API:: - - display.show(Image.HAPPY) - """ +Given an image object it's possible to display it via the ``display`` API:: + display.show(Image.HAPPY)""" HEART: Image - """Heart image.""" - + """Imagen de un corazón. (corazón)""" HEART_SMALL: Image - """Small heart image.""" - + """Imagen de un corazón pequeño. (corazón pequeño)""" HAPPY: Image - """Happy face image.""" - + """Imagen de una cara feliz. (feliz)""" SMILE: Image - """Smiling mouth image.""" - + """Imagen de una cara sonriente. (sonrisa)""" SAD: Image - """Sad face image.""" - + """Imagen de una cara triste. (triste)""" CONFUSED: Image - """Confused face image.""" - + """Imagen de una cara confundida. (confundida)""" ANGRY: Image - """Angry face image.""" - + """Imagen de una cara enfadada. (enfadada)""" ASLEEP: Image - """Sleeping face image.""" - + """Imagen de una cara durmiendo. (dormida)""" SURPRISED: Image - """Surprised face image.""" - + """Imagen de una cara sorprendida. (sorprendida)""" SILLY: Image - """Silly face image.""" - + """Imagen de una cara tonta. (tonta)""" FABULOUS: Image - """Sunglasses face image.""" - + """Imagen de una cara con gafas de sol. (fabulosa)""" MEH: Image - """Unimpressed face image.""" - + """Imagen de una cara indiferente. (indiferente)""" YES: Image - """Tick image.""" - + """Imagen de verificación. (sí)""" NO: Image - """Cross image.""" - + """Imagen de cruz.""" CLOCK12: Image - """Image with line pointing to 12 o'clock.""" - + """Imagen de una línea apuntando a las 12:00. (reloj12)""" CLOCK11: Image - """Image with line pointing to 11 o'clock.""" - + """Imagen de una línea apuntando a las 11:00. (reloj11)""" CLOCK10: Image - """Image with line pointing to 10 o'clock.""" - + """Imagen de una línea apuntando a las 10:00. (reloj10)""" CLOCK9: Image - """Image with line pointing to 9 o'clock.""" - + """Imagen de una línea apuntando a las 9:00. (reloj9)""" CLOCK8: Image - """Image with line pointing to 8 o'clock.""" - + """Imagen de una línea apuntando a las 8:00. (reloj8)""" CLOCK7: Image - """Image with line pointing to 7 o'clock.""" - + """Imagen de una línea apuntando a las 7:00. (reloj7)""" CLOCK6: Image - """Image with line pointing to 6 o'clock.""" - + """Imagen de una línea apuntando a las 6:00. (reloj6)""" CLOCK5: Image - """Image with line pointing to 5 o'clock.""" - + """Imagen de una línea apuntando a las 5:00. (reloj5)""" CLOCK4: Image - """Image with line pointing to 4 o'clock.""" - + """Imagen de una línea apuntando a las 4:00. (reloj4)""" CLOCK3: Image - """Image with line pointing to 3 o'clock.""" - + """Imagen de una línea apuntando a las 3:00. (reloj3)""" CLOCK2: Image - """Image with line pointing to 2 o'clock.""" - + """Imagen de una línea apuntando a las 2:00. (reloj2)""" CLOCK1: Image - """Image with line pointing to 1 o'clock.""" - + """Imagen de una línea apuntando a la 1:00. (reloj1)""" ARROW_N: Image - """Image of arrow pointing north.""" - + """Imagen de una flecha apuntando hacia el norte. (flecha n)""" ARROW_NE: Image - """Image of arrow pointing north east.""" - + """Imagen de una flecha apuntando hacia el nordeste. (flecha ne)""" ARROW_E: Image - """Image of arrow pointing east.""" - + """Imagen de una flecha apuntando hacia el este. (flecha e)""" ARROW_SE: Image - """Image of arrow pointing south east.""" - + """Imagen de una flecha apuntando hacia el sudeste. (flecha se)""" ARROW_S: Image - """Image of arrow pointing south.""" - + """Imagen de una flecha apuntando hacia el sur. (flecha s)""" ARROW_SW: Image - """Image of arrow pointing south west.""" - + """Imagen de una flecha apuntando hacia el sudoeste. (flecha so)""" ARROW_W: Image - """Image of arrow pointing west.""" - + """Imagen de una flecha apuntando hacia el oeste. (flecha o)""" ARROW_NW: Image - """Image of arrow pointing north west.""" - + """Imagen de una flecha apuntando hacia el noroeste. (flecha no)""" TRIANGLE: Image - """Image of a triangle pointing up.""" - + """Imagen de un triángulo apuntando hacia arriba. (triángulo)""" TRIANGLE_LEFT: Image - """Image of a triangle in the left corner.""" - + """Imagen de un triángulo en la esquina izquierda. (triángulo izquierda)""" CHESSBOARD: Image - """Alternate LEDs lit in a chessboard pattern.""" - + """LED iluminados de forma alterna según un patrón de tablero de ajedrez. (tablero de ajedrez)""" DIAMOND: Image - """Diamond image.""" - + """Imagen de un diamante. (diamante)""" DIAMOND_SMALL: Image - """Small diamond image.""" - + """Imagen de un diamante pequeño. (diamante pequeño)""" SQUARE: Image - """Square image.""" - + """Imagen de un cuadrado. (cuadrado)""" SQUARE_SMALL: Image - """Small square image.""" - + """Imagen de un cuadrado pequeño. (cuadrado pequeño)""" RABBIT: Image - """Rabbit image.""" - + """Imagen de un conejo. (conejo)""" COW: Image - """Cow image.""" - + """Imagen de una vaca. (vaca)""" MUSIC_CROTCHET: Image - """Crotchet note image.""" - + """Imagen de una nota negra. (negra musical)""" MUSIC_QUAVER: Image - """Quaver note image.""" - + """Imagen de una nota corchea. (corchea musical)""" MUSIC_QUAVERS: Image - """Pair of quavers note image.""" - + """Imagen de un par de notas corcheas. (corcheas musicales)""" PITCHFORK: Image - """Pitchfork image.""" - + """Imagen de una horca. (horca)""" XMAS: Image - """Christmas tree image.""" - + """Imagen de un árbol de Navidad. (navidad)""" PACMAN: Image - """Pac-Man arcade character image.""" - + """Imagen del personaje de videojuegos Pac-Man.""" TARGET: Image - """Target image.""" - + """Imagen de un objetivo. (diana)""" TSHIRT: Image - """T-shirt image.""" - + """Imagen de una camiseta. (camiseta)""" ROLLERSKATE: Image - """Rollerskate image.""" - + """Imagen de un patín. (patín)""" DUCK: Image - """Duck image.""" - + """Imagen de un pato. (pato)""" HOUSE: Image - """House image.""" - + """Imagen de una casa. (casa)""" TORTOISE: Image - """Tortoise image.""" - + """Imagen de una tortuga. (tortuga)""" BUTTERFLY: Image - """Butterfly image.""" - + """Imagen de una mariposa. (mariposa)""" STICKFIGURE: Image - """Stick figure image.""" - + """Imagen de un monigote. (monigote)""" GHOST: Image - """Ghost image.""" - + """Imagen de un fantasma. (fantasma)""" SWORD: Image - """Sword image.""" - + """Imagen de una espada. (espada)""" GIRAFFE: Image - """Giraffe image.""" - + """Imagen de una jirafa. (girafa)""" SKULL: Image - """Skull image.""" - + """Imagen de una calavera. (calavera)""" UMBRELLA: Image - """Umbrella image.""" - + """Imagen de un paraguas. (paraguas)""" SNAKE: Image - """Snake image.""" - + """Imagen de una serpiente. (serpiente)""" SCISSORS: Image - """Scissors image.""" - + """Imagen de tijeras. (tijeras)""" ALL_CLOCKS: List[Image] - """A list containing all the CLOCK_ images in sequence.""" - + """Una lista que contiene todas las imágenes CLOCK_ en secuencia. (todos los relojes)""" ALL_ARROWS: List[Image] - """A list containing all the ARROW_ images in sequence.""" + """Una lista que contiene todas las imágenes ARROW_ en secuencia. (todas las flechas)""" + @overload def __init__(self, string: str) -> None: - """Create an image from a string describing which LEDs are lit. + """Crea una imagen a partir de una cadena que describe los LED que están encendidos. - ``string`` has to consist of digits 0-9 arranged into lines, - describing the image, for example:: +``string`` has to consist of digits 0-9 arranged into lines, +describing the image, for example:: - image = Image("90009:" - "09090:" - "00900:" - "09090:" - "90009") + 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 newlines (\\n) insead of the colons. +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 newlines (\\n) insead of the colons. - :param string: The string describing the image. - """ +:param string: (cadena) La cadena que describe la imagen.""" ... + @overload - def __init__( - self, width: int = 5, height: int = 5, buffer: ReadableBuffer = None - ) -> None: - """Create an empty image with ``width`` columns and ``height`` rows. + def __init__(self, width: int=5, height: int=5, buffer: ReadableBuffer=None) -> None: + """Crea una imagen vacía con ``width`` columnas y ``height`` filas. - :param width: Optional width of the image - :param height: Optional height of the image - :param buffer: Optional array or bytes of ``width``×``height`` integers in range 0-9 to initialize the image +:param width: (ancho) Ancho opcional de la imagen +:param height: (altura) Altura opcional de la imagen +:param buffer: (búfer) Matriz opcional de bytes de ``width`` × ``height`` enteros en el rango 0 - 9 para inicializar la imagen - Examples:: +Examples:: - Image(2, 2, b'\x08\x08\x08\x08') - Image(2, 2, bytearray([9,9,9,9])) + Image(2, 2, b'\x08\x08\x08\x08') + Image(2, 2, bytearray([9,9,9,9])) - These create 2 x 2 pixel images at full brightness. - """ +These create 2 x 2 pixel images at full brightness.""" ... + def width(self) -> int: - """Get the number of columns. + """Obtiene el número de columnas. (ancho) - :return: The number of columns in the image - """ +:return: The number of columns in the image""" ... + def height(self) -> int: - """Get the number of rows. + """Obtiene el número de filas. (altura) - :return: The number of rows in the image - """ +:return: The number of rows in the image""" ... + def set_pixel(self, x: int, y: int, value: int) -> None: - """Set the brightness of a pixel. + """Establece el brillo de un píxel. (configurar píxel) - Example: ``my_image.set_pixel(0, 0, 9)`` +Example: ``my_image.set_pixel(0, 0, 9)`` - :param x: The column number - :param y: The row number - :param value: The brightness as an integer between 0 (dark) and 9 (bright) +:param x: El número de columna +:param y: El número de fila +:param value: (valor) El brillo expresado como un entero entre 0 (oscuro) y 9 (brillante) - This method will raise an exception when called on any of the built-in - read-only images, like ``Image.HEART``. - """ +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: - """Get the brightness of a pixel. + """Obtiene el brillo de un píxel. (obtener píxel) - Example: ``my_image.get_pixel(0, 0)`` +Example: ``my_image.get_pixel(0, 0)`` - :param x: The column number - :param y: The row number - :return: The brightness as an integer between 0 and 9. - """ +:param x: El número de columna +:param y: El número de fila +:return: The brightness as an integer between 0 and 9.""" ... + def shift_left(self, n: int) -> Image: - """Create a new image by shifting the picture left. + """Crea una nueva imagen desplazando la imagen hacia la izquierda. (desplazamiento a la izquierda) - Example: ``Image.HEART_SMALL.shift_left(1)`` +Example: ``Image.HEART_SMALL.shift_left(1)`` - :param n: The number of columns to shift by - :return: The shifted image - """ +:param n: El número de columnas a desplazar +:return: The shifted image""" ... + def shift_right(self, n: int) -> Image: - """Create a new image by shifting the picture right. + """Crea una nueva imagen desplazando la imagen hacia la derecha. (desplazamiento a la derecha) - Example: ``Image.HEART_SMALL.shift_right(1)`` +Example: ``Image.HEART_SMALL.shift_right(1)`` - :param n: The number of columns to shift by - :return: The shifted image - """ +:param n: El número de columnas a desplazar +:return: The shifted image""" ... + def shift_up(self, n: int) -> Image: - """Create a new image by shifting the picture up. + """Crea una nueva imagen desplazando la imagen hacia arriba. (desplazamiento hacia arriba) - Example: ``Image.HEART_SMALL.shift_up(1)`` +Example: ``Image.HEART_SMALL.shift_up(1)`` - :param n: The number of rows to shift by - :return: The shifted image - """ +:param n: El número de filas a desplazar +:return: The shifted image""" ... + def shift_down(self, n: int) -> Image: - """Create a new image by shifting the picture down. + """Crea una nueva imagen desplazando la imagen hacia abajo. (desplazamiento hacia abajo) - Example: ``Image.HEART_SMALL.shift_down(1)`` +Example: ``Image.HEART_SMALL.shift_down(1)`` - :param n: The number of rows to shift by - :return: The shifted image - """ +:param n: El número de filas a desplazar +:return: The shifted image""" ... + def crop(self, x: int, y: int, w: int, h: int) -> Image: - """Create a new image by cropping the picture. + """Crear una nueva imagen recortando la imagen. (recortar) - Example: ``Image.HEART.crop(1, 1, 3, 3)`` +Example: ``Image.HEART.crop(1, 1, 3, 3)`` - :param x: The crop offset column - :param y: The crop offset row - :param w: The crop width - :param h: The crop height - :return: The new image - """ +:param x: La columna de desplazamiento del recorte +:param y: La fila de desplazamiento del recorte +:param w: (a) El ancho del recorte +:param h: La altura del recorte +:return: The new image""" ... + def copy(self) -> Image: - """Create an exact copy of the image. + """Crea una copia exacta de la imagen. (copiar) - Example: ``Image.HEART.copy()`` +Example: ``Image.HEART.copy()`` - :return: The new image - """ +:return: The new image""" ... + def invert(self) -> Image: - """Create a new image by inverting the brightness of the pixels in the - source image. + """Crea una nueva imagen invirtiendo el brillo de los píxeles de la +imagen de origen. (invertir) - Example: ``Image.SMALL_HEART.invert()`` +Example: ``Image.SMALL_HEART.invert()`` - :return: The new image. - """ +:return: The new image.""" ... + def fill(self, value: int) -> None: - """Set the brightness of all the pixels in the image. + """Establece el brillo de todos los píxeles de la imagen. (llenar) - Example: ``my_image.fill(5)`` +Example: ``my_image.fill(5)`` - :param value: The new brightness as a number between 0 (dark) and 9 (bright). +:param value: (valor) El nuevo brillo expresado como un número entre 0 (oscuro) y 9 (brillante). - This method will raise an exception when called on any of the built-in - read-only images, like ``Image.HEART``. - """ +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 an area from another image into this image. - - Example: ``my_image.blit(Image.HEART, 1, 1, 3, 3, 1, 1)`` - - :param src: The source image - :param x: The starting column offset in the source image - :param y: The starting row offset in the source image - :param w: The number of columns to copy - :param h: The number of rows to copy - :param xdest: The column offset to modify in this image - :param ydest: The row offset to modify in this image - - Pixels outside the source image are treated as having a brightness 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 blit(self, src: Image, x: int, y: int, w: int, h: int, xdest: int=0, ydest: int=0) -> None: + """Copia un área de otra imagen en esta imagen. + +Example: ``my_image.blit(Image.HEART, 1, 1, 3, 3, 1, 1)`` + +:param src: (org) La imagen de origen +:param x: El desplazamiento de columna inicial en la imagen de origen +:param y: El desplazamiento de fila inicial en la imagen de origen +:param w: (a) El número de columnas a copiar +:param h: El número de filas a copiar +:param xdest: El desplazamiento de columna a modificar en esta imagen +:param ydest: El desplazamiento de fila a modificar en esta imagen + +Pixels outside the source image are treated as having a brightness 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.""" + """Obtiene una representación en cadena compacta de la imagen.""" ... + def __str__(self) -> str: - """Get a readable string representation of the image.""" + """Obtiene una representación en cadena legible de la imagen. (cad)""" ... + def __add__(self, other: Image) -> Image: - """Create a new image by adding the brightness values from the two - images for each pixel. + """Crea una nueva imagen sumando los valores de brillo de las dos imágenes +para cada píxel. (añadir) - Example: ``Image.HEART + Image.HAPPY`` +Example: ``Image.HEART + Image.HAPPY`` - :param other: The image to add. - """ +:param other: (otro) La imagen a añadir.""" ... + def __sub__(self, other: Image) -> Image: - """Create a new image by subtracting the brightness values of the - other image from this image. + """Crea una nueva imagen restando los valores de brillo de la otra imagen a los de esta imagen. (rest) - Example: ``Image.HEART - Image.HEART_SMALL`` +Example: ``Image.HEART - Image.HEART_SMALL`` - :param other: The image to subtract. - """ +:param other: (otro) La imagen a restar.""" ... + def __mul__(self, n: float) -> Image: - """Create a new image by multiplying the brightness of each pixel by - ``n``. + """Crea una nueva imagen multiplicando el brillo de cada píxel por ``n``. - Example: ``Image.HEART * 0.5`` +Example: ``Image.HEART * 0.5`` - :param n: The value to multiply by. - """ +:param n: El valor por el que multiplicar.""" ... + def __truediv__(self, n: float) -> Image: - """Create a new image by dividing the brightness of each pixel by - ``n``. + """Crea una nueva imagen dividiendo el brillo de cada píxel entre ``n``. - Example: ``Image.HEART / 2`` +Example: ``Image.HEART / 2`` - :param n: The value to divide by. - """ +:param n: El valor entre el que dividir.""" ... class SoundEvent: LOUD: SoundEvent - """Represents the transition of sound events, from ``quiet`` to ``loud`` like clapping or shouting.""" - + """Representa la transición de eventos de sonido, desde ``quiet`` a ``loud``, como aplaudir o gritar. (alto)""" QUIET: SoundEvent - """Represents the transition of sound events, from ``loud`` to ``quiet`` like speaking or background music.""" + """Representa la transición de eventos de sonido, desde ``loud`` hasta ``quiet``, como hablar o una música de fondo. (silencioso)""" class Sound: - """The built-in sounds can be called using ``audio.play(Sound.NAME)``.""" - + """Los sonidos predefinidos pueden llamarse usando ``audio.play(Sound.NAME)``. (sonido)""" GIGGLE: Sound - """Giggling sound.""" - + """Sonido de risita. (risita)""" HAPPY: Sound - """Happy sound.""" - + """Sonido alegre. (feliz)""" HELLO: Sound - """Greeting sound.""" - + """Sonido de saludo. (hola)""" MYSTERIOUS: Sound - """Mysterious sound.""" - + """Sonido misterioso. (misterioso)""" SAD: Sound - """Sad sound.""" - + """Sonido triste. (triste)""" SLIDE: Sound - """Sliding sound.""" - + """Sonido deslizante. (deslizante)""" SOARING: Sound - """Soaring sound.""" - + """Sonido creciente. (creciente)""" SPRING: Sound - """Spring sound.""" - + """Sonido de muelle. (muelle)""" TWINKLE: Sound - """Twinkling sound.""" - + """Sonido parpadeante. (parpadeante)""" YAWN: Sound - """Yawning sound.""" + """Sonido de bostezo. (bostezo)""" \ No newline at end of file diff --git a/lang/es-es/typeshed/stdlib/microbit/accelerometer.pyi b/lang/es-es/typeshed/stdlib/microbit/accelerometer.pyi index bac82c0..3d591b4 100644 --- a/lang/es-es/typeshed/stdlib/microbit/accelerometer.pyi +++ b/lang/es-es/typeshed/stdlib/microbit/accelerometer.pyi @@ -1,115 +1,103 @@ -"""Measure the acceleration of the micro:bit and recognise gestures. -""" - +"""Mide la aceleración del micro:bit y reconoce gestos. (acelerómetro)""" from typing import Tuple def get_x() -> int: - """Get the acceleration measurement in the ``x`` axis in milli-g. + """Obtiene la medición de la aceleración en el eje ``x`` en mili-g. (obtener x) - Example: ``accelerometer.get_x()`` +Example: ``accelerometer.get_x()`` - :return: A positive or negative integer depending on direction in the range +/- 2000mg. - """ +:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" ... def get_y() -> int: - """Get the acceleration measurement in the ``y`` axis in milli-g. + """Obtiene la medición de la aceleración en el eje ``y`` en mili-g. (obtener y) - Example: ``accelerometer.get_y()`` +Example: ``accelerometer.get_y()`` - :return: A positive or negative integer depending on direction in the range +/- 2000mg. - """ +:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" ... def get_z() -> int: - """Get the acceleration measurement in the ``z`` axis in milli-g. + """Obtiene la medición de la aceleración en el eje ``z`` en mili-g. (obtener z) - Example: ``accelerometer.get_z()`` +Example: ``accelerometer.get_z()`` - :return: A positive or negative integer depending on direction in the range +/- 2000mg. - """ +:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" ... def get_values() -> Tuple[int, int, int]: - """Get the acceleration measurements in all axes at once as a tuple. + """Obtiene las mediciones de las aceleraciones en todos los ejes como una tupla. (obtener valores) - Example: ``x, y, z = accelerometer.get_values()`` +Example: ``x, y, z = accelerometer.get_values()`` - :return: a three-element tuple of integers ordered as X, Y, Z, each value a positive or negative integer depending on direction in the range +/- 2000mg - """ +:return: a three-element tuple of integers ordered as X, Y, Z, each value a positive or negative integer depending on direction in the range +/- 2000mg""" ... def get_strength() -> int: - """Get the acceleration measurement of all axes combined, as a positive integer. This is the Pythagorean sum of the X, Y and Z axes. + """Obtiene la medida de la aceleración de todos los ejes combinados, como un entero positivo. Es la suma Pitagórica de los ejes X, Y y Z. (obtener fuerza) - Example: ``accelerometer.get_strength()`` +Example: ``accelerometer.get_strength()`` - :return: The combined acceleration strength of all the axes, in milli-g. - """ +:return: The combined acceleration strength of all the axes, in milli-g.""" ... def current_gesture() -> str: - """Get the name of the current gesture. + """Obtiene el nombre del gesto actual. (gesto actual) - Example: ``accelerometer.current_gesture()`` +Example: ``accelerometer.current_gesture()`` - 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. +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. - :return: The current gesture - """ +:return: The current gesture""" ... def is_gesture(name: str) -> bool: - """Check if the named gesture is currently active. + """Comprueba si el gesto está actualmente activo. (gesto activo) - Example: ``accelerometer.is_gesture('shake')`` +Example: ``accelerometer.is_gesture('shake')`` - 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. +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. - :param name: The gesture name. - :return: ``True`` if the gesture is active, ``False`` otherwise. - """ +:param name: (nombre) El nombre del gesto. +:return: ``True`` if the gesture is active, ``False`` otherwise.""" ... def was_gesture(name: str) -> bool: - """Check if the named gesture was active since the last call. + """Comprueba si el gesto estuvo activo desde la última llamada. (gesto anterior) - Example: ``accelerometer.was_gesture('shake')`` +Example: ``accelerometer.was_gesture('shake')`` - 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. +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. - :param name: The gesture name. - :return: ``True`` if the gesture was active since the last call, ``False`` otherwise. - """ +:param name: (nombre) El nombre del gesto. +:return: ``True`` if the gesture was active since the last call, ``False`` otherwise.""" def get_gestures() -> Tuple[str, ...]: - """Return a tuple of the gesture history. + """Devuelve una tupla con el historial de gestos. (obtener gestos) - Example: ``accelerometer.get_gestures()`` +Example: ``accelerometer.get_gestures()`` - Clears the gesture history before returning. +Clears the gesture history before returning. - Gestures are not updated in the background so there needs to be constant - calls to some accelerometer method to do the gesture detection. Usually - gestures can be detected using a loop with a small :func:`microbit.sleep` delay. +Gestures are not updated in the background so there needs to be constant +calls to some accelerometer method to do the gesture detection. Usually +gestures can be detected using a loop with a small :func:`microbit.sleep` delay. - :return: The history as a tuple, most recent last. - """ +:return: The history as a tuple, most recent last.""" ... def set_range(value: int) -> None: - """Set the accelerometer sensitivity range, in g (standard gravity), to the closest values supported by the hardware, so it rounds to either ``2``, ``4``, or ``8`` g. + """Configura el rango de sensibilidad del acelerómetro, en g (gravedad estándar), a los valores más cercanos soportados por el hardware, por lo que redondea a ``2``, ``4``, u ``8`` g. (configurar rango) - Example: ``accelerometer.set_range(8)`` +Example: ``accelerometer.set_range(8)`` - :param value: New range for the accelerometer, an integer in ``g``. - """ +:param value: (valor) Nuevo rango para el acelerómetro, un entero en ``g``.""" \ No newline at end of file diff --git a/lang/es-es/typeshed/stdlib/microbit/audio.pyi b/lang/es-es/typeshed/stdlib/microbit/audio.pyi index 3b1e327..90bc14f 100644 --- a/lang/es-es/typeshed/stdlib/microbit/audio.pyi +++ b/lang/es-es/typeshed/stdlib/microbit/audio.pyi @@ -1,160 +1,124 @@ -"""Play sounds using the micro:bit (import ``audio`` for V1 compatibility). -""" - +"""Reproducir sonidos usando el micro:bit (importar ``audio`` para compatibilidad con V1).""" from ..microbit import MicroBitDigitalPin, Sound, pin0 from typing import ClassVar, Iterable, Union -def play( - source: Union[Iterable[AudioFrame], Sound, SoundEffect], - wait: bool = True, - pin: MicroBitDigitalPin = pin0, - return_pin: Union[MicroBitDigitalPin, None] = None, -) -> None: - """Play a built-in sound, sound effect or custom audio frames. +def play(source: Union[Iterable[AudioFrame], Sound, SoundEffect], wait: bool=True, pin: MicroBitDigitalPin=pin0, return_pin: Union[MicroBitDigitalPin, None]=None) -> None: + """Reproduce un sonido integrado, un efecto de sonido o marcos de audio personalizados. (reproducir) - Example: ``audio.play(Sound.GIGGLE)`` +Example: ``audio.play(Sound.GIGGLE)`` - :param source: A built-in ``Sound`` such as ``Sound.GIGGLE``, a ``SoundEffect`` or sample data as an iterable of ``AudioFrame`` objects. - :param wait: If ``wait`` is ``True``, this function will block until the sound is complete. - :param pin: An optional argument to specify the output pin can be used to override the default of ``pin0``. If we do not want any sound to play we can use ``pin=None``. - :param return_pin: Specifies a differential edge connector pin to connect to an external speaker instead of ground. This is ignored for the **V2** revision. - """ +:param source: (origen) Un ``Sound`` integrado como ``Sound.GIGGLE``, un ``SoundEffect`` o datos de muestra como un iterable de objetos ``AudioFrame``. +:param wait: (esperar) Si ``wait`` es ``True`` (verdadero), la función se bloqueará hasta que el sonido finalice. +:param pin: Se puede usar un argumento opcional para especificar el pin de salida, reemplazando el valor predeterminado de ``pin0``. Si no queremos que se reproduzca ningún sonido, podemos usar ``pin=None``. +:param return_pin: (devolver pin) Especifica un pin de conector de borde diferencial para conectarse a un altavoz externo en lugar de tierra. Esto se ignora para la revisión **V2**.""" def is_playing() -> bool: - """Check whether a sound is playing. + """Comprueba si se está reproduciendo un sonido. (reproduciendo) - Example: ``audio.is_playing()`` +Example: ``audio.is_playing()`` - :return: ``True`` if audio is playing, otherwise ``False``.""" +:return: ``True`` if audio is playing, otherwise ``False``.""" ... def stop() -> None: - """Stop all audio playback. + """Detiene la reproducción de audio. (detener) - Example: ``audio.stop()`` - """ +Example: ``audio.stop()``""" ... class SoundEffect: - """A sound effect, composed by a set of parameters configured via the constructor or attributes.""" - + """Un efecto de sonido, compuesto por un conjunto de parámetros configurados a través del constructor o atributos. (efectosonido)""" WAVEFORM_SINE: ClassVar[int] - """Sine wave option used for the ``waveform`` parameter.""" - + """Opción de onda senoidal utilizada para el parámetro ``waveform``. (forma de onda senoidal)""" WAVEFORM_SAWTOOTH: ClassVar[int] - """Sawtooth wave option used for the ``waveform`` parameter.""" - + """Opción de onda con diente de sierra usada para el parámetro ``waveform``. (forma de onda diente de sierra)""" WAVEFORM_TRIANGLE: ClassVar[int] - """Triangle wave option used for the ``waveform`` parameter.""" - + """Opción de onda triangular usada para el parámetro ``waveform``. (forma de onda triangular)""" WAVEFORM_SQUARE: ClassVar[int] - """Square wave option used for the ``waveform`` parameter.""" - + """Opción de onda cuadrada usada para el parámetro ``waveform``. (forma de onda cuadrada)""" WAVEFORM_NOISE: ClassVar[int] - """Noise option used for the ``waveform`` parameter.""" - + """Opción de ruido usada para el parámetro ``waveform``. (forma de onda de ruido)""" SHAPE_LINEAR: ClassVar[int] - """Linear interpolation option used for the ``shape`` parameter.""" - + """Opción de interpolación lineal usada para el parámetro ``shape``. (forma lineal)""" SHAPE_CURVE: ClassVar[int] - """Curve interpolation option used for the ``shape`` parameter.""" - + """Opción de interpolación de curva usada para el parámetro ``shape``. (forma curva)""" SHAPE_LOG: ClassVar[int] - """Logarithmic interpolation option used for the ``shape`` parameter.""" - + """Opción de interpolación logarítmica usada para el parámetro ``shape``. (registro de forma)""" FX_NONE: ClassVar[int] - """No effect option used for the ``fx`` parameter.""" - + """Ninguna opción de efecto usada para el parámetro ``fx``. (fx ninguno)""" FX_TREMOLO: ClassVar[int] - """Tremolo effect option used for the ``fx`` parameter.""" - + """Opción de efecto Trémolo usada para el parámetro ``fx``. (fx trémolo)""" FX_VIBRATO: ClassVar[int] - """Vibrato effect option used for the ``fx`` parameter.""" - + """Opción de efecto vibrato utilizada para el parámetro ``fx``.""" FX_WARBLE: ClassVar[int] - """Warble effect option used for the ``fx`` parameter.""" - + """Opción de efecto gorjeo utilizada para el parámetro ``fx``. (fx gorjeo)""" freq_start: int - """Start frequency in Hertz (Hz), a number between ``0`` and ``9999``""" - + """Frecuencia de inicio en Hertz (Hz), un número entre ``0`` y ``9999`` (frecuencia de inicio)""" freq_end: int - """End frequency in Hertz (Hz), a number between ``0`` and ``9999``""" - + """Frecuencia final en Hertz (Hz), un número entre ``0`` y ``9999`` (frecuencia final)""" duration: int - """Duration of the sound in milliseconds, a number between ``0`` and ``9999``""" - + """Duración del sonido en milisegundos, un número entre ``0`` y ``9999`` (duración)""" vol_start: int - """Start volume value, a number between ``0`` and ``255``""" - + """Valor de volumen inicial, un número entre ``0`` y ``255`` (volumen de inicio)""" vol_end: int - """End volume value, a number between ``0`` and ``255``""" - + """Valor final del volumen, un número entre ``0`` y ``255`` (volumen final)""" waveform: int - """Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise)""" - + """Tipo de forma ondulada, uno de estos valores: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (ruido generado aleatoriamente) (forma de onda)""" fx: int - """Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``""" - + """Efecto para añadir en el sonido, uno de los siguientes valores: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``o ``FX_NONE``""" shape: int - """The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``""" - - def __init__( - self, - freq_start: int = 500, - freq_end: int = 2500, - duration: int = 500, - vol_start: int = 255, - vol_end: int = 0, - waveform: int = WAVEFORM_SQUARE, - fx: int = FX_NONE, - shape: int = SHAPE_LOG, - ): - """Create a new sound effect. - - Example: ``my_effect = SoundEffect(duration=1000)`` - - All the parameters are optional, with default values as shown above, and - they can all be modified via attributes of the same name. For example, we - can first create an effect ``my_effect = SoundEffect(duration=1000)``, - and then change its attributes ``my_effect.duration = 500``. - - :param freq_start: Start frequency in Hertz (Hz), a number between ``0`` and ``9999``. - :param freq_end: End frequency in Hertz (Hz), a number between ``0`` and ``9999``. - :param duration: Duration of the sound in milliseconds, a number between ``0`` and ``9999``. - :param vol_start: Start volume value, a number between ``0`` and ``255``. - :param vol_end: End volume value, a number between ``0`` and ``255``. - :param waveform: Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise). - :param fx: Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``. - :param shape: The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``. - """ + """El tipo de curva de interpolación entre las frecuencias de inicio y final, diferentes formas de onda tienen diferentes tasas de cambio en la frecuencia. Uno de los siguientes valores: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG`` (forma)""" + + def __init__(self, freq_start: int=500, freq_end: int=2500, duration: int=500, vol_start: int=255, vol_end: int=0, waveform: int=WAVEFORM_SQUARE, fx: int=FX_NONE, shape: int=SHAPE_LOG): + """Crea un nuevo efecto de sonido. + +Example: ``my_effect = SoundEffect(duration=1000)`` + +All the parameters are optional, with default values as shown above, and +they can all be modified via attributes of the same name. For example, we +can first create an effect ``my_effect = SoundEffect(duration=1000)``, +and then change its attributes ``my_effect.duration = 500``. + +:param freq_start: (frecuencia de inicio) Frecuencia de inicio en Hertz (Hz), un número entre ``0`` y ``9999``. +:param freq_end: (frecuencia final) Frecuencia final en Hertz (Hz), un número entre ``0`` y ``9999``. +:param duration: (duración) Duración del sonido en milisegundos, un número entre ``0`` y ``9999``. +:param vol_start: (volumen inicial) Valor de volumen inicial, un número entre ``0`` y ``255``. +:param vol_end: (volumen final) Valor de volumen final, un número entre ``0`` y ``255``. +:param waveform: (forma de onda) Tipo de forma de onda, uno de estos valores: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (ruido generado aleatoriamente). +:param fx: Efecto para añadir en el sonido, uno de los siguientes valores: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``o ``FX_NONE``. +:param shape: (forma) El tipo de curva de interpolación entre las frecuencias de inicio y final, diferentes formas de onda tienen diferentes tasas de cambio en la frecuencia. Uno de los siguientes valores: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``.""" + def copy(self) -> SoundEffect: - """Create a copy of this ``SoundEffect``. + """Crea una copia de este ``SoundEffect``. (copiar) - Example: ``sound_2 = sound_1.copy()`` +Example: ``sound_2 = sound_1.copy()`` - :return: A copy of the SoundEffect. - """ +:return: A copy of the SoundEffect.""" class AudioFrame: - """An ``AudioFrame`` object is a list of 32 samples each of which is a unsigned byte - (whole number between 0 and 255). + """Un objeto ``AudioFrame`` es una lista de 32 muestras, cada una de las cuales es un byte +sin signo (número entero entre 0 y 255). - It takes just over 4 ms to play a single frame. +It takes just over 4 ms to play a single frame. - Example:: +Example:: - frame = AudioFrame() - for i in range(len(frame)): - frame[i] = 252 - i * 8 - """ + frame = AudioFrame() + for i in range(len(frame)): + frame[i] = 252 - i * 8""" def copyfrom(self, other: AudioFrame) -> None: - """Overwrite the data in this ``AudioFrame`` with the data from another ``AudioFrame`` instance. + """Sobrescribe los datos de este ``AudioFrame`` con los datos de otra instancia ``AudioFrame``. (copiadesde) + +Example: ``my_frame.copyfrom(source_frame)`` + +:param other: (otro) Instancia ``AudioFrame`` desde la que copiar los datos.""" + + def __len__(self) -> int: + ... - Example: ``my_frame.copyfrom(source_frame)`` + def __setitem__(self, key: int, value: int) -> None: + ... - :param other: ``AudioFrame`` instance from which to copy the data. - """ - def __len__(self) -> int: ... - def __setitem__(self, key: int, value: int) -> None: ... - def __getitem__(self, key: int) -> int: ... + def __getitem__(self, key: int) -> int: + ... \ No newline at end of file diff --git a/lang/es-es/typeshed/stdlib/microbit/compass.pyi b/lang/es-es/typeshed/stdlib/microbit/compass.pyi index c74a47b..d6777af 100644 --- a/lang/es-es/typeshed/stdlib/microbit/compass.pyi +++ b/lang/es-es/typeshed/stdlib/microbit/compass.pyi @@ -1,78 +1,70 @@ -"""Use the built-in compass. -""" +"""Usar la brújula incorporada. (brújula)""" def calibrate() -> None: - """Starts the calibration process. + """Inicia el proceso de calibración. (calibrar) - Example: ``compass.calibrate()`` +Example: ``compass.calibrate()`` - 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. - """ +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: - """Check is the compass is calibrated. + """Comprueba si la brújula está calibrada. (está calibrado) - Example: ``compass.is_calibrated()`` +Example: ``compass.is_calibrated()`` - :return: ``True`` if the compass has been successfully calibrated, ``False`` otherwise. - """ +:return: ``True`` if the compass has been successfully calibrated, ``False`` otherwise.""" ... def clear_calibration() -> None: - """Undoes the calibration, making the compass uncalibrated again. + """Deshace la calibración, haciendo que la brújula esté otra vez sin calibrar. (eliminar calibración) - Example: ``compass.clear_calibration()`` - """ +Example: ``compass.clear_calibration()``""" ... def get_x() -> int: - """Get the magnetic field strength on the ``x`` axis. + """Obtiene la fuerza del campo magnético en el eje ``x``. (obtener x) - Example: ``compass.get_x()`` +Example: ``compass.get_x()`` - Call ``calibrate`` first or the results will be inaccurate. +Call ``calibrate`` first or the results will be inaccurate. - :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. - """ +:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" ... def get_y() -> int: - """Get the magnetic field strength on the ``y`` axis. + """Obtiene la fuerza del campo magnético en el eje ``y``. (obtener y) - Example: ``compass.get_y()`` +Example: ``compass.get_y()`` - Call ``calibrate`` first or the results will be inaccurate. +Call ``calibrate`` first or the results will be inaccurate. - :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. - """ +:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" ... def get_z() -> int: - """Get the magnetic field strength on the ``z`` axis. + """Obtiene la fuerza del campo magnético en el eje ``z``. (obtener z) - Example: ``compass.get_z()`` +Example: ``compass.get_z()`` - Call ``calibrate`` first or the results will be inaccurate. +Call ``calibrate`` first or the results will be inaccurate. - :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. - """ +:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" ... def heading() -> int: - """Get the compass heading. + """Obtiene el rumbo de la brújula. (rumbo) - Example: ``compass.heading()`` +Example: ``compass.heading()`` - :return: An integer in the range from 0 to 360, representing the angle in degrees, clockwise, with north as 0. - """ +:return: An integer in the range from 0 to 360, representing the angle in degrees, clockwise, with north as 0.""" ... def get_field_strength() -> int: - """Get the magnitude of the magnetic field around the device. + """Obtiene la magnitud del campo magnético alrededor del dispositivo. (obtener fuerza del campo) - Example: ``compass.get_field_strength()`` +Example: ``compass.get_field_strength()`` - :return: An integer indication of the magnitude of the magnetic field in nano tesla.""" - ... +:return: An integer indication of the magnitude of the magnetic field in nano tesla.""" + ... \ No newline at end of file diff --git a/lang/es-es/typeshed/stdlib/microbit/display.pyi b/lang/es-es/typeshed/stdlib/microbit/display.pyi index aa4013e..63db48b 100644 --- a/lang/es-es/typeshed/stdlib/microbit/display.pyi +++ b/lang/es-es/typeshed/stdlib/microbit/display.pyi @@ -1,115 +1,92 @@ -"""Show text, images and animations on the 5×5 LED display. -""" - +"""Mostrar texto, imágenes y animaciones en la pantalla LED de 5 × 5. (pantalla)""" from ..microbit import Image from typing import Union, overload, Iterable def get_pixel(x: int, y: int) -> int: - """Get the brightness of the LED at column ``x`` and row ``y``. + """Obtiene el brillo del LED que hay en la columna ``x`` y fila ``y``. (obtener píxel) - Example: ``display.get_pixel(0, 0)`` +Example: ``display.get_pixel(0, 0)`` - :param x: The display column (0..4) - :param y: The display row (0..4) - :return: A number between 0 (off) and 9 (bright) - """ +:param x: La columna de la pantalla (0..4) +:param y: La fila de la pantalla (0..4) +:return: A number 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``. + """Establece el brillo del LED que hay en la columna ``x`` y fila ``y``. (configurar píxel) - Example: ``display.set_pixel(0, 0, 9)`` +Example: ``display.set_pixel(0, 0, 9)`` - :param x: The display column (0..4) - :param y: The display row (0..4) - :param value: The brightness between 0 (off) and 9 (bright) - """ +:param x: La columna de la pantalla (0..4) +:param y: La fila de la pantalla (0..4) +:param value: (valor) El brillo entre 0 (apagado) y 9 (brillante)""" ... def clear() -> None: - """Set the brightness of all LEDs to 0 (off). + """Ajusta el brillo de todos los LED a 0 (apagado). (borrar) - Example: ``display.clear()`` - """ +Example: ``display.clear()``""" ... -def show( - image: Union[str, float, int, Image, Iterable[Image]], - delay: int = 400, - wait: bool = True, - loop: bool = False, - clear: bool = False, -) -> None: - """Shows images, letters or digits on the LED display. +def show(image: Union[str, float, int, Image, Iterable[Image]], delay: int=400, wait: bool=True, loop: bool=False, clear: bool=False) -> None: + """Muestra imágenes, letras o dígitos en la pantalla LED. (mostrar) - Example: ``display.show(Image.HEART)`` +Example: ``display.show(Image.HEART)`` - When ``image`` is an image or a list of images then each image is displayed in turn. - If ``image`` is a string or number, each letter or digit is displayed in turn. +When ``image`` is an image or a list of images then each image is displayed in turn. +If ``image`` is a string or number, each letter or digit is displayed in turn. - :param image: A string, number, image or list of images to show. - :param delay: Each letter, digit or image is shown with ``delay`` milliseconds between them. - :param wait: If ``wait`` is ``True``, this function will block until the animation is finished, otherwise the animation will happen in the background. - :param loop: If ``loop`` is ``True``, the animation will repeat forever. - :param clear: If ``clear`` is ``True``, the display will be cleared after the sequence has finished. +:param image: (imagen) Una cadena, número, imagen o lista de imágenes para mostrar. +:param delay: (retardo) Cada letra, dígito o imagen se muestra con ``delay`` milisegundos de retardo entre ellos. +:param wait: (esperar) Si ``wait`` es ``True`` (verdadero), la función se bloqueará hasta que finalice la animación; de lo contrario, la animación se ejecutará en segundo plano. +:param loop: (bucle) Si ``loop`` es ``True`` (verdadero), la animación se repetirá para siempre. +:param clear: (borrar) Si ``clear`` es ``True`` (verdadero), la pantalla se borrará una vez que la secuencia haya terminado. - The ``wait``, ``loop`` and ``clear`` arguments must be specified using their keyword. - """ +The ``wait``, ``loop`` and ``clear`` arguments must be specified using their keyword.""" ... -def scroll( - text: Union[str, float, int], - delay: int = 150, - wait: bool = True, - loop: bool = False, - monospace: bool = False, -) -> None: - """Scrolls a number or text on the LED display. - - Example: ``display.scroll('micro:bit')`` - - :param text: The string to scroll. If ``text`` is an integer or float it is first converted to a string using ``str()``. - :param delay: The ``delay`` parameter controls how fast the text is scrolling. - :param wait: If ``wait`` is ``True``, this function will block until the animation is finished, otherwise the animation will happen in the background. - :param loop: If ``loop`` is ``True``, the animation will repeat forever. - :param monospace: 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. - - The ``wait``, ``loop`` and ``monospace`` arguments must be specified - using their keyword. - """ +def scroll(text: Union[str, float, int], delay: int=150, wait: bool=True, loop: bool=False, monospace: bool=False) -> None: + """Desplaza un número o texto por la pantalla LED. (desplazar) + +Example: ``display.scroll('micro:bit')`` + +:param text: (texto) La cadena a desplazar. Si ``text`` es un entero o de coma flotante, primero se convertirá a cadena usando ``str()``. +:param delay: (retardo) El parámetro ``delay`` controla la velocidad de desplazamiento del texto. +:param wait: (esperar) Si ``wait`` es ``True`` (verdadero), la función se bloqueará hasta que finalice la animación; de lo contrario, la animación se ejecutará en segundo plano. +:param loop: (bucle) Si ``loop`` es ``True`` (verdadero), la animación se repetirá para siempre. +:param monospace: Si ``monospace`` es ``True`` (verdadero), todos los caracteres ocuparán columnas de 5 píxeles de ancho; de lo contrario, habrá exactamente 1 columna de píxeles vacíos entre cada carácter a medida que se desplazan. + +The ``wait``, ``loop`` and ``monospace`` arguments must be specified +using their keyword.""" ... def on() -> None: - """Turn on the LED display. + """Enciende la pantalla LED. (encendido) - Example: ``display.on()`` - """ +Example: ``display.on()``""" ... def off() -> None: - """Turn off the LED display (disabling the display allows you to re-use the GPIO pins for other purposes). + """Apaga la pantalla LED (desactivar la pantalla te permite reutilizar los pines GPIO para otros fines). (apagado) - Example: ``display.off()`` - """ +Example: ``display.off()``""" ... def is_on() -> bool: - """Check whether the LED display is enabled. + """Comprueba si la pantalla LED está activada. (está encendido) - Example: ``display.is_on()`` +Example: ``display.is_on()`` - :return: ``True`` if the display is on, otherwise returns ``False``. - """ +:return: ``True`` if the display is on, otherwise returns ``False``.""" ... def read_light_level() -> int: - """Read the light level. + """Lee el nivel de luz. (leer nivel de luz) - Example: ``display.read_light_level()`` +Example: ``display.read_light_level()`` - Uses the display's LEDs in reverse-bias mode to sense the amount of light - falling on the display. +Uses the display's LEDs in reverse-bias mode to sense the amount of light +falling on the display. - :return: An integer between 0 and 255 representing the light level, with larger meaning more light. - """ - ... +:return: An integer between 0 and 255 representing the light level, with larger meaning more light.""" + ... \ No newline at end of file diff --git a/lang/es-es/typeshed/stdlib/microbit/i2c.pyi b/lang/es-es/typeshed/stdlib/microbit/i2c.pyi index df26efa..d126acb 100644 --- a/lang/es-es/typeshed/stdlib/microbit/i2c.pyi +++ b/lang/es-es/typeshed/stdlib/microbit/i2c.pyi @@ -1,57 +1,49 @@ -"""Communicate with devices using the I²C bus protocol. -""" - +"""Comunicarse con dispositivos que usan el protocolo de bus I²C.""" from _typeshed import ReadableBuffer from ..microbit import MicroBitDigitalPin, pin19, pin20 from typing import List -def init( - freq: int = 100000, sda: MicroBitDigitalPin = pin20, scl: MicroBitDigitalPin = pin19 -) -> None: - """Re-initialize a peripheral. +def init(freq: int=100000, sda: MicroBitDigitalPin=pin20, scl: MicroBitDigitalPin=pin19) -> None: + """Reinicia un periférico. (inic) - Example: ``i2c.init()`` +Example: ``i2c.init()`` - :param freq: clock frequency - :param sda: ``sda`` pin (default 20) - :param scl: ``scl`` pin (default 19) +:param freq: (frec) frecuencia del reloj +:param sda: pin ``sda`` (por defecto, 20) +:param scl: pin ``scl`` (por defecto, 19) - On a micro:bit V1 board, changing the I²C pins from defaults will make - the accelerometer and compass stop working, as they are connected - internally to those pins. This warning does not apply to the **V2** - revision of the micro:bit as this has `separate I²C lines `_ - for the motion sensors and the edge connector. - """ +On a micro:bit V1 board, changing the I²C pins from defaults will make +the accelerometer and compass stop working, as they are connected +internally to those pins. This warning does not apply to the **V2** +revision of the micro:bit as this has `separate I²C lines `_ +for the motion sensors and the edge connector.""" ... def scan() -> List[int]: - """Scan the bus for devices. + """Escanea el bus para buscar dispositivos. (escanear) - Example: ``i2c.scan()`` +Example: ``i2c.scan()`` - :return: A list of 7-bit addresses corresponding to those devices that responded to the scan. - """ +:return: A list of 7-bit addresses corresponding to those devices that responded to the scan.""" ... -def read(addr: int, n: int, repeat: bool = False) -> bytes: - """Read bytes from a device. +def read(addr: int, n: int, repeat: bool=False) -> bytes: + """Lee bytes de un dispositivo. (leer) - Example: ``i2c.read(0x50, 64)`` +Example: ``i2c.read(0x50, 64)`` - :param addr: The 7-bit address of the device - :param n: The number of bytes to read - :param repeat: If ``True``, no stop bit will be sent - :return: The bytes read - """ +:param addr: (dir) La dirección de 7 bits del dispositivo +:param n: El número de bytes a leer +:param repeat: (repetir) Si es ``True`` (verdadero), no se enviará ningún bit de parada +:return: The bytes read""" ... -def write(addr: int, buf: ReadableBuffer, repeat: bool = False) -> None: - """Write bytes to a device. +def write(addr: int, buf: ReadableBuffer, repeat: bool=False) -> None: + """Escribe bytes en un dispositivo. (escribir) - Example: ``i2c.write(0x50, bytes([1, 2, 3]))`` +Example: ``i2c.write(0x50, bytes([1, 2, 3]))`` - :param addr: The 7-bit address of the device - :param buf: A buffer containing the bytes to write - :param repeat: If ``True``, no stop bit will be sent - """ - ... +:param addr: (dir) La dirección de 7 bits del dispositivo +:param buf: (búf) Un búfer que contiene los bytes a escribir +:param repeat: (repetir) Si es ``True`` (verdadero), no se enviará ningún bit de parada""" + ... \ No newline at end of file diff --git a/lang/es-es/typeshed/stdlib/microbit/microphone.pyi b/lang/es-es/typeshed/stdlib/microbit/microphone.pyi index 68e8f3a..4033fa3 100644 --- a/lang/es-es/typeshed/stdlib/microbit/microphone.pyi +++ b/lang/es-es/typeshed/stdlib/microbit/microphone.pyi @@ -1,70 +1,62 @@ -"""Respond to sound using the built-in microphone (V2 only). -""" - +"""Responde al sonido usando el micrófono integrado (solo V2). (micrófono)""" from typing import Optional, Tuple from ..microbit import SoundEvent def current_event() -> Optional[SoundEvent]: - """Get the last recorded sound event + """Obtiene el último evento de sonido grabado (evento actual) - Example: ``microphone.current_event()`` +Example: ``microphone.current_event()`` - :return: The event, ``SoundEvent('loud')`` or ``SoundEvent('quiet')``. - """ +:return: The event, ``SoundEvent('loud')`` or ``SoundEvent('quiet')``.""" ... def was_event(event: SoundEvent) -> bool: - """Check if a sound was heard at least once since the last call. + """Comprueba si se ha escuchado un sonido al menos una vez desde la última llamada. (evento anterior) - Example: ``microphone.was_event(SoundEvent.LOUD)`` +Example: ``microphone.was_event(SoundEvent.LOUD)`` - This call clears the sound history before returning. +This call clears the sound history before returning. - :param event: The event to check for, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET`` - :return: ``True`` if sound was heard at least once since the last call, otherwise ``False``. - """ +:param event: (evento) El evento a comprobar, como ``SoundEvent.LOUD`` o ``SoundEvent.QUIET`` +:return: ``True`` if sound was heard at least once since the last call, otherwise ``False``.""" ... def is_event(event: SoundEvent) -> bool: - """Check the most recent sound event detected. + """Comprueba el evento de sonido más reciente detectado. (evento reciente) - Example: ``microphone.is_event(SoundEvent.LOUD)`` +Example: ``microphone.is_event(SoundEvent.LOUD)`` - This call does not clear the sound event history. +This call does not clear the sound event history. - :param event: The event to check for, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET`` - :return: ``True`` if sound was the most recent heard, ``False`` otherwise. - """ +:param event: (evento) El evento a comprobar, como ``SoundEvent.LOUD`` o ``SoundEvent.QUIET`` +:return: ``True`` if sound was the most recent heard, ``False`` otherwise.""" ... def get_events() -> Tuple[SoundEvent, ...]: - """Get the sound event history as a tuple. + """Obtiene el historial de eventos de sonido como una tupla. (obtener eventos) - Example: ``microphone.get_events()`` +Example: ``microphone.get_events()`` - This call clears the sound history before returning. +This call clears the sound history before returning. - :return: A tuple of the event history with the most recent event last. - """ +:return: A tuple of the event history with the most recent event last.""" ... def set_threshold(event: SoundEvent, value: int) -> None: - """Set the threshold for a sound event. + """Establece el umbral para un evento de sonido. (configurar límite) - Example: ``microphone.set_threshold(SoundEvent.LOUD, 250)`` +Example: ``microphone.set_threshold(SoundEvent.LOUD, 250)`` - A high threshold means the event will only trigger if the sound is very loud (>= 250 in the example). +A high threshold means the event will only trigger if the sound is very loud (>= 250 in the example). - :param event: A sound event, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET``. - :param value: The threshold level in the range 0-255. - """ +:param event: (evento) Un evento de sonido, como ``SoundEvent.LOUD`` o ``SoundEvent.QUIET``. +:param value: (valor) El nivel de umbral en el rango 0 - 255.""" ... def sound_level() -> int: - """Get the sound pressure level. + """Obtiene el nivel de presión sonora. (nivel de sonido) - Example: ``microphone.sound_level()`` +Example: ``microphone.sound_level()`` - :return: A representation of the sound pressure level in the range 0 to 255. - """ - ... +:return: A representation of the sound pressure level in the range 0 to 255.""" + ... \ No newline at end of file diff --git a/lang/es-es/typeshed/stdlib/microbit/speaker.pyi b/lang/es-es/typeshed/stdlib/microbit/speaker.pyi index 5a74a4d..0a63d09 100644 --- a/lang/es-es/typeshed/stdlib/microbit/speaker.pyi +++ b/lang/es-es/typeshed/stdlib/microbit/speaker.pyi @@ -1,18 +1,15 @@ -"""Control the built-in speaker (V2 only). -""" +"""Controlar el altavoz integrado (solo V2). (altavoz)""" def off() -> None: - """Turn the speaker off. + """Apaga el altavoz. (apagado) - Example: ``speaker.off()`` +Example: ``speaker.off()`` - This does not disable sound output to an edge connector pin. - """ +This does not disable sound output to an edge connector pin.""" ... def on() -> None: - """Turn the speaker on. + """Enciende el altavoz. (encendido) - Example: ``speaker.on()`` - """ - ... +Example: ``speaker.on()``""" + ... \ No newline at end of file diff --git a/lang/es-es/typeshed/stdlib/microbit/spi.pyi b/lang/es-es/typeshed/stdlib/microbit/spi.pyi index 09c4046..bff4a2a 100644 --- a/lang/es-es/typeshed/stdlib/microbit/spi.pyi +++ b/lang/es-es/typeshed/stdlib/microbit/spi.pyi @@ -1,60 +1,47 @@ -"""Communicate with devices using the serial peripheral interface (SPI) bus. -""" - +"""Comunicarse con dispositivos que usan el bus de interfaz de periféricos serie (SPI, por sus siglas en inglés).""" from _typeshed import ReadableBuffer, WriteableBuffer from ..microbit import pin13, pin14, pin15, MicroBitDigitalPin -def init( - baudrate: int = 1000000, - bits: int = 8, - mode: int = 0, - sclk: MicroBitDigitalPin = pin13, - mosi: MicroBitDigitalPin = pin15, - miso: MicroBitDigitalPin = pin14, -) -> None: - """Initialize SPI communication. - - Example: ``spi.init()`` - - For correct communication, the parameters have to be the same on both communicating devices. - - :param baudrate: The speed of communication. - :param bits: The width in bits of each transfer. Currently only ``bits=8`` is supported. However, this may change in the future. - :param mode: Determines the combination of clock polarity and phase - `see online table `_. - :param sclk: sclk pin (default 13) - :param mosi: mosi pin (default 15) - :param miso: miso pin (default 14) - """ +def init(baudrate: int=1000000, bits: int=8, mode: int=0, sclk: MicroBitDigitalPin=pin13, mosi: MicroBitDigitalPin=pin15, miso: MicroBitDigitalPin=pin14) -> None: + """Inicializa la comunicación SPI. + +Example: ``spi.init()`` + +For correct communication, the parameters have to be the same on both communicating devices. + +:param baudrate: (tasa de baudios) La velocidad de comunicación. +:param bits: El ancho en bits de cada transferencia. Actualmente solo se admite ``bits=8}, pero esto puede cambiar en el futuro. +:param mode: (modo) Determina la combinación de fase y polaridad del reloj - `ver tabla en línea `_. +:param sclk: pin SCLK (por defecto, 13) +:param mosi: pin MOSI (por defecto, 15) +:param miso: pin MISO (por defecto, 14)""" ... -def read(nbytes: int, out: int = 0) -> bytes: - """Read at most ``nbytes`` while continuously writing the single byte given by ``out``. +def read(nbytes: int, out: int=0) -> bytes: + """Lee como máximo ``nbytes`` mientras está escribiendo continuamente el byte individual dado por ``out``. (leer) - Example: ``spi.read(64)`` +Example: ``spi.read(64)`` - :param nbytes: Maximum number of bytes to read. - :param out: The byte value to write (default 0). - :return: The bytes read. - """ +:param nbytes: Número máximo de bytes a leer. +:param out: (salida) El valor del byte a escribir (por defecto 0). +:return: The bytes read.""" ... def write(buffer: ReadableBuffer) -> None: - """Write bytes to the bus. + """Escribe bytes en el bus. (escribir) - Example: ``spi.write(bytes([1, 2, 3]))`` +Example: ``spi.write(bytes([1, 2, 3]))`` - :param buffer: A buffer to read data from. - """ +:param buffer: (búfer) Un búfer del que leer datos.""" ... def write_readinto(out: WriteableBuffer, in_: ReadableBuffer) -> None: - """Write the ``out`` buffer to the bus and read any response into the ``in_`` buffer. + """Escribe el búfer ``out`` en el bus y lee cualquier respuesta en el búfer ``in_``. (escritura leeren) - Example: ``spi.write_readinto(out_buffer, in_buffer)`` +Example: ``spi.write_readinto(out_buffer, in_buffer)`` - The length of the buffers should be the same. The buffers can be the same object. +The length of the buffers should be the same. The buffers can be the same object. - :param out: The buffer to write any response to. - :param in_: The buffer to read data from. - """ - ... +:param out: (a) El búfer en el que escribe una respuesta. +:param in_: (de) El búfer del que leer datos.""" + ... \ No newline at end of file diff --git a/lang/es-es/typeshed/stdlib/microbit/uart.pyi b/lang/es-es/typeshed/stdlib/microbit/uart.pyi index 2ab650f..fc9bd04 100644 --- a/lang/es-es/typeshed/stdlib/microbit/uart.pyi +++ b/lang/es-es/typeshed/stdlib/microbit/uart.pyi @@ -1,96 +1,79 @@ -"""Communicate with a device using a serial interface. -""" - +"""Comunicarse con un dispositivo usando una interfaz serie.""" from _typeshed import WriteableBuffer from ..microbit import MicroBitDigitalPin from typing import Optional, Union - ODD: int -"""Odd parity""" - +"""Paridad impar (impar)""" EVEN: int -"""Even parity""" - -def init( - baudrate: int = 9600, - bits: int = 8, - parity: Optional[int] = None, - stop: int = 1, - tx: Optional[MicroBitDigitalPin] = None, - rx: Optional[MicroBitDigitalPin] = None, -) -> None: - """Initialize serial communication. - - Example: ``uart.init(115200, tx=pin0, rx=pin1)`` - - :param baudrate: The speed of communication. - :param bits: The size of bytes being transmitted. micro:bit only supports 8. - :param parity: How parity is checked, ``None``, ``uart.ODD`` or ``uart.EVEN``. - :param stop: The number of stop bits, has to be 1 for micro:bit. - :param tx: Transmitting pin. - :param rx: Receiving pin. - - 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. - - For more details see `the online documentation `_. - """ +"""Paridad par (par)""" + +def init(baudrate: int=9600, bits: int=8, parity: Optional[int]=None, stop: int=1, tx: Optional[MicroBitDigitalPin]=None, rx: Optional[MicroBitDigitalPin]=None) -> None: + """Inicializa la comunicación serie. + +Example: ``uart.init(115200, tx=pin0, rx=pin1)`` + +:param baudrate: (tasa de baudios) La velocidad de comunicación. +:param bits: El tamaño de bytes transmitidos; micro:bit solo admite 8. +:param parity: (paridad) Cómo se comprueba la paridad: ``None``, ``uart.ODD`` o ``uart.EVEN``. +:param stop: (detener) El número de bits de parada; tiene que ser 1 para el micro:bit. +:param tx: Pin transmisor. +:param rx: Pin receptor. + +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. + +For more details see `the online documentation `_.""" ... def any() -> bool: - """Check if any data is waiting. + """Comprueba si hay datos en espera. (algún) - Example: ``uart.any()`` +Example: ``uart.any()`` - :return: ``True`` if any data is waiting, else ``False``. - """ +:return: ``True`` if any data is waiting, else ``False``.""" ... -def read(nbytes: Optional[int] = None) -> Optional[bytes]: - """Read bytes. +def read(nbytes: Optional[int]=None) -> Optional[bytes]: + """Lee bytes. (leer) - Example: ``uart.read()`` +Example: ``uart.read()`` - :param nbytes: If ``nbytes`` is specified then read at most that many bytes, otherwise read as many bytes as possible - :return: A bytes object or ``None`` on timeout - """ +:param nbytes: Si se especifica ``nbytes``, lee como máximo ese número de bytes; si no, lee tantos bytes como sea posible +:return: A bytes object or ``None`` on timeout""" ... -def readinto(buf: WriteableBuffer, nbytes: Optional[int] = None) -> Optional[int]: - """Read bytes into the ``buf``. +def readinto(buf: WriteableBuffer, nbytes: Optional[int]=None) -> Optional[int]: + """Lee bytes en el ``buf``. (leeren) - Example: ``uart.readinto(input_buffer)`` +Example: ``uart.readinto(input_buffer)`` - :param buf: The buffer to write to. - :param nbytes: If ``nbytes`` is specified then read at most that many bytes, otherwise read ``len(buf)`` bytes. - :return: number of bytes read and stored into ``buf`` or ``None`` on timeout. - """ +:param buf: (búf) El búfer en el que escribir. +:param nbytes: Si se especifica ``nbytes``, lee como máximo ese número de bytes; si no, lee ``len(buf)`` bytes. +:return: number of bytes read and stored into ``buf`` or ``None`` on timeout.""" ... def readline() -> Optional[bytes]: - """Read a line, ending in a newline character. + """Lee una línea, terminando en un carácter de nueva línea. (leerlínea) - Example: ``uart.readline()`` +Example: ``uart.readline()`` - :return: The line read or ``None`` on timeout. The newline character is included in the returned bytes. - """ +:return: The line read or ``None`` on timeout. The newline character is included in the returned bytes.""" ... def write(buf: Union[bytes, str]) -> Optional[int]: - """Write a buffer to the bus. + """Escribe un búfer en el bus. (escribir) - Example: ``uart.write('hello world')`` +Example: ``uart.write('hello world')`` - :param buf: A bytes object or a string. - :return: The number of bytes written, or ``None`` on timeout. +:param buf: (búf) Un objeto de bytes o una cadena. +:return: The number of bytes written, or ``None`` on timeout. - Examples:: +Examples:: - uart.write('hello world') - uart.write(b'hello world') - uart.write(bytes([1, 2, 3])) - """ - ... + uart.write('hello world') + uart.write(b'hello world') + uart.write(bytes([1, 2, 3]))""" + ... \ No newline at end of file diff --git a/lang/es-es/typeshed/stdlib/micropython.pyi b/lang/es-es/typeshed/stdlib/micropython.pyi index 7a6079f..21db84c 100644 --- a/lang/es-es/typeshed/stdlib/micropython.pyi +++ b/lang/es-es/typeshed/stdlib/micropython.pyi @@ -1,144 +1,132 @@ -"""MicroPython internals.""" - +"""Componentes internos de MicroPython.""" from typing import Any, TypeVar, overload - -_T = TypeVar("_T") +_T = TypeVar('_T') def const(expr: _T) -> _T: - """Used to declare that the expression is a constant so that the compiler can - optimise it. + """Se usa para declarar que la expresión es una constante para que el compilador pueda +optimizarla. - The use of this function should be as follows:: +The use of this function should be as follows:: - from micropython import const - CONST_X = const(123) - CONST_Y = const(2 * CONST_X + 1) + from micropython import const + CONST_X = const(123) + CONST_Y = const(2 * CONST_X + 1) - Constants declared this way are still accessible as global variables from - outside the module they are declared in. On the other hand, if a constant - begins with an underscore then it is hidden, it is not available as a - global variable, and does not take up any memory during execution. +Constants declared this way are still accessible as global variables from +outside the module they are declared in. On the other hand, if a constant +begins with an underscore then it is hidden, it is not available as a +global variable, and does not take up any memory during execution. - :param expr: A constant expression. - """ +:param expr: Una expresión constante.""" ... @overload def opt_level() -> int: - """Get the current optimisation level for the compilation of scripts. + """Obtiene el nivel actual de optimización para la compilación de scripts. (nivel de opt) - Example: ``micropython.opt_level()`` +Example: ``micropython.opt_level()`` - The optimisation level controls the following compilation features: +The optimisation level controls the following compilation features: - - Assertions: at level 0 assertion statements are enabled and compiled - into the bytecode; at levels 1 and higher assertions are not compiled. +- Assertions: at level 0 assertion statements are enabled and compiled + into the bytecode; at levels 1 and higher assertions are not compiled. - - Built-in ``__debug__`` variable: at level 0 this variable expands to - True; at levels 1 and higher it expands to False. +- Built-in ``__debug__`` variable: at level 0 this variable expands to + True; at levels 1 and higher it expands to False. - - Source-code line numbers: at levels 0, 1 and 2 source-code line number - are stored along with the bytecode so that exceptions can report the - line number they occurred at; at levels 3 and higher line numbers are - not stored. +- Source-code line numbers: at levels 0, 1 and 2 source-code line number + are stored along with the bytecode so that exceptions can report the + line number they occurred at; at levels 3 and higher line numbers are + not stored. - :return: An integer representing the current level. - """ +:return: An integer representing the current level.""" ... @overload def opt_level(level: int) -> None: - """Sets the optimisation level for subsequent compilation of scripts. + """Establece el nivel de optimización para la posterior compilación de scripts. (nivel de opt) - Example: ``micropython.opt_level(1)`` +Example: ``micropython.opt_level(1)`` - The optimisation level controls the following compilation features: +The optimisation level controls the following compilation features: - - Assertions: at level 0 assertion statements are enabled and compiled - into the bytecode; at levels 1 and higher assertions are not compiled. +- Assertions: at level 0 assertion statements are enabled and compiled + into the bytecode; at levels 1 and higher assertions are not compiled. - - Built-in ``__debug__`` variable: at level 0 this variable expands to - True; at levels 1 and higher it expands to False. +- Built-in ``__debug__`` variable: at level 0 this variable expands to + True; at levels 1 and higher it expands to False. - - Source-code line numbers: at levels 0, 1 and 2 source-code line number - are stored along with the bytecode so that exceptions can report the - line number they occurred at; at levels 3 and higher line numbers are - not stored. +- Source-code line numbers: at levels 0, 1 and 2 source-code line number + are stored along with the bytecode so that exceptions can report the + line number they occurred at; at levels 3 and higher line numbers are + not stored. - The default optimisation level is usually level 0. +The default optimisation level is usually level 0. - :param level: An integer optimisation level. - """ +:param level: (nivel) Un entero que representa el nivel de optimización.""" ... -def mem_info(verbose: Any = None) -> None: - """Print information about currently used memory. +def mem_info(verbose: Any=None) -> None: + """Imprime información sobre la memoria usada en este momento. (info de mem) - Example: ``micropython.mem_info()`` +Example: ``micropython.mem_info()`` - :param verbose: If the ``verbose`` argument is given then extra information is printed. - """ +:param verbose: Si se pasa el argumento ``verbose``, se imprime información adicional.""" ... -def qstr_info(verbose: Any = None) -> None: - """Print information about currently interned strings. +def qstr_info(verbose: Any=None) -> None: + """Imprime información sobre las cadenas internadas en este momento. (info de cad actual) - Example: ``micropython.qstr_info()`` +Example: ``micropython.qstr_info()`` - :param verbose: If the ``verbose`` argument is given then extra information is printed. +:param verbose: Si se pasa el argumento ``verbose``, se imprime información adicional. - The information that is printed is implementation dependent, but currently - includes the number of interned strings and the amount of RAM they use. In - verbose mode it prints out the names of all RAM-interned strings. - """ +The information that is printed is implementation dependent, but currently +includes the number of interned strings and the amount of RAM they use. In +verbose mode it prints out the names of all RAM-interned strings.""" ... def stack_use() -> int: - """Return an integer representing the current amount of stack that is being - used. + """Devuelve un entero que representa la cantidad de pila que se está usando en este momento. (pila usada) - Example: ``micropython.stack_use()`` +Example: ``micropython.stack_use()`` - The absolute value of this is not particularly useful, rather it - should be used to compute differences in stack usage at different points. +The absolute value of this is not particularly useful, rather it +should be used to compute differences in stack usage at different points. - :return: An integer representing current stack use. - """ +:return: An integer representing current stack use.""" ... def heap_lock() -> None: - """Lock the heap. + """Bloquea el montón. (bloquear montón) - Example: ``micropython.heap_lock()`` +Example: ``micropython.heap_lock()`` - When locked no memory allocation can occur and a ``MemoryError`` will be - raised if any heap allocation is attempted. - """ +When locked no memory allocation can occur and a ``MemoryError`` will be +raised if any heap allocation is attempted.""" ... def heap_unlock() -> None: - """Unlock the heap. + """Desbloquea el montón. (desbloquear el montón) - Example: ``micropython.heap_unlock()`` +Example: ``micropython.heap_unlock()`` - When locked no memory allocation can occur and a ``MemoryError`` will be - raised if any heap allocation is attempted. - """ +When locked no memory allocation can occur and a ``MemoryError`` will be +raised if any heap allocation is attempted.""" ... def kbd_intr(chr: int) -> None: - """Set the character that will raise a ``KeyboardInterrupt`` exception. + """Establece qué carácter lanzará una excepción ``KeyboardInterrupt``. (intr tecl) - Example: ``micropython.kbd_intr(-1)`` +Example: ``micropython.kbd_intr(-1)`` - :param chr: Character code to raise the interrupt or -1 to disable capture of Ctrl-C. +:param chr: (car) Código de carácter que lanzará la interrupción o -1 para desactivar la captura de Ctrl + C. - By default this is set to 3 during script execution, corresponding to Ctrl-C. - Passing -1 to this function will disable capture of Ctrl-C, and passing 3 - will restore it. +By default this is set to 3 during script execution, corresponding to Ctrl-C. +Passing -1 to this function will disable capture of Ctrl-C, and passing 3 +will restore it. - This function can be used to prevent the capturing of Ctrl-C on the - incoming stream of characters that is usually used for the REPL, in case - that stream is used for other purposes. - """ - ... +This function can be used to prevent the capturing of Ctrl-C on the +incoming stream of characters that is usually used for the REPL, in case +that stream is used for other purposes.""" + ... \ No newline at end of file diff --git a/lang/es-es/typeshed/stdlib/music.pyi b/lang/es-es/typeshed/stdlib/music.pyi index 5f4778b..9483beb 100644 --- a/lang/es-es/typeshed/stdlib/music.pyi +++ b/lang/es-es/typeshed/stdlib/music.pyi @@ -1,167 +1,128 @@ -"""Create and play melodies. -""" +"""Crear y reproducir melodías. (música)""" from typing import Optional, Tuple, Union, List - from .microbit import MicroBitDigitalPin, pin0 - DADADADUM: Tuple[str, ...] -"""Melody: the opening to Beethoven’s 5th Symphony in C minor.""" - +"""Melodía: apertura de la "Sinfonía n.º 5 en do menor" de Beethoven.""" ENTERTAINER: Tuple[str, ...] -"""Melody: the opening fragment of Scott Joplin’s Ragtime classic “The Entertainer”.""" - +"""Melodía: fragmento inicial del clásico Ragtime de Scott Joplin “The Entertainer”.""" PRELUDE: Tuple[str, ...] -"""Melody: the opening of the first Prelude in C Major of J.S.Bach’s 48 Preludes and Fugues.""" - +"""Melodía: apertura del primer "Preludio en do mayor" de los 48 Preludios y Fugas de J. S. Bach. (preludio)""" ODE: Tuple[str, ...] -"""Melody: the “Ode to Joy” theme from Beethoven’s 9th Symphony in D minor.""" - +"""Melodía: tema “Oda a la alegría” de la "Sinfonía n.º 9 en re menor" de Beethoven. (oda)""" NYAN: Tuple[str, ...] -"""Melody: the Nyan Cat theme (http://www.nyan.cat/). +"""Melodía: el tema de Nyan Cat (http://www.nyan.cat/). The composer is unknown. This is fair use for educational porpoises (as they say in New York).""" - RINGTONE: Tuple[str, ...] -"""Melody: something that sounds like a mobile phone ringtone. +"""Melodía: algo que suena como un tono de llamada de un teléfono móvil. (tono de llamada) To be used to indicate an incoming message. """ - FUNK: Tuple[str, ...] -"""Melody: a funky bass line for secret agents and criminal masterminds.""" - +"""Melodía: una línea de bajo funky para agentes secretos y maestros criminales.""" BLUES: Tuple[str, ...] -"""Melody: a boogie-woogie 12-bar blues walking bass.""" - +"""Melodía: "walking bass" con un blues boogie-woogie de 12 compases.""" BIRTHDAY: Tuple[str, ...] -"""Melody: “Happy Birthday to You…” +"""Melodía: “Cumpleaños feliz” (cumpleaños) For copyright status see: http://www.bbc.co.uk/news/world-us-canada-34332853 """ - WEDDING: Tuple[str, ...] -"""Melody: the bridal chorus from Wagner’s opera “Lohengrin”.""" - +"""Melodía: coro nupcial de la ópera de Wagner "Lohengrin". (boda)""" FUNERAL: Tuple[str, ...] -"""Melody: the “funeral march” otherwise known as Frédéric Chopin’s Piano Sonata No. 2 in B♭ minor, Op. 35.""" - +"""Melodía: “Marcha fúnebre”, conocida también como "Sonata para piano n.º 2 en si bemol menor, Op. 35" de Frédéric Chopin.""" PUNCHLINE: Tuple[str, ...] -"""Melody: a fun fragment that signifies a joke has been made.""" - +"""Melodía: un fragmento divertido que representa que se ha hecho un chiste. (remate)""" PYTHON: Tuple[str, ...] -"""Melody: John Philip Sousa’s march “Liberty Bell” aka, the theme for “Monty Python’s Flying Circus” (after which the Python programming language is named).""" - +"""Melodía: la marcha de John Philip Sousa “Liberty Bell”, también conocida por ser el tema del “Monty Python Flying Circus” (de donde obtiene su nombre el lenguaje de programación Python).""" BADDY: Tuple[str, ...] -"""Melody: silent movie era entrance of a baddy.""" - +"""Melodía: entrada de un malote en la época del cine mudo. (malote)""" CHASE: Tuple[str, ...] -"""Melody: silent movie era chase scene.""" - +"""Melodía: escena de persecución en la época del cine mudo. (persecución)""" BA_DING: Tuple[str, ...] -"""Melody: a short signal to indicate something has happened.""" - +"""Melodía: una señal corta para indicar que algo ha pasado.""" WAWAWAWAA: Tuple[str, ...] -"""Melody: a very sad trombone.""" - +"""Melodía: un trombón muy triste.""" JUMP_UP: Tuple[str, ...] -"""Melody: for use in a game, indicating upward movement.""" - +"""Melodía: para usar en un juego, indicando un movimiento ascendente. (saltar arriba)""" JUMP_DOWN: Tuple[str, ...] -"""Melody: for use in a game, indicating downward movement.""" - +"""Melodía: para usar en un juego, indicando un movimiento descendente. (saltar abajo)""" POWER_UP: Tuple[str, ...] -"""Melody: a fanfare to indicate an achievement unlocked.""" - +"""Melodía: una fanfarria para indicar un logro desbloqueado. (subida de potencia)""" POWER_DOWN: Tuple[str, ...] -"""Melody: a sad fanfare to indicate an achievement lost.""" +"""Melodía: una fanfarria triste para indicar un logro perdido. (bajada de potencia)""" -def set_tempo(ticks: int = 4, bpm: int = 120) -> None: - """Sets the approximate tempo for playback. +def set_tempo(ticks: int=4, bpm: int=120) -> None: + """Establece el ritmo aproximado de la reproducción. (configurar tempo) - Example: ``music.set_tempo(bpm=120)`` +Example: ``music.set_tempo(bpm=120)`` - :param ticks: The number of ticks constituting a beat. - :param bpm: An integer determining how many beats per minute. +:param ticks: (tics) El número de tics que constituyen un ritmo. +:param bpm: Un entero que determina el número de compases por minuto. - Suggested default values allow the following useful behaviour: +Suggested default values allow the following useful behaviour: - - music.set_tempo() – reset the tempo to default of ticks = 4, bpm = 120 - - music.set_tempo(ticks=8) – change the “definition” of a beat - - music.set_tempo(bpm=180) – just change the tempo +- music.set_tempo() – reset the tempo to default of ticks = 4, bpm = 120 +- music.set_tempo(ticks=8) – change the “definition” of a beat +- music.set_tempo(bpm=180) – just change the tempo - To work out the length of a tick in milliseconds is very simple arithmetic: - 60000/bpm/ticks_per_beat. For the default values that’s - 60000/120/4 = 125 milliseconds or 1 beat = 500 milliseconds. - """ +To work out the length of a tick in milliseconds is very simple arithmetic: +60000/bpm/ticks_per_beat. For the default values that’s +60000/120/4 = 125 milliseconds or 1 beat = 500 milliseconds.""" ... def get_tempo() -> Tuple[int, int]: - """Gets the current tempo as a tuple of integers: ``(ticks, bpm)``. + """Obtiene el ritmo actual como una tupla de enteros: ``(ticks, bpm)``. (obtener tempo) - Example: ``ticks, beats = music.get_tempo()`` +Example: ``ticks, beats = music.get_tempo()`` - :return: The temp as a tuple with two integer values, the ticks then the beats per minute. - """ +:return: The temp as a tuple with two integer values, the ticks then the beats per minute.""" ... -def play( - music: Union[str, List[str], Tuple[str, ...]], - pin: Optional[MicroBitDigitalPin] = pin0, - wait: bool = True, - loop: bool = False, -) -> None: - """Plays music. +def play(music: Union[str, List[str], Tuple[str, ...]], pin: Optional[MicroBitDigitalPin]=pin0, wait: bool=True, loop: bool=False) -> None: + """Reproduce música. (reproducir) - Example: ``music.play(music.NYAN)`` +Example: ``music.play(music.NYAN)`` - :param music: music specified in `a special notation `_ - :param pin: the output pin for use with an external speaker (default ``pin0``), ``None`` for no sound. - :param wait: If ``wait`` is set to ``True``, this function is blocking. - :param loop: If ``loop`` is set to ``True``, the tune repeats until ``stop`` is called or the blocking call is interrupted. +:param music: (música) música especificada en `una notación especial `_ +:param pin: pin de salida para usar con un altavoz externo (por defecto ``pin0``), ``None`` para que no haya sonido. +:param wait: (esperar) Si ``wait`` se configura como ``True`` (verdadero), esta función estará bloqueando. +:param loop: (bucle) Si ``loop`` se configura como ``True`` (verdadero), la melodía se repite hasta que se llama a ``stop`` o se interrumpe la llamada de bloqueo. - Many built-in melodies are defined in this module. - """ +Many built-in melodies are defined in this module.""" ... -def pitch( - frequency: int, - duration: int = -1, - pin: Optional[MicroBitDigitalPin] = pin0, - wait: bool = True, -) -> None: - """Play a note. +def pitch(frequency: int, duration: int=-1, pin: Optional[MicroBitDigitalPin]=pin0, wait: bool=True) -> None: + """Reproduce una nota. (tono) - Example: ``music.pitch(185, 1000)`` +Example: ``music.pitch(185, 1000)`` - :param frequency: An integer frequency - :param duration: A millisecond duration. If negative then sound is continuous until the next call or a call to ``stop``. - :param pin: Optional output pin (default ``pin0``). - :param wait: If ``wait`` is set to ``True``, this function is blocking. +:param frequency: (frecuencia) Una frecuencia entera +:param duration: (duración) La duración en milisegundos. Si es negativa, el sonido continuará hasta la siguiente llamada o una llamada a ``stop``. +:param pin: Pin de salida opcional (por defecto, ``pin0``). +:param wait: (esperar) Si ``wait`` se configura como ``True`` (verdadero), esta función estará bloqueando. - For example, if the frequency is set to 440 and the length to - 1000 then we hear a standard concert A for one second. +For example, if the frequency is set to 440 and the length to +1000 then we hear a standard concert A for one second. - You can only play one pitch on one pin at any one time. - """ +You can only play one pitch on one pin at any one time.""" ... -def stop(pin: Optional[MicroBitDigitalPin] = pin0) -> None: - """Stops all music playback on the built-in speaker and any pin outputting sound. +def stop(pin: Optional[MicroBitDigitalPin]=pin0) -> None: + """Detiene la reproducción de toda la música en el altavoz integrado y en cualquier pin que esté emitiendo sonido. (detener) - Example: ``music.stop()`` +Example: ``music.stop()`` - :param pin: An optional argument can be provided to specify a pin, e.g. ``music.stop(pin1)``. - """ +:param pin: Se puede proporcionar un argumento opcional para especificar un pin; por ejemplo, ``music.stop(pin1)``.""" def reset() -> None: - """Resets ticks, bpm, duration and octave to their default values. + """Restablece los valores de "ticks", "bpm", "duration" y "octave" a sus valores por defecto. (restablecer) - Example: ``music.reset()`` +Example: ``music.reset()`` - Values: - - ``ticks = 4`` - - ``bpm = 120`` - - ``duration = 4`` - - ``octave = 4`` - """ - ... +Values: +- ``ticks = 4`` +- ``bpm = 120`` +- ``duration = 4`` +- ``octave = 4``""" + ... \ No newline at end of file diff --git a/lang/es-es/typeshed/stdlib/neopixel.pyi b/lang/es-es/typeshed/stdlib/neopixel.pyi index 2d5a749..03d4025 100644 --- a/lang/es-es/typeshed/stdlib/neopixel.pyi +++ b/lang/es-es/typeshed/stdlib/neopixel.pyi @@ -1,82 +1,81 @@ -"""Individually addressable RGB and RGBW LED strips. -""" +"""Tiras de LED RGB y RGBW accesibles individualmente.""" from .microbit import MicroBitDigitalPin from typing import Tuple class NeoPixel: - def __init__(self, pin: MicroBitDigitalPin, n: int, bpp: int = 3) -> None: - """Initialise a new strip of neopixel LEDs controlled via a pin. - Example: ``np = neopixel.NeoPixel(pin0, 8)`` + def __init__(self, pin: MicroBitDigitalPin, n: int, bpp: int=3) -> None: + """Inicializa una nueva tira de LED NeoPixel controlada a través de un pin. - To support RGBW neopixels, a third argument can be passed to - ``NeoPixel`` to indicate the number of bytes per pixel (``bpp``). - For RGBW, this is is 4 rather than the default of 3 for RGB and GRB. +Example: ``np = neopixel.NeoPixel(pin0, 8)`` - Each pixel is addressed by a position (starting from 0). Neopixels are - given RGB (red, green, blue) / RGBW (red, green, blue, white) values - between 0-255 as a tuple. For example, in RGB, ``(255,255,255)`` is - white. In RGBW, ``(255,255,255,0)`` or ``(0,0,0,255)`` is white. +To support RGBW neopixels, a third argument can be passed to +``NeoPixel`` to indicate the number of bytes per pixel (``bpp``). +For RGBW, this is is 4 rather than the default of 3 for RGB and GRB. - See `the online docs `_ for warnings and other advice. +Each pixel is addressed by a position (starting from 0). Neopixels are +given RGB (red, green, blue) / RGBW (red, green, blue, white) values +between 0-255 as a tuple. For example, in RGB, ``(255,255,255)`` is +white. In RGBW, ``(255,255,255,0)`` or ``(0,0,0,255)`` is white. - :param pin: The pin controlling the neopixel strip. - :param n: The number of neopixels in the strip. - :param bpp: Bytes per pixel. For RGBW neopixel support, pass 4 rather than the default of 3 for RGB and GRB. - """ +See `the online docs `_ for warnings and other advice. + +:param pin: El pin que controla la tira NeoPixel. +:param n: El número de LED NeoPixel de la tira. +:param bpp: Bytes por píxel. Para compatibilidad de neopíxeles RGBW, pasa 4 en lugar del valor predeterminado de 3 para RGB y GRB.""" ... + def clear(self) -> None: - """Clear all the pixels. + """Borrar todos los píxeles. (borrar) - Example: ``np.clear()`` - """ +Example: ``np.clear()``""" ... + def show(self) -> None: - """Show the pixels. + """Muestra los píxeles. (mostrar) - Example: ``np.show()`` +Example: ``np.show()`` - Must be called for any updates to become visible. - """ +Must be called for any updates to become visible.""" ... + def write(self) -> None: - """Show the pixels (micro:bit V2 only). + """Muestra los píxeles (solo micro:bit V2). (escribir) - Example: ``np.write()`` +Example: ``np.write()`` - Must be called for any updates to become visible. +Must be called for any updates to become visible. - Equivalent to ``show``. - """ +Equivalent to ``show``.""" ... + def fill(self, colour: Tuple[int, ...]) -> None: - """Colour all pixels a given RGB/RGBW value (micro:bit V2 only). + """Colorea todos los píxeles con un valor RGB/RGBW dado (solo micro:bit V2). (llenar) - Example: ``np.fill((0, 0, 255))`` +Example: ``np.fill((0, 0, 255))`` - :param colour: A tuple of the same length as the number of bytes per pixel (bpp). +:param colour: (color) Una tupla de la misma longitud que el número de bytes por píxel (bpp). - Use in conjunction with ``show()`` to update the neopixels. - """ +Use in conjunction with ``show()`` to update the neopixels.""" ... + def __setitem__(self, key: int, value: Tuple[int, ...]) -> None: - """Set a pixel colour. + """Establece el color de un píxel. (configurar elemento) - Example: ``np[0] = (255, 0, 0)`` +Example: ``np[0] = (255, 0, 0)`` + +:param key: (clave) El número de píxel. +:param value: (valor) El color.""" - :param key: The pixel number. - :param value: The colour. - """ def __getitem__(self, key: int) -> Tuple[int, ...]: - """Get a pixel colour. + """Obtiene el color de un píxel. (obtener elemento) + +Example: ``r, g, b = np[0]`` - Example: ``r, g, b = np[0]`` +:param key: (clave) El número de píxel. +:return: The colour tuple.""" - :param key: The pixel number. - :return: The colour tuple. - """ def __len__(self) -> int: - """Get length of this pixel strip. + """Obtiene la longitud de esta tira de píxeles. (lon) - Example: ``len(np)`` - """ +Example: ``len(np)``""" \ No newline at end of file diff --git a/lang/es-es/typeshed/stdlib/os.pyi b/lang/es-es/typeshed/stdlib/os.pyi index 2f2db77..ac41541 100644 --- a/lang/es-es/typeshed/stdlib/os.pyi +++ b/lang/es-es/typeshed/stdlib/os.pyi @@ -1,73 +1,63 @@ -"""Access the file system. -""" - +"""Acceder al sistema de archivos. (so)""" from typing import Tuple from typing import List def listdir() -> List[str]: - """List files. + """Lista los archivos. - Example: ``os.listdir()`` +Example: ``os.listdir()`` - :return: A list of the names of all the files contained within the local - persistent on-device file system. - """ +:return: A list of the names of all the files contained within the local +persistent on-device file system.""" ... def remove(filename: str) -> None: - """Remove (delete) a file. + """Elimina un archivo. (eliminar) - Example: ``os.remove('data.txt')`` +Example: ``os.remove('data.txt')`` - :param filename: The file to delete. +:param filename: (nombre del archivo) El archivo a eliminar. - If the file does not exist an ``OSError`` exception will occur. - """ +If the file does not exist an ``OSError`` exception will occur.""" ... def size(filename: str) -> int: - """Returns the size of a file. + """Devuelve el tamaño de un archivo. (tamaño) - Example: ``os.size('data.txt')`` +Example: ``os.size('data.txt')`` - :param filename: The file - :return: The size in bytes. +:param filename: (nombre del archivo) El archivo +:return: The size in bytes. - If the file does not exist an ``OSError`` exception will occur. - """ +If the file does not exist an ``OSError`` exception will occur.""" class uname_result(Tuple[str, str, str, str, str]): - """Result of ``os.uname()``""" + """Resultado de ``os.uname()`` (resultado de nombreu)""" sysname: str - """Operating system name.""" - + """Nombre del sistema operativo. (nombre del sistema)""" nodename: str - """Name of machine on network (implementation-defined).""" - + """Nombre de la máquina en la red (definida por la implementación). (nombre del nodo)""" release: str - """Operating system release.""" - + """Versión de lanzamiento del sistema operativo. (lanzamiento)""" version: str - """Operating system version.""" - + """Versión del sistema operativo. (versión)""" machine: str - """Hardware identifier.""" + """Identificador de hardware. (máquina)""" def uname() -> uname_result: - """Returns information identifying the current operating system. + """Devuelve información que identifica el sistema operativo actual. (nombreu) - Example: ``os.uname()`` +Example: ``os.uname()`` - The return value is an object with five attributes: +The return value is an object with five attributes: - - ``sysname`` - operating system name - - ``nodename`` - name of machine on network (implementation-defined) - - ``release`` - operating system release - - ``version`` - operating system version - - ``machine`` - hardware identifier +- ``sysname`` - operating system name +- ``nodename`` - name of machine on network (implementation-defined) +- ``release`` - operating system release +- ``version`` - operating system version +- ``machine`` - hardware identifier - There is no underlying operating system in MicroPython. As a result the - information returned by the ``uname`` function is mostly useful for - versioning details. - """ - ... +There is no underlying operating system in MicroPython. As a result the +information returned by the ``uname`` function is mostly useful for +versioning details.""" + ... \ No newline at end of file diff --git a/lang/es-es/typeshed/stdlib/radio.pyi b/lang/es-es/typeshed/stdlib/radio.pyi index 8dd0267..dfb8031 100644 --- a/lang/es-es/typeshed/stdlib/radio.pyi +++ b/lang/es-es/typeshed/stdlib/radio.pyi @@ -1,152 +1,130 @@ -"""Communicate between micro:bits with the built-in radio. -""" - +"""Comunicarse entre micro:bits con la radio incorporada.""" from _typeshed import WriteableBuffer from typing import Optional, Tuple - RATE_1MBIT: int -"""Constant used to indicate a throughput of 1 MBit a second.""" - +"""Constante utilizada para indicar un rendimiento de 1 Mb por segundo. (tasa de 1 mbit)""" RATE_2MBIT: int -"""Constant used to indicate a throughput of 2 MBit a second.""" +"""Constante utilizada para indicar un rendimiento de 2 Mb por segundo. (tasa de 2 mbit)""" def on() -> None: - """Turns the radio on. + """Enciende la radio. (encender) - Example: ``radio.on()`` +Example: ``radio.on()`` - This needs to be explicitly called since the radio draws power and takes - up memory that you may otherwise need. - """ +This needs to be explicitly called since the radio draws power and takes +up memory that you may otherwise need.""" ... def off() -> None: - """Turns off the radio, saving power and memory. + """Apaga la radio, ahorrando energía y memoria. (apagado) - Example: ``radio.off()`` - """ +Example: ``radio.off()``""" ... -def config( - length: int = 32, - queue: int = 3, - channel: int = 7, - power: int = 6, - address: int = 0x75626974, - group: int = 0, - data_rate: int = RATE_1MBIT, -) -> None: - """Configures the radio. - - Example: ``radio.config(group=42)`` - - The default configuration is suitable for most use. - - :param length: (default=32) defines the maximum length, in bytes, of a message sent via the radio. - It can be up to 251 bytes long (254 - 3 bytes for S0, LENGTH and S1 preamble). - :param queue: (default=3) specifies the number of messages that can be stored on the incoming message queue. - If there are no spaces left on the queue for incoming messages, then the incoming message is dropped. - :param channel: (default=7) an integer value from 0 to 83 (inclusive) that defines an arbitrary "channel" to which the radio is tuned. - Messages will be sent via this channel and only messages received via this channel will be put onto the incoming message queue. Each step is 1MHz wide, based at 2400MHz. - :param power: (default=6) is an integer value from 0 to 7 (inclusive) to indicate the strength of signal used when broadcasting a message. - The higher the value the stronger the signal, but the more power is consumed by the device. The numbering translates to positions in the following list of dBm (decibel milliwatt) values: -30, -20, -16, -12, -8, -4, 0, 4. - :param address: (default=0x75626974) an arbitrary name, expressed as a 32-bit address, that's used to filter incoming packets at the hardware level, keeping only those that match the address you set. - The default used by other micro:bit related platforms is the default setting used here. - :param group: (default=0) an 8-bit value (0-255) used with the ``address`` when filtering messages. - Conceptually, "address" is like a house/office address and "group" is like the person at that address to which you want to send your message. - :param data_rate: (default=``radio.RATE_1MBIT``) indicates the speed at which data throughput takes place. - Can be one of the following constants defined in the ``radio`` module: ``RATE_250KBIT``, ``RATE_1MBIT`` or ``RATE_2MBIT``. - - If ``config`` is not called then the defaults described above are assumed. - """ +def config(length: int=32, queue: int=3, channel: int=7, power: int=6, address: int=1969383796, group: int=0, data_rate: int=RATE_1MBIT) -> None: + """Configura la radio. + +Example: ``radio.config(group=42)`` + +The default configuration is suitable for most use. + +:param length: (longitud) (valor predeterminado = 32) define la longitud máxima, en bytes, de un mensaje enviado a través de la radio. +Puede tener hasta 251 bytes de largo (254 - 3 bytes para preámbulos S0, LENGTH y S1). +:param queue: (cola) (valor predeterminado = 3) especifica el número de mensajes que pueden almacenarse en la cola de mensajes entrantes. +Si no quedan espacios en la cola para los mensajes entrantes, el mensaje entrante será eliminado. +:param channel: (canal) (valor predeterminado = 7) un valor entero de 0 a 83 (inclusive) que define un "canal" arbitrario en el cual la radio está sintonizada. +Los mensajes se enviarán a través de este canal y solo los mensajes recibidos a través de este canal se pondrán en la cola de mensajes entrantes. Cada paso es de 1 MHz de ancho, basado en 2400 MHz. +:param power: (potencia) (valor predeterminado = 6) es un valor entero de 0 a 7 (inclusive) para indicar la fuerza de la señal usada al transmitir un mensaje. +Cuanto más alto sea el valor, más fuerte es la señal, pero más energía consume el dispositivo. La numeración se traduce a posiciones en la siguiente lista de valores de dBm (decibelio-milivatio): -30, -20, -16, -12, -8, -4, 0, 4. +:param address: (dirección) (valor predeterminado = 0x75626974) un nombre arbitrario, expresado como una dirección de 32 bits, que se usa para filtrar los paquetes entrantes a nivel de hardware, manteniendo solo aquellos que coincidan con la dirección que has establecido. +El valor predeterminado utilizado por otras plataformas relacionadas con el micro:bit es la configuración predeterminada utilizada aquí. +:param group: (grupo) (valor predeterminado = 0) un valor de 8 bits (0 - 255) usado con el valor de ``address`` al filtrar mensajes. +Conceptualmente, "address" (dirección) es como una dirección de casa u oficina y "group" (grupo) es la persona que está en esa dirección y a la que quieres enviar un mensaje. +:param data_rate: (tasa de datos) (valor predeterminado = ``radio.RATE_1MBIT``) indica la velocidad a la que se lleva a cabo el procesamiento de datos. +Puede ser una de las siguientes constantes definidas en el módulo ``radio``: ``RATE_250KBIT``, ``RATE_1MBIT`` o ``RATE_2MBIT``. + +If ``config`` is not called then the defaults described above are assumed.""" ... def reset() -> None: - """Reset the settings to their default values. + """Restablece la configuración a sus valores predeterminados. (restablecer) - Example: ``radio.reset()`` +Example: ``radio.reset()`` - The defaults as as per the ``config`` function above. - """ +The defaults as as per the ``config`` function above.""" ... def send_bytes(message: bytes) -> None: - """Sends a message containing bytes. + """Envía un mensaje que contiene bytes. (enviar bytes) - Example: ``radio.send_bytes(b'hello')`` +Example: ``radio.send_bytes(b'hello')`` - :param message: The bytes to send. - """ +:param message: (mensaje) Los bytes a enviar.""" ... def receive_bytes() -> Optional[bytes]: - """Receive the next incoming message on the message queue. + """Recibe el siguiente mensaje entrante en la cola de mensajes. (recibir bytes) - Example: ``radio.receive_bytes()`` +Example: ``radio.receive_bytes()`` - :return: The message bytes if any, otherwise ``None``. - """ +:return: The message bytes if any, otherwise ``None``.""" ... def receive_bytes_into(buffer: WriteableBuffer) -> Optional[int]: - """Copy the next incoming message on the message queue into a buffer. + """Copia el siguiente mensaje entrante de la cola de mensajes en un búfer. (recibir bytes en) - Example: ``radio.receive_bytes_info(buffer)`` +Example: ``radio.receive_bytes_info(buffer)`` - :param buffer: The target buffer. The message is truncated if larger than the buffer. - :return: ``None`` if there are no pending messages, otherwise it returns the length of the message (which might be more than the length of the buffer). - """ +:param buffer: (búfer) El búfer de destino. El mensaje se trunca si es más grande que el búfer. +:return: ``None`` if there are no pending messages, otherwise it returns the length of the message (which might be more than the length of the buffer).""" ... def send(message: str) -> None: - """Sends a message string. + """Envía una cadena de mensaje. (enviar) - Example: ``radio.send('hello')`` +Example: ``radio.send('hello')`` - This is the equivalent of ``radio.send_bytes(bytes(message, 'utf8'))`` but with ``b'\x01\x00\x01'`` - prepended to the front (to make it compatible with other platforms that target the micro:bit). +This is the equivalent of ``radio.send_bytes(bytes(message, 'utf8'))`` but with ``b'\x01\x00\x01'`` +prepended to the front (to make it compatible with other platforms that target the micro:bit). - :param message: The string to send. - """ +:param message: (mensaje) La cadena a enviar.""" ... def receive() -> Optional[str]: - """Works in exactly the same way as ``receive_bytes`` but returns whatever was sent. + """Funciona exactamente del mismo modo que ``receive_bytes``, pero devuelve lo que se envió. (recibir) - Example: ``radio.receive()`` +Example: ``radio.receive()`` - Equivalent to ``str(receive_bytes(), 'utf8')`` but with a check that the the first - three bytes are ``b'\x01\x00\x01'`` (to make it compatible with other platforms that - may target the micro:bit). +Equivalent to ``str(receive_bytes(), 'utf8')`` but with a check that the the first +three bytes are ``b'\x01\x00\x01'`` (to make it compatible with other platforms that +may target the micro:bit). - :return: The message with the prepended bytes stripped and converted to a string. +:return: The message with the prepended bytes stripped and converted to a string. - A ``ValueError`` exception is raised if conversion to string fails. - """ +A ``ValueError`` exception is raised if conversion to string fails.""" ... def receive_full() -> Optional[Tuple[bytes, int, int]]: - """Returns a tuple containing three values representing the next incoming message on the message queue. + """Devuelve una tupla de tres valores que representan el siguiente mensaje entrante de la cola de mensajes. (recibir completo) - Example: ``radio.receive_full()`` +Example: ``radio.receive_full()`` - If there are no pending messages then ``None`` is returned. +If there are no pending messages then ``None`` is returned. - The three values in the tuple represent: +The three values in the tuple represent: - - the next incoming message on the message queue as bytes. - - the RSSI (signal strength): a value between 0 (strongest) and -255 (weakest) as measured in dBm. - - a microsecond timestamp: the value returned by ``time.ticks_us()`` when the message was received. +- the next incoming message on the message queue as bytes. +- the RSSI (signal strength): a value between 0 (strongest) and -255 (weakest) as measured in dBm. +- a microsecond timestamp: the value returned by ``time.ticks_us()`` when the message was received. - For example:: +For example:: - details = radio.receive_full() - if details: - msg, rssi, timestamp = details + details = radio.receive_full() + if details: + msg, rssi, timestamp = details - This function is useful for providing information needed for triangulation - and/or trilateration with other micro:bit devices. +This function is useful for providing information needed for triangulation +and/or trilateration with other micro:bit devices. - :return: ``None`` if there is no message, otherwise a tuple of length three with the bytes, strength and timestamp values. - """ - ... +:return: ``None`` if there is no message, otherwise a tuple of length three with the bytes, strength and timestamp values.""" + ... \ No newline at end of file diff --git a/lang/es-es/typeshed/stdlib/random.pyi b/lang/es-es/typeshed/stdlib/random.pyi index a2c2ef3..a1e6d13 100644 --- a/lang/es-es/typeshed/stdlib/random.pyi +++ b/lang/es-es/typeshed/stdlib/random.pyi @@ -1,93 +1,80 @@ -"""Generate random numbers. -""" +"""Generar números aleatorios. (aleatorio)""" from typing import TypeVar, Sequence, Union, overload def getrandbits(n: int) -> int: - """Generate an integer with ``n`` random bits. + """Genera un entero con ``n`` bits aleatorios. - Example: ``random.getrandbits(1)`` +Example: ``random.getrandbits(1)`` - :param n: A value between 1-30 (inclusive). - """ +:param n: Un valor entre 1 - 30 (inclusive).""" ... def seed(n: int) -> None: - """Initialize the random number generator. + """Inicializa el generador de números aleatorios. (semilla) - Example: ``random.seed(0)`` +Example: ``random.seed(0)`` - :param n: The integer seed +:param n: La semilla como un número entero - This will give you reproducibly deterministic randomness from a given starting - state (``n``). - """ +This will give you reproducibly deterministic randomness from a given starting +state (``n``).""" ... def randint(a: int, b: int) -> int: - """Choose a random integer between ``a`` and ``b`` inclusive. + """Elige un entero aleatorio entre ``a`` y ``b`` inclusive. (entero aleatorio) - Example: ``random.randint(0, 9)`` +Example: ``random.randint(0, 9)`` - :param a: Start value for the range (inclusive) - :param b: End value for the range (inclusive) +:param a: Valor inicial para el rango (inclusive) +:param b: Valor final para el rango (inclusive) - Alias for ``randrange(a, b + 1)``. - """ +Alias for ``randrange(a, b + 1)``.""" ... @overload def randrange(stop: int) -> int: - """Choose a randomly selected integer between zero and up to (but not - including) ``stop``. + """Elige un entero seleccionado aleatoriamente desde cero hasta (pero sin incluir) ``stop``. (rango aleatorio) - Example: ``random.randrange(10)`` +Example: ``random.randrange(10)`` - :param stop: End value for the range (exclusive) - """ +:param stop: (detener) Valor final para el rango (exclusivo)""" ... @overload -def randrange(start: int, stop: int, step: int = 1) -> int: - """ - Choose a randomly selected element from ``range(start, stop, step)``. +def randrange(start: int, stop: int, step: int=1) -> int: + """Elige un elemento seleccionado aleatoriamente de ``range(start, stop, step)``. (rango aleatorio) - Example: ``random.randrange(0, 10)`` +Example: ``random.randrange(0, 10)`` - :param start: The start of the range (inclusive) - :param stop: The end of the range (exclusive) - :param step: The step. - """ +:param start: (comenzar) El inicio del rango (inclusive) +:param stop: (detener) El final del rango (exclusivo) +:param step: (paso) El paso.""" ... - -_T = TypeVar("_T") +_T = TypeVar('_T') def choice(seq: Sequence[_T]) -> _T: - """Choose a random element from the non-empty sequence ``seq``. + """Elige un elemento aleatorio de la secuencia no vacía ``seq``. (elección) - Example: ``random.choice([Image.HAPPY, Image.SAD])`` +Example: ``random.choice([Image.HAPPY, Image.SAD])`` - :param seq: A sequence. +:param seq: (sec) Una secuencia. - If ``seq`` is empty, raises ``IndexError``. - """ +If ``seq`` is empty, raises ``IndexError``.""" ... def random() -> float: - """Generate a random floating point number in the range [0.0, 1.0). + """Genera un número de coma flotante aleatorio en el rango [0.0, 1.0). (aleatorio) - Example: ``random.random()`` +Example: ``random.random()`` - :return: The random floating point number - """ +:return: The random floating point number""" ... def uniform(a: float, b: float) -> float: - """ - Return a random floating point number between ``a`` and ``b`` inclusive. + """Devuelve un número de coma flotante aleatorio entre ``a`` y ``b`` inclusive. (uniforme) - Example: ``random.uniform(0, 9)`` +Example: ``random.uniform(0, 9)`` - :param a: Start value for the range (inclusive) - :param b: End value for the range (inclusive) - """ - ... +:param a: Valor inicial para el rango (inclusive) +:param b: Valor final para el rango (inclusive)""" + ... \ No newline at end of file diff --git a/lang/es-es/typeshed/stdlib/speech.pyi b/lang/es-es/typeshed/stdlib/speech.pyi index 349d188..7494036 100644 --- a/lang/es-es/typeshed/stdlib/speech.pyi +++ b/lang/es-es/typeshed/stdlib/speech.pyi @@ -1,106 +1,79 @@ -"""Make the micro:bit talk, sing and make other speech like sounds. -""" - +"""Hacer que el micro:bit hable, cante y haga otros sonidos parecidos a la voz. (habla)""" from typing import Optional from .microbit import MicroBitDigitalPin, pin0 def translate(words: str) -> str: - """Translate English words to phonemes. + """Traducir palabras en inglés a fonemas. (traducir) - Example: ``speech.translate('hello world')`` +Example: ``speech.translate('hello world')`` - :param words: A string of English words. - :return: A string containing a best guess at the appropriate phonemes to pronounce. - The output is generated from this `text to phoneme translation table `_. +:param words: (palabras) Una cadena de palabras en inglés. +:return: A string containing a best guess at the appropriate phonemes to pronounce. +The output is generated from this `text to phoneme translation table `_. - This function should be used to generate a first approximation of phonemes - that can be further hand-edited to improve accuracy, inflection and - emphasis. +This function should be used to generate a first approximation of phonemes +that can be further hand-edited to improve accuracy, inflection and +emphasis. - See `the online documentation `_ for detailed information. - """ +See `the online documentation `_ for detailed information.""" ... -def pronounce( - phonemes: str, - pitch: int = 64, - speed: int = 72, - mouth: int = 128, - throat: int = 128, - pin: Optional[MicroBitDigitalPin] = pin0, -) -> None: - """Pronounce phonemes. - - Example: ``speech.pronounce(' /HEHLOW WERLD')`` - - :param phonemes: The string of phonemes to pronounce - :param pitch: A number representing the pitch of the voice - :param speed: A number representing the speed of the voice - :param mouth: A number representing the mouth of the voice - :param throat: A number representing the throat of the voice - :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. - If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. - - Override the optional pitch, speed, mouth and throat settings to change the - timbre (quality) of the voice. - - See `the online documentation `_ for detailed information. - """ - ... +def pronounce(phonemes: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: Optional[MicroBitDigitalPin]=pin0) -> None: + """Pronunciar fonemas. (pronunciar) + +Example: ``speech.pronounce(' /HEHLOW WERLD')`` + +:param phonemes: (fonemas) La cadena de fonemas a pronunciar +:param pitch: (tono) Un número que representa el tono de la voz +:param speed: (velocidad) Un número que representa la velocidad de la voz +:param mouth: (boca) Un número que representa la boca de la voz +:param throat: (garganta) Un número que representa la garganta de la voz +:param pin: Se puede usar un argumento opcional para especificar el pin de salida, reemplazando el valor predeterminado de ``pin0``. +Si no queremos que se reproduzca ningún sonido, podemos usar ``pin=None``. Solo para el micro:bit V2. -def say( - words: str, - pitch: int = 64, - speed: int = 72, - mouth: int = 128, - throat: int = 128, - pin: MicroBitDigitalPin = pin0, -) -> None: - """Say English words. - - Example: ``speech.say('hello world')`` - - :param words: The string of words to say. - :param pitch: A number representing the pitch of the voice - :param speed: A number representing the speed of the voice - :param mouth: A number representing the mouth of the voice - :param throat: A number representing the throat of the voice - :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. - If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. - - The result is semi-accurate for English. Override the optional pitch, speed, - mouth and throat settings to change the timbre (quality) of the voice. - - This is a short-hand equivalent of: - ``speech.pronounce(speech.translate(words))`` - - See `the online documentation `_ for detailed information. - """ +Override the optional pitch, speed, mouth and throat settings to change the +timbre (quality) of the voice. + +See `the online documentation `_ for detailed information.""" ... -def sing( - phonemes: str, - pitch: int = 64, - speed: int = 72, - mouth: int = 128, - throat: int = 128, - pin: MicroBitDigitalPin = pin0, -) -> None: - """Sing phonemes. - - Example: ``speech.sing(' /HEHLOW WERLD')`` - - :param phonemes: The string of words to sing. - :param pitch: A number representing the pitch of the voice - :param speed: A number representing the speed of the voice - :param mouth: A number representing the mouth of the voice - :param throat: A number representing the throat of the voice - :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. - If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. - - Override the optional pitch, speed, mouth and throat settings to change - the timbre (quality) of the voice. - - See `the online documentation `_ for detailed information. - """ +def say(words: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: MicroBitDigitalPin=pin0) -> None: + """Dice palabras en inglés. (decir) + +Example: ``speech.say('hello world')`` + +:param words: (palabras) La cadena de palabras a decir. +:param pitch: (tono) Un número que representa el tono de la voz +:param speed: (velocidad) Un número que representa la velocidad de la voz +:param mouth: (boca) Un número que representa la boca de la voz +:param throat: (garganta) Un número que representa la garganta de la voz +:param pin: Se puede usar un argumento opcional para especificar el pin de salida, reemplazando el valor predeterminado de ``pin0``. +Si no queremos que se reproduzca ningún sonido, podemos usar ``pin=None``. Solo para el micro:bit V2. + +The result is semi-accurate for English. Override the optional pitch, speed, +mouth and throat settings to change the timbre (quality) of the voice. + +This is a short-hand equivalent of: +``speech.pronounce(speech.translate(words))`` + +See `the online documentation `_ for detailed information.""" ... + +def sing(phonemes: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: MicroBitDigitalPin=pin0) -> None: + """Canta fonemas. (cantar) + +Example: ``speech.sing(' /HEHLOW WERLD')`` + +:param phonemes: (fonemas) La cadena de palabras a cantar. +:param pitch: (tono) Un número que representa el tono de la voz +:param speed: (velocidad) Un número que representa la velocidad de la voz +:param mouth: (boca) Un número que representa la boca de la voz +:param throat: (garganta) Un número que representa la garganta de la voz +:param pin: Se puede usar un argumento opcional para especificar el pin de salida, reemplazando el valor predeterminado de ``pin0``. +Si no queremos que se reproduzca ningún sonido, podemos usar ``pin=None``. Solo para el micro:bit V2. + +Override the optional pitch, speed, mouth and throat settings to change +the timbre (quality) of the voice. + +See `the online documentation `_ for detailed information.""" + ... \ No newline at end of file diff --git a/lang/es-es/typeshed/stdlib/struct.pyi b/lang/es-es/typeshed/stdlib/struct.pyi index 53b3e0b..9d0a36d 100644 --- a/lang/es-es/typeshed/stdlib/struct.pyi +++ b/lang/es-es/typeshed/stdlib/struct.pyi @@ -1,65 +1,56 @@ -"""Pack and unpack primitive data types. -""" - +"""Empaquetar y desempaquetar tipos de dato primitivos. (estruc)""" from _typeshed import ReadableBuffer, WriteableBuffer from typing import Any, Tuple, Union def calcsize(fmt: str) -> int: - """Get the number of bytes needed to store the given ``fmt``. + """Obtiene el número de bytes necesarios para almacenar el ``fmt`` dado. (calctamaño) - Example: ``struct.calcsize('hf')`` +Example: ``struct.calcsize('hf')`` - :param fmt: A format string. - :return The number of bytes needed to store such a value. - """ +:param fmt: Una cadena de formato. +:return The number of bytes needed to store such a value.""" ... def pack(fmt: str, v1: Any, *vn: Any) -> bytes: - """Pack values according to a format string. + """Empaqueta valores según una cadena de formato. (empaquetar) - Example: ``struct.pack('hf', 1, 3.1415)`` +Example: ``struct.pack('hf', 1, 3.1415)`` - :param fmt: The format string. - :param v1: The first value. - :param *vn: The remaining values. - :return A bytes object encoding the values. - """ +:param fmt: La cadena de formato. +:param v1: El primer valor. +:param *vn: Los valores restantes. +:return A bytes object encoding the values.""" ... -def pack_into( - fmt: str, buffer: WriteableBuffer, offset: int, v1: Any, *vn: Any -) -> None: - """Pack values according to a format string. +def pack_into(fmt: str, buffer: WriteableBuffer, offset: int, v1: Any, *vn: Any) -> None: + """Empaqueta valores según una cadena de formato. (empaquetar en) - Example: ``struct.pack_info('hf', buffer, 1, 3.1415)`` +Example: ``struct.pack_info('hf', buffer, 1, 3.1415)`` - :param fmt: The format string. - :param buffer: The target buffer to write into. - :param offset: The offset into the buffer. May be negative to count from the end of the buffer. - :param v1: The first value. - :param *vn: The remaining values. - """ +:param fmt: La cadena de formato. +:param buffer: (búfer) El búfer de destino en el que se va a escribir. +:param offset: (desplazamiento) El desplazamiento en el búfer. Puede ser negativo para contar desde el final del búfer. +:param v1: El primer valor. +:param *vn: Los valores restantes.""" ... def unpack(fmt: str, data: ReadableBuffer) -> Tuple[Any, ...]: - """Unpack data according to a format string. + """Desempaqueta datos según una cadena de formato. (desempaquetar) - Example: ``v1, v2 = struct.unpack('hf', buffer)`` +Example: ``v1, v2 = struct.unpack('hf', buffer)`` - :param fmt: The format string. - :param data: The data. - :return: A tuple of the unpacked values. - """ +:param fmt: La cadena de formato. +:param data: (datos) Los datos. +:return: A tuple of the unpacked values.""" ... -def unpack_from(fmt: str, buffer: ReadableBuffer, offset: int = 0) -> Tuple: - """Unpack data from a buffer according to a format string. +def unpack_from(fmt: str, buffer: ReadableBuffer, offset: int=0) -> Tuple: + """Desempaqueta datos de un búfer según una cadena de formato. (desempaquetar de) - Example: ``v1, v2 = struct.unpack_from('hf', buffer)`` +Example: ``v1, v2 = struct.unpack_from('hf', buffer)`` - :param fmt: The format string. - :param buffer: The source buffer to read from. - :param offset: The offset into the buffer. May be negative to count from the end of the buffer. - :return: A tuple of the unpacked values. - """ - ... +:param fmt: La cadena de formato. +:param buffer: (búfer) El búfer de origen del que leer. +:param offset: (desplazamiento) El desplazamiento en el búfer. Puede ser negativo para contar desde el final del búfer. +:return: A tuple of the unpacked values.""" + ... \ No newline at end of file diff --git a/lang/es-es/typeshed/stdlib/sys.pyi b/lang/es-es/typeshed/stdlib/sys.pyi index 320bac9..7f93873 100644 --- a/lang/es-es/typeshed/stdlib/sys.pyi +++ b/lang/es-es/typeshed/stdlib/sys.pyi @@ -1,43 +1,36 @@ -"""System specific functions""" - +"""Funciones específicas del sistema""" from typing import Any, Dict, List, NoReturn, TextIO, Tuple -def exit(retval: object = ...) -> NoReturn: - """Terminate current program with a given exit code. +def exit(retval: object=...) -> NoReturn: + """Termina el programa actual con un código de salida determinado. (salir) - Example: ``sys.exit(1)`` +Example: ``sys.exit(1)`` - This function raises a ``SystemExit`` exception. If an argument is given, its - value given as an argument to ``SystemExit``. +This function raises a ``SystemExit`` exception. If an argument is given, its +value given as an argument to ``SystemExit``. - :param retval: The exit code or message. - """ +:param retval: El mensaje o código de salida.""" ... def print_exception(exc: Exception) -> None: - """ - Print an exception with a traceback. - - Example: ``sys.print_exception(e)`` + """Imprime una excepción con un seguimiento. (imprimir excepción) - :param exc: The exception to print +Example: ``sys.print_exception(e)`` - This is simplified version of a function which appears in the - ``traceback`` module in CPython. - """ +:param exc: La excepción a imprimir +This is simplified version of a function which appears in the +``traceback`` module in CPython.""" argv: List[str] -"""A mutable list of arguments the current program was started with.""" - +"""Una lista mutable de argumentos con los que se inició el programa actual.""" byteorder: str -"""The byte order of the system (``"little"`` or ``"big"``).""" +"""El orden de bytes del sistema (``"little"`` o ``"big"``). (ordenbytes)""" class _implementation: name: str version: Tuple[int, int, int] - implementation: _implementation -"""Object with information about the current Python implementation. +"""Objeto con información sobre la implementación actual de Python. (implementación) For MicroPython, it has following attributes: @@ -51,13 +44,12 @@ minimal ports). CPython mandates more attributes for this object, but the actual useful bare minimum is implemented in MicroPython. """ - maxsize: int """ -Maximum value which a native integer type can hold on the current platform, -or maximum value representable by MicroPython integer type, if it's smaller -than platform max value (that is the case for MicroPython ports without -long int support). +Valor máximo que un tipo entero nativo puede contener en la plataforma actual +o valor máximo representable por el tipo entero de MicroPython, en el caso de que sea más pequeño +que el valor máximo de la plataforma (que es el caso de los puertos de MicroPython incompatibles con el +tipo entero largo). (tamañomáx) This attribute is useful for detecting "bitness" of a platform (32-bit vs 64-bit, etc.). It's recommended to not compare this attribute to some @@ -77,17 +69,14 @@ value directly, but instead count number of bits in it:: # (e.g. 31) due to peculiarities described above, so use "> 16", # "> 32", "> 64" style of comparisons. """ - modules: Dict[str, Any] -"""Dictionary of loaded modules. +"""Diccionario de módulos cargados. (módulos) On some ports, it may not include builtin modules.""" - path: List[str] -"""A mutable list of directories to search for imported modules.""" - +"""Una lista mutable de directorios para buscar módulos importados. (ruta)""" platform: str -"""The platform that MicroPython is running on. +"""La plataforma en la que se está ejecutando MicroPython. (plataforma) For OS/RTOS ports, this is usually an identifier of the OS, e.g. ``"linux"``. For baremetal ports it is an identifier of a board, e.g. ``"pyboard"`` for @@ -97,13 +86,11 @@ distinguish one board from another. If you need to check whether your program runs on MicroPython (vs other Python implementation), use ``sys.implementation`` instead. """ - version: str -"""Python language version that this implementation conforms to, as a string.""" - +"""Versión del lenguaje Python a la que se ajusta esta implementación, en forma de cadena. (versión)""" version_info: Tuple[int, int, int] -"""Python language version that this implementation conforms to, as a tuple of ints. +"""Versión del lenguaje Python a la que se ajusta esta implementación, en forma de tupla de enteros. (info de versión) Only the first three version numbers (major, minor, micro) are supported and they can be referenced only by index, not by name. -""" +""" \ No newline at end of file diff --git a/lang/es-es/typeshed/stdlib/time.pyi b/lang/es-es/typeshed/stdlib/time.pyi index 598c483..6dd4bb3 100644 --- a/lang/es-es/typeshed/stdlib/time.pyi +++ b/lang/es-es/typeshed/stdlib/time.pyi @@ -1,132 +1,112 @@ -"""Measure time and add delays to programs. -""" - +"""Mide el tiempo y añade retardos a los programas. (tiempo)""" from typing import Union def sleep(seconds: Union[int, float]) -> None: - """ - Delay a number of seconds. + """Retarda varios segundos. (dormir) - Example: ``time.sleep(1)`` +Example: ``time.sleep(1)`` - :param seconds: The number of seconds to sleep for. - Use a floating-point number to sleep for a fractional number of seconds. - """ +:param seconds: (segundos) El número de segundos de retardo. +Usa un número de coma flotante para generar un retardo durante un número fraccional de segundos.""" ... def sleep_ms(ms: int) -> None: - """ - Delay for given number of milliseconds. + """Genera un retardo para el número dado de milisegundos. (dormir ms) - Example: ``time.sleep_ms(1_000_000)`` +Example: ``time.sleep_ms(1_000_000)`` - :param ms: The number of milliseconds delay (>= 0). - """ +:param ms: El número de milisegundos de retardo (>= 0).""" ... def sleep_us(us: int) -> None: - """ - Delay for given number of microseconds. + """Genera un retardo para el número dado de microsegundos. (dormir us) - Example: ``time.sleep_us(1000)`` +Example: ``time.sleep_us(1000)`` - :param us: The number of microseconds delay (>= 0). - """ +:param us: El número de microsegundos de retardo (>= 0).""" ... def ticks_ms() -> int: - """ - Get an increasing, millisecond counter with an arbitrary reference point, - that wraps around after some value. + """Obtiene un contador en milisegundos creciente con un punto de referencia arbitrario que se reinicia después de algún valor. (tics ms) - Example: ``time.ticks_ms()`` +Example: ``time.ticks_ms()`` - :return: The counter value in milliseconds. - """ +:return: The counter value in milliseconds.""" ... def ticks_us() -> int: - """ - Get an increasing, microsecond counter with an arbitrary reference point, - that wraps around after some value. + """Obtiene un contador en microsegundos creciente con un punto de referencia arbitrario que se reinicia después de algún valor. (tics us) - Example: ``time.ticks_us()`` +Example: ``time.ticks_us()`` - :return: The counter value in microseconds. - """ +:return: The counter value in microseconds.""" ... def ticks_add(ticks: int, delta: int) -> int: - """ - Offset ticks value by a given number, which can be either positive or - negative. + """Valor de desplazamiento de tics por un número determinado, el cual puede ser positivo o +negativo. (añadir tics) - Example: ``time.ticks_add(time.ticks_ms(), 200)`` +Example: ``time.ticks_add(time.ticks_ms(), 200)`` - Given a ticks value, this function allows to calculate ticks - value delta ticks before or after it, following modular-arithmetic - definition of tick values. +Given a ticks value, this function allows to calculate ticks +value delta ticks before or after it, following modular-arithmetic +definition of tick values. - :param ticks: A ticks value - :param delta: An integer offset +:param ticks: (tics) Un valor de tics +:param delta: Un desplazamiento entero - Example:: +Example:: - # Find out what ticks value there was 100ms ago - print(ticks_add(time.ticks_ms(), -100)) + # Find out what ticks value there was 100ms ago + print(ticks_add(time.ticks_ms(), -100)) - # Calculate deadline for operation and test for it - deadline = ticks_add(time.ticks_ms(), 200) - while ticks_diff(deadline, time.ticks_ms()) > 0: - do_a_little_of_something() + # Calculate deadline for operation and test for it + deadline = ticks_add(time.ticks_ms(), 200) + while ticks_diff(deadline, time.ticks_ms()) > 0: + do_a_little_of_something() - # Find out TICKS_MAX used by this port - print(ticks_add(0, -1)) - """ + # Find out TICKS_MAX used by this port + print(ticks_add(0, -1))""" ... def ticks_diff(ticks1: int, ticks2: int) -> int: - """ - Measure ticks difference between values returned from - ``time.ticks_ms()`` or ``ticks_us()``, as a signed value - which may wrap around. - - Example: ``time.ticks_diff(scheduled_time, now)`` - - :param ticks1: The value to subtract from - :param ticks2: The value to subtract - - The argument order is the same as for subtraction operator, - ``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. - - ``ticks_diff()`` is designed to accommodate various usage - patterns, among them: - - Polling with timeout. In this case, the order of events is known, and you - will deal only with positive results of :func:`time.ticks_diff()`:: - - # Wait for GPIO pin to be asserted, but at most 500us - start = time.ticks_us() - while pin.value() == 0: - if time.ticks_diff(time.ticks_us(), start) > 500: - raise TimeoutError - - - Scheduling events. In this case, :func:`time.ticks_diff()` result may be - negative if an event is overdue:: - - # This code snippet is not optimized - now = time.ticks_ms() - scheduled_time = task.scheduled_time() - if ticks_diff(scheduled_time, now) > 0: - print("Too early, let's nap") - sleep_ms(ticks_diff(scheduled_time, now)) - task.run() - elif ticks_diff(scheduled_time, now) == 0: - print("Right at time!") - task.run() - elif ticks_diff(scheduled_time, now) < 0: - print("Oops, running late, tell task to run faster!") - task.run(run_faster=True) - """ - ... + """Mide la diferencia de tics entre los valores devueltos por ``time.ticks_ms()`` o ``ticks_us()`` como un valor con signo que se puede reiniciar. (diferencia de tics) + +Example: ``time.ticks_diff(scheduled_time, now)`` + +:param ticks1: (tics1) El valor del que restar +:param ticks2: (tics2) El valor a restar + +The argument order is the same as for subtraction operator, +``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. + +``ticks_diff()`` is designed to accommodate various usage +patterns, among them: + +Polling with timeout. In this case, the order of events is known, and you +will deal only with positive results of :func:`time.ticks_diff()`:: + + # Wait for GPIO pin to be asserted, but at most 500us + start = time.ticks_us() + while pin.value() == 0: + if time.ticks_diff(time.ticks_us(), start) > 500: + raise TimeoutError + + +Scheduling events. In this case, :func:`time.ticks_diff()` result may be +negative if an event is overdue:: + + # This code snippet is not optimized + now = time.ticks_ms() + scheduled_time = task.scheduled_time() + if ticks_diff(scheduled_time, now) > 0: + print("Too early, let's nap") + sleep_ms(ticks_diff(scheduled_time, now)) + task.run() + elif ticks_diff(scheduled_time, now) == 0: + print("Right at time!") + task.run() + elif ticks_diff(scheduled_time, now) < 0: + print("Oops, running late, tell task to run faster!") + task.run(run_faster=True)""" + ... \ No newline at end of file diff --git a/lang/fr/typeshed/stdlib/gc.pyi b/lang/fr/typeshed/stdlib/gc.pyi index 1370abf..f74d65f 100644 --- a/lang/fr/typeshed/stdlib/gc.pyi +++ b/lang/fr/typeshed/stdlib/gc.pyi @@ -1,73 +1,68 @@ -"""Control the garbage collector""" - +"""Contrôler le ramasse-miettes""" from typing import overload def enable() -> None: - """Enable automatic garbage collection.""" + """Active la collecte automatique du ramasse-miettes.""" ... def disable() -> None: - """Disable automatic garbage collection. + """Désactive la collecte automatique du ramasse-miettes. - Heap memory can still be allocated, - and garbage collection can still be initiated manually using ``gc.collect``.""" +Heap memory can still be allocated, +and garbage collection can still be initiated manually using ``gc.collect``.""" def collect() -> None: - """Run a garbage collection.""" + """Exécute une collecte avec le ramasse-miettes""" ... def mem_alloc() -> int: - """Get the number of bytes of heap RAM that are allocated. + """Obtenir le nombre d'octets alloués pour le tas en RAM - :return: The number of bytes allocated. +:return: The number of bytes allocated. - This function is MicroPython extension. - """ +This function is MicroPython extension.""" ... def mem_free() -> int: - """Get the number of bytes of available heap RAM, or -1 if this amount is not known. + """Obtenir le nombre d'octets disponibles pour le tas en RAM, ou -1 si ce nombre est inconnu. - :return: The number of bytes free. +:return: The number of bytes free. - This function is MicroPython extension. - """ +This function is MicroPython extension.""" ... @overload def threshold() -> int: - """Query the additional GC allocation threshold. + """Demander le seuil d'allocation supplémentaire GC. - :return: The GC allocation threshold. +:return: The GC allocation threshold. - This function is a MicroPython extension. CPython has a similar - function - ``set_threshold()``, but due to different GC - implementations, its signature and semantics are different. - """ +This function is a MicroPython extension. CPython has a similar +function - ``set_threshold()``, but due to different GC +implementations, its signature and semantics are different.""" ... @overload def threshold(amount: int) -> None: - """Set the additional GC allocation threshold. - - Normally, a collection is triggered only when a new allocation - cannot be satisfied, i.e. on an out-of-memory (OOM) condition. - If this function is called, in addition to OOM, a collection - will be triggered each time after ``amount`` bytes have been - allocated (in total, since the previous time such an amount of bytes - have been allocated). ``amount`` is usually specified as less than the - full heap size, with the intention to trigger a collection earlier than when the - heap becomes exhausted, and in the hope that an early collection will prevent - excessive memory fragmentation. This is a heuristic measure, the effect - of which will vary from application to application, as well as - the optimal value of the ``amount`` parameter. - - A value of -1 means a disabled allocation threshold. - - This function is a MicroPython extension. CPython has a similar - function - ``set_threshold()``, but due to different GC - implementations, its signature and semantics are different. - - :param amount: The number of bytes after which a garbage collection should be triggered. - """ - ... + """Fixer le seuil d'allocation supplémentaire GC. + +Normally, a collection is triggered only when a new allocation +cannot be satisfied, i.e. on an out-of-memory (OOM) condition. +If this function is called, in addition to OOM, a collection +will be triggered each time after ``amount`` bytes have been +allocated (in total, since the previous time such an amount of bytes +have been allocated). ``amount`` is usually specified as less than the +full heap size, with the intention to trigger a collection earlier than when the +heap becomes exhausted, and in the hope that an early collection will prevent +excessive memory fragmentation. This is a heuristic measure, the effect +of which will vary from application to application, as well as +the optimal value of the ``amount`` parameter. + +A value of -1 means a disabled allocation threshold. + +This function is a MicroPython extension. CPython has a similar +function - ``set_threshold()``, but due to different GC +implementations, its signature and semantics are different. + +:param amount: Le nombre d'octets après lequel un passage du ramasse-miettes doit être déclenché.""" + ... \ No newline at end of file diff --git a/lang/fr/typeshed/stdlib/log.pyi b/lang/fr/typeshed/stdlib/log.pyi index c9870fa..2a33dad 100644 --- a/lang/fr/typeshed/stdlib/log.pyi +++ b/lang/fr/typeshed/stdlib/log.pyi @@ -1,104 +1,89 @@ -"""Log data to your micro:bit V2.""" - +"""Journalisez des données sur votre micro:bit V2.""" from typing import Literal, Mapping, Optional, Union, overload - MILLISECONDS = 1 -"""Milliseconds timestamp format.""" - +"""Format d'horodatage en millisecondes.""" SECONDS = 10 -"""Seconds timestamp format.""" - +"""Format d'horodatage en secondes.""" MINUTES = 600 -"""Minutes timestamp format.""" - +"""Format d'horodatage en minutes.""" HOURS = 36000 -"""Hours timestamp format.""" - +"""Format d'horodatage en heures.""" DAYS = 864000 -"""Days timestamp format.""" +"""Format d'horodatage en jours.""" -def set_labels( - *labels: str, timestamp: Optional[Literal[1, 10, 36000, 864000]] = SECONDS -) -> None: - """Set up the log file header. +def set_labels(*labels: str, timestamp: Optional[Literal[1, 10, 36000, 864000]]=SECONDS) -> None: + """Définir l'en-tête du fichier journal - Example: ``log.set_labels('X', 'Y', 'Z', timestamp=log.MINUTES)`` +Example: ``log.set_labels('X', 'Y', 'Z', timestamp=log.MINUTES)`` - Ideally this function should be called a single time, before any data is - logged, to configure the data table header once. +Ideally this function should be called a single time, before any data is +logged, to configure the data table header once. - If a log file already exists when the program starts, or if this function - is called multiple times, it will check the labels already defined in the - log file. If this function call contains any new labels not already - present, it will generate a new header row with the additional columns. +If a log file already exists when the program starts, or if this function +is called multiple times, it will check the labels already defined in the +log file. If this function call contains any new labels not already +present, it will generate a new header row with the additional columns. - By default the first column contains a timestamp for each row. The time - unit can be selected via the timestamp argument. +By default the first column contains a timestamp for each row. The time +unit can be selected via the timestamp argument. - :param *labels: Any number of positional arguments, each corresponding to an entry in the log header. - :param timestamp: Select the timestamp unit that will be automatically added as the first column in every row. Timestamp values can be one of ``log.MILLISECONDS``, ``log.SECONDS``, ``log.MINUTES``, ``log.HOURS``, ``log.DAYS`` or ``None`` to disable the timestamp. The default value is ``log.SECONDS``. - """ +:param *labels: Un nombre quelconque d'arguments positionnels, chacun correspondant à une entrée dans l'en-tête du journal. +:param timestamp: (horodatage) Sélectionnez l'unité d'horodatage qui sera automatiquement ajoutée comme première colonne de chaque ligne. Les valeurs d'horodatage peuvent être l'une des suivantes ``log.MILLISECONDS``, ``log.SECONDS``, ``log.MINUTES``, ``log.HOURS``, ``log.DAYS`` ou ``None`` pour désactiver l'horodatage. La valeur par défaut est ``log.SECONDS``.""" ... @overload -def add( - data_dictionary: Optional[Mapping[str, Union[str, int, float]]], -) -> None: - """Add a data row to the log by passing a dictionary of headers and values. +def add(data_dictionary: Optional[Mapping[str, Union[str, int, float]]]) -> None: + """Ajoute une ligne de données au journal en passant un dictionnaire d'en-têtes et de valeurs. - Example: ``log.add({ 'temp': temperature() })`` +Example: ``log.add({ 'temp': temperature() })`` - Each call to this function adds a row to the log. +Each call to this function adds a row to the log. - New labels not previously specified via the set_labels function, or by a - previous call to this function, will trigger a new header entry to be added - to the log with the extra labels. +New labels not previously specified via the set_labels function, or by a +previous call to this function, will trigger a new header entry to be added +to the log with the extra labels. - Labels previously specified and not present in a call to this function will - be skipped with an empty value in the log row. +Labels previously specified and not present in a call to this function will +be skipped with an empty value in the log row. - :param data_dictionary: The data to log as a dictionary with a key for each header. - """ +:param data_dictionary: Les données à enregistrer sous forme de dictionnaire avec une clé pour chaque en-tête.""" ... @overload def add(**kwargs: Union[str, int, float]) -> None: - """Add a data row to the log using keyword arguments. + """Ajoute une ligne de données au journal en utilisant des arguments nommés. - Example: ``log.add(temp=temperature())`` +Example: ``log.add(temp=temperature())`` - Each call to this function adds a row to the log. +Each call to this function adds a row to the log. - New labels not previously specified via the set_labels function, or by a - previous call to this function, will trigger a new header entry to be added - to the log with the extra labels. +New labels not previously specified via the set_labels function, or by a +previous call to this function, will trigger a new header entry to be added +to the log with the extra labels. - Labels previously specified and not present in a call to this function will - be skipped with an empty value in the log row. - """ +Labels previously specified and not present in a call to this function will +be skipped with an empty value in the log row.""" ... def delete(full=False): - """Deletes the contents of the log, including headers. + """Supprime le contenu du journal, y compris les en-têtes. - Example: ``log.delete()`` +Example: ``log.delete()`` - To add the log headers again the ``set_labels`` function should to be called after this function. +To add the log headers again the ``set_labels`` function should to be called after this function. - There are two erase modes; “full” completely removes the data from the physical storage, - and “fast” invalidates the data without removing it. +There are two erase modes; “full” completely removes the data from the physical storage, +and “fast” invalidates the data without removing it. - :param full: ``True`` selects a “full” erase and ``False`` selects the “fast” erase method. - """ +:param full: ``True`` sélectionne un effacement "complet" et ``False`` sélectionne la méthode d'effacement "rapide".""" ... def set_mirroring(serial: bool): - """Configure mirroring of the data logging activity to the serial output. + """Configurez la mise en miroir de l'activité d'enregistrement des données sur la sortie série. - Example: ``log.set_mirroring(True)`` +Example: ``log.set_mirroring(True)`` - Serial mirroring is disabled by default. When enabled, it will print to serial each row logged into the log file. +Serial mirroring is disabled by default. When enabled, it will print to serial each row logged into the log file. - :param serial: ``True`` enables mirroring data to the serial output. - """ - ... +:param serial: ``True`` active la mise en miroir des données sur la sortie série.""" + ... \ No newline at end of file diff --git a/lang/fr/typeshed/stdlib/machine.pyi b/lang/fr/typeshed/stdlib/machine.pyi index 2e82f5b..fbb2e40 100644 --- a/lang/fr/typeshed/stdlib/machine.pyi +++ b/lang/fr/typeshed/stdlib/machine.pyi @@ -1,97 +1,84 @@ -"""Low-level utilities. -""" +"""Utilitaires bas niveau""" from typing import Any from .microbit import MicroBitDigitalPin def unique_id() -> bytes: - """Get a byte string with a unique identifier of a board. + """Récupère une chaîne d'octets représentant un identifiant unique d'une carte. - Example: ``machine.unique_id()`` +Example: ``machine.unique_id()`` - :return: An identifier that varies from one board instance to another. - """ +:return: An identifier that varies from one board instance to another.""" ... def reset() -> None: - """Reset the device in a manner similar to pushing the external RESET button. + """Réinitialise l'appareil d'une manière similaire à la pression sur le bouton RESET externe. - Example: ``machine.reset()`` - """ +Example: ``machine.reset()``""" ... def freq() -> int: - """Get the CPU frequency in hertz. + """Récupère la fréquence du CPU en hertz. - Example: ``machine.freq()`` +Example: ``machine.freq()`` - :return: The CPU frequency. - """ +:return: The CPU frequency.""" ... def disable_irq() -> Any: - """Disable interrupt requests. + """Désactiver les demandes d'interruption. - Example: ``interrupt_state = machine.disable_irq()`` +Example: ``interrupt_state = machine.disable_irq()`` - :return: the previous IRQ state which should be considered an opaque value +:return: the previous IRQ state which should be considered an opaque value - The return value should be passed to the ``enable_irq`` function to restore - interrupts to their original state. - """ +The return value should be passed to the ``enable_irq`` function to restore +interrupts to their original state.""" ... def enable_irq(state: Any) -> None: - """Re-enable interrupt requests. + """Réactiver les demandes d'interruption. - Example: ``machine.enable_irq(interrupt_state)`` +Example: ``machine.enable_irq(interrupt_state)`` - :param state: The value that was returned from the most recent call to the ``disable_irq`` function. - """ +:param state: La valeur qui a été renvoyée par l'appel le plus récent à la fonction ``disable_irq``.""" ... -def time_pulse_us( - pin: MicroBitDigitalPin, pulse_level: int, timeout_us: int = 1000000 -) -> int: - """Time a pulse on a pin. +def time_pulse_us(pin: MicroBitDigitalPin, pulse_level: int, timeout_us: int=1000000) -> int: + """Chronométrer une impulsion sur une broche. - Example: ``time_pulse_us(pin0, 1)`` +Example: ``time_pulse_us(pin0, 1)`` - If the current input value of the pin is different to ``pulse_level``, the - function first waits until the pin input becomes equal to - ``pulse_level``, then times the duration that the pin is equal to - ``pulse_level``. If the pin is already equal to ``pulse_level`` then timing - starts straight away. +If the current input value of the pin is different to ``pulse_level``, the +function first waits until the pin input becomes equal to +``pulse_level``, then times the duration that the pin is equal to +``pulse_level``. If the pin is already equal to ``pulse_level`` then timing +starts straight away. - :param pin: The pin to use - :param pulse_level: 0 to time a low pulse or 1 to time a high pulse - :param timeout_us: A microsecond timeout - :return: The duration of the pulse in microseconds, or -1 for a timeout waiting for the level to match ``pulse_level``, or -2 on timeout waiting for the pulse to end - """ +:param pin: (broche) La broche à utiliser +:param pulse_level: 0 pour chronométrer une impulsion basse ou 1 pour chronométrer une impulsion haute. +:param timeout_us: Un délai d'attente en microseconde +:return: The duration of the pulse in microseconds, or -1 for a timeout waiting for the level to match ``pulse_level``, or -2 on timeout waiting for the pulse to end""" ... class mem: - """The class for the ``mem8``, ``mem16`` and ``mem32`` memory views.""" + """La classe pour les vues mémoire ``mem8``, ``mem16`` et ``mem32``.""" def __getitem__(self, address: int) -> int: - """Access a value from memory. + """Accéder à une valeur dans la mémoire. - :param address: The memory address. - :return: The value at that address as an integer. - """ +:param address: L'adresse en mémoire. +:return: The value at that address as an integer.""" ... + def __setitem__(self, address: int, value: int) -> None: - """Set a value at the given address. + """Écrire une valeur à une adresse donnée. - :param address: The memory address. - :param value: The integer value to set. - """ +:param address: L'adresse en mémoire. +:param value: La valeur entière à écrire.""" ... - mem8: mem -"""8-bit (byte) view of memory.""" - +"""Vue de la mémoire au format 8-bit (octet).""" mem16: mem -"""16-bit view of memory.""" - +"""Vue de la mémoire au format 16-bit.""" mem32: mem -"""32-bit view of memory.""" +"""Vue de la mémoire au format 32-bit.""" \ No newline at end of file diff --git a/lang/fr/typeshed/stdlib/math.pyi b/lang/fr/typeshed/stdlib/math.pyi index f82d4de..3dc7d6c 100644 --- a/lang/fr/typeshed/stdlib/math.pyi +++ b/lang/fr/typeshed/stdlib/math.pyi @@ -1,273 +1,246 @@ -"""Mathematical functions. -""" - +"""Fonctions mathématiques.""" from typing import Tuple def acos(x: float) -> float: - """Calculate the inverse cosine. + """Calculer le cosinus inversé. - Example: ``math.acos(1)`` +Example: ``math.acos(1)`` - :param x: A number - :return: The inverse cosine of ``x`` - """ +:param x: Un nombre +:return: The inverse cosine of ``x``""" ... def asin(x: float) -> float: - """Calculate the inverse sine. + """Calculer le sinus inversé. - Example: ``math.asin(0)`` +Example: ``math.asin(0)`` - :param x: A number - :return: The inverse sine of ``x`` - """ +:param x: Un nombre +:return: The inverse sine of ``x``""" ... def atan(x: float) -> float: - """Calculate the inverse tangent. + """Calculer la tangente inverse. - Example: ``math.atan(0)`` +Example: ``math.atan(0)`` - :param x: A number - :return: The inverse tangent of ``x`` - """ +:param x: Un nombre +:return: The inverse tangent of ``x``""" ... def atan2(y: float, x: float) -> float: - """Calculate the principal value of the inverse tangent of ``y/x``. + """Calculer la valeur principale de la tangente inverse de ``y/x``. - Example: ``math.atan2(0, -1)`` +Example: ``math.atan2(0, -1)`` - :param y: A number - :param x: A number - :return: The principal value of the inverse tangent of ``y/x`` - """ +:param y: Un nombre +:param x: Un nombre +:return: The principal value of the inverse tangent of ``y/x``""" ... def ceil(x: float) -> float: - """Round a number towards positive infinity. + """Arrondir un nombre vers l'infini positif. - Example: ``math.ceil(0.1)`` +Example: ``math.ceil(0.1)`` - :param x: A number - :return: ``x`` rounded towards positive infinity. - """ +:param x: Un nombre +:return: ``x`` rounded towards positive infinity.""" ... def copysign(x: float, y: float) -> float: - """Calculate ``x`` with the sign of ``y``. + """Calculer ``x`` avec le signe de ``y``. - Example: ``math.copysign(1, -1)`` +Example: ``math.copysign(1, -1)`` - :param x: A number - :param y: The source of the sign for the return value - :return: ``x`` with the sign of ``y`` - """ +:param x: Un nombre +:param y: La source du signe pour la valeur de retour +:return: ``x`` with the sign of ``y``""" ... def cos(x: float) -> float: - """Calculate the cosine of ``x``. + """Calculer le cosinus de ``x``. - Example: ``math.cos(0)`` +Example: ``math.cos(0)`` - :param x: A number - :return: The cosine of ``x`` - """ +:param x: Un nombre +:return: The cosine of ``x``""" ... def degrees(x: float) -> float: - """Convert radians to degrees. + """Convertir les radians en degrés. (degrés) - Example: ``math.degrees(2 * math.pi)`` +Example: ``math.degrees(2 * math.pi)`` - :param x: A value in radians - :return: The value converted to degrees""" +:param x: Une valeur en radians +:return: The value converted to degrees""" ... def exp(x: float) -> float: - """Calculate the exponential of ``x``. + """Calculer l'exponentiel de ``x``. - Example: ``math.exp(1)`` +Example: ``math.exp(1)`` - :param x: A number - :return: The exponential of ``x``. - """ +:param x: Un nombre +:return: The exponential of ``x``.""" ... def fabs(x: float) -> float: - """Return the absolute value of ``x``. + """Renvoie la valeur absolue de ``x``. - Example: ``math.fabs(-0.1)`` +Example: ``math.fabs(-0.1)`` - :param x: A number - :return: The absolute value of ``x`` - """ +:param x: Un nombre +:return: The absolute value of ``x``""" ... def floor(x: float) -> int: - """Round a number towards negative infinity. + """Arrondir un nombre vers l'infini négatif. - Example: ``math.floor(0.9)`` +Example: ``math.floor(0.9)`` - :param x: A number - :return: ``x`` rounded towards negative infinity. - """ +:param x: Un nombre +:return: ``x`` rounded towards negative infinity.""" ... def fmod(x: float, y: float) -> float: - """Calculate the remainder of ``x/y``. + """Calculer le reste de ``x/y``. - Example: ``math.fmod(10, 3)`` +Example: ``math.fmod(10, 3)`` - :param x: The numerator - :param y: The denominator - """ +:param x: Le numérateur +:param y: Le dénominateur""" ... def frexp(x: float) -> Tuple[float, int]: - """Decomposes a floating-point number into its mantissa and exponent. + """Décompose un nombre à virgule flottante en sa mantisse et son exposant. - Example: ``mantissa, exponent = math.frexp(2)`` +Example: ``mantissa, exponent = math.frexp(2)`` - The returned value is the tuple ``(m, e)`` such that ``x == m * 2**e`` - exactly. If ``x == 0`` then the function returns ``(0.0, 0)``, otherwise - the relation ``0.5 <= abs(m) < 1`` holds. +The returned value is the tuple ``(m, e)`` such that ``x == m * 2**e`` +exactly. If ``x == 0`` then the function returns ``(0.0, 0)``, otherwise +the relation ``0.5 <= abs(m) < 1`` holds. - :param x: A floating-point number - :return: A tuple of length two containing its mantissa then exponent - """ +:param x: Un nombre à virgule flottante +:return: A tuple of length two containing its mantissa then exponent""" ... def isfinite(x: float) -> bool: - """Check if a value is finite. + """Vérifier si une valeur est finie. - Example: ``math.isfinite(float('inf'))`` +Example: ``math.isfinite(float('inf'))`` - :param x: A number. - :return: ``True`` if ``x`` is finite, ``False`` otherwise. - """ +:param x: Un nombre. +:return: ``True`` if ``x`` is finite, ``False`` otherwise.""" ... def isinf(x: float) -> bool: - """Check if a value is infinite. + """Vérifie si une valeur est infinie. - Example: ``math.isinf(float('-inf'))`` +Example: ``math.isinf(float('-inf'))`` - :param x: A number. - :return: ``True`` if ``x`` is infinite, ``False`` otherwise. - """ +:param x: Un nombre. +:return: ``True`` if ``x`` is infinite, ``False`` otherwise.""" ... def isnan(x: float) -> bool: - """Check if a value is not-a-number (NaN). + """Vérifie si une valeur n'est pas un nombre (NaN). - Example: ``math.isnan(float('nan'))`` +Example: ``math.isnan(float('nan'))`` - :param x: A number - :return: ``True`` if ``x`` is not-a-number (NaN), ``False`` otherwise.""" +:param x: Un nombre +:return: ``True`` if ``x`` is not-a-number (NaN), ``False`` otherwise.""" ... def ldexp(x: float, exp: int) -> float: - """Calculate ``x * (2**exp)``. + """Calculer ``x * (2**exp)``. - Example: ``math.ldexp(0.5, 2)`` +Example: ``math.ldexp(0.5, 2)`` - :param x: A number - :param exp: Integer exponent - :return: ``x * (2**exp)`` - """ +:param x: Un nombre +:param exp: Exposant entier +:return: ``x * (2**exp)``""" ... -def log(x: float, base: float = e) -> float: - """Calculate the logarithm of ``x`` to the given base (defaults to natural logorithm). +def log(x: float, base: float=e) -> float: + """Calculer le logarithme de ``x`` à la base donnée (logarithme naturel par défaut). - Example: ``math.log(math.e)`` +Example: ``math.log(math.e)`` - With one argument, return the natural logarithm of x (to base e). +With one argument, return the natural logarithm of x (to base e). - With two arguments, return the logarithm of x to the given base, calculated as ``log(x)/log(base)``. +With two arguments, return the logarithm of x to the given base, calculated as ``log(x)/log(base)``. - :param x: A number - :param base: The base to use - :return: The natural logarithm of ``x`` - """ +:param x: Un nombre +:param base: La base à utiliser +:return: The natural logarithm of ``x``""" ... def modf(x: float) -> Tuple[float, float]: - """Calculate the fractional and integral parts of ``x``. + """Calculer les parties fractionnelles et intégrales de ``x``. - Example: ``fractional, integral = math.modf(1.5)`` +Example: ``fractional, integral = math.modf(1.5)`` - :param x: A number - :return: A tuple of two floats representing the fractional then integral parts of ``x``. +:param x: Un nombre +:return: A tuple of two floats representing the fractional then integral parts of ``x``. - Both the fractional and integral values have the same sign as ``x``. - """ +Both the fractional and integral values have the same sign as ``x``.""" ... def pow(x: float, y: float) -> float: - """Returns ``x`` to the power of ``y``. + """Renvoie ``x`` à la puissance ``y``. - Example: ``math.pow(4, 0.5)`` +Example: ``math.pow(4, 0.5)`` - :param x: A number - :param y: The exponent - :return: ``x`` to the power of ``y`` - """ +:param x: Un nombre +:param y: L'exposant +:return: ``x`` to the power of ``y``""" ... def radians(x: float) -> float: - """Convert a degrees to radians. + """Convertir les degrés en radians. - Example: ``math.radians(360)`` +Example: ``math.radians(360)`` - :param x: A value in degrees - :return: The value converted to radians - """ +:param x: Une valeur en degrés +:return: The value converted to radians""" ... def sin(x: float) -> float: - """Calculate the sine of ``x``. + """Calculer le sinus de ``x``. - Example: ``math.sin(math.pi/2)`` +Example: ``math.sin(math.pi/2)`` - :param x: A number - :return: The sine of ``x`` - """ +:param x: Un nombre +:return: The sine of ``x``""" ... def sqrt(x: float) -> float: - """Calculate the square root of ``x``. + """Calculer la racine carrée de ``x``. - Example: ``math.sqrt(4)`` +Example: ``math.sqrt(4)`` - :param x: A number - :return: The square root of ``x`` - """ +:param x: Un nombre +:return: The square root of ``x``""" ... def tan(x: float) -> float: - """Calculate the tangent of ``x``. + """Calculer la tangente de ``x``. - Example: ``math.tan(0)`` +Example: ``math.tan(0)`` - :param x: A number - :return: The tangent of ``x``. - """ +:param x: Un nombre +:return: The tangent of ``x``.""" ... def trunc(x: float) -> int: - """Round a number towards 0. + """Arrondir un nombre vers 0. - Example: ``math.trunc(-0.9)`` +Example: ``math.trunc(-0.9)`` - :param x: A number - :return: ``x`` rounded towards zero. - """ +:param x: Un nombre +:return: ``x`` rounded towards zero.""" ... - e: float -"""Base of the natural logarithm""" - +"""Base du logarithme naturel""" pi: float -"""The ratio of a circle's circumference to its diameter""" +"""Le ratio entre la circonférence d'un cercle et son diamètre""" \ No newline at end of file diff --git a/lang/fr/typeshed/stdlib/microbit/__init__.pyi b/lang/fr/typeshed/stdlib/microbit/__init__.pyi index f12158f..90bf6e6 100644 --- a/lang/fr/typeshed/stdlib/microbit/__init__.pyi +++ b/lang/fr/typeshed/stdlib/microbit/__init__.pyi @@ -1,11 +1,6 @@ -"""Pins, images, sounds, temperature and volume. -""" - +"""Broches, images, sons, température et volume""" from typing import Any, Callable, List, Optional, Tuple, Union, overload - from _typeshed import ReadableBuffer - -# V2 only from . import accelerometer as accelerometer from . import audio as audio from . import compass as compass @@ -16,831 +11,700 @@ from . import speaker as speaker from . import spi as spi from . import uart as uart -def run_every( - callback: Optional[Callable[[], None]] = None, - days: int = 0, - h: int = 0, - min: int = 0, - s: int = 0, - ms: int = 0, -) -> Callable[[Callable[[], None]], Callable[[], None]]: - """Schedule to run a function at the interval specified by the time arguments **V2 only**. +def run_every(callback: Optional[Callable[[], None]]=None, days: int=0, h: int=0, min: int=0, s: int=0, ms: int=0) -> Callable[[Callable[[], None]], Callable[[], None]]: + """Planifie l'exécution d'une fonction à l'intervalle spécifié par les arguments temporels **V2 uniquement**. - Example: ``run_every(my_logging, min=5)`` +Example: ``run_every(my_logging, min=5)`` - ``run_every`` can be used in two ways: +``run_every`` can be used in two ways: - As a Decorator - placed on top of the function to schedule. For example:: +As a Decorator - placed on top of the function to schedule. For example:: - @run_every(h=1, min=20, s=30, ms=50) - def my_function(): - # Do something here + @run_every(h=1, min=20, s=30, ms=50) + def my_function(): + # Do something here - As a Function - passing the callback as a positional argument. For example:: +As a Function - passing the callback as a positional argument. For example:: - def my_function(): - # Do something here - run_every(my_function, s=30) + def my_function(): + # Do something here + run_every(my_function, s=30) - Each argument corresponds to a different time unit and they are additive. - So ``run_every(min=1, s=30)`` schedules the callback every minute and a half. +Each argument corresponds to a different time unit and they are additive. +So ``run_every(min=1, s=30)`` schedules the callback every minute and a half. - When an exception is thrown inside the callback function it deschedules the - function. To avoid this you can catch exceptions with ``try/except``. +When an exception is thrown inside the callback function it deschedules the +function. To avoid this you can catch exceptions with ``try/except``. - :param callback: Function to call at the provided interval. Omit when using as a decorator. - :param days: Sets the day mark for the scheduling. - :param h: Sets the hour mark for the scheduling. - :param min: Sets the minute mark for the scheduling. - :param s: Sets the second mark for the scheduling. - :param ms: Sets the millisecond mark for the scheduling. - """ +:param callback: Fonction à appeler à l'intervalle fourni. À omettre en cas d'utilisation comme décorateur. +:param days: Définit la marque du jour pour la programmation. +:param h: Définit la marque d'heure pour la programmation. +:param min: Définit la marque de minute pour la programmation. +:param s: Définit la marque de seconde pour la programmation. +:param ms: Définit la marque de milliseconde pour la programmation.""" def panic(n: int) -> None: - """Enter a panic mode. + """Passer en mode panique. - Example: ``panic(127)`` +Example: ``panic(127)`` - :param n: An arbitrary integer <= 255 to indicate a status. +:param n: Un nombre entier arbitraire <= 255 pour indiquer un état. - Requires restart. - """ +Requires restart.""" def reset() -> None: - """Restart the board.""" - + """Redémarrer la carte.""" @overload def scale(value: float, from_: Tuple[float, float], to: Tuple[int, int]) -> int: - """Converts a value from a range to an integer range. + """Convertit une valeur dans l'intervalle donné vers son équivalent dans un autre intervalle d'entiers. - Example: ``volume = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255))`` +Example: ``volume = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255))`` - For example, to convert an accelerometer X value to a speaker volume. +For example, to convert an accelerometer X value to a speaker volume. - If one of the numbers in the ``to`` parameter is a floating point - (i.e a decimal number like ``10.0``), this function will return a - floating point number. +If one of the numbers in the ``to`` parameter is a floating point +(i.e a decimal number like ``10.0``), this function will return a +floating point number. - temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0)) + temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0)) - :param value: A number to convert. - :param from_: A tuple to define the range to convert from. - :param to: A tuple to define the range to convert to. - :return: The ``value`` converted to the ``to`` range. - """ +:param value: Un nombre à convertir. +:param from_: Un tuple qui définit l'intervalle de départ. +:param to: Un tuple qui définit l'intervalle d'arrivée. +:return: The ``value`` converted to the ``to`` range.""" @overload def scale(value: float, from_: Tuple[float, float], to: Tuple[float, float]) -> float: - """Converts a value from a range to a floating point range. + """Convertit une valeur dans l'intervalle donné vers son équivalent dans un autre intervalle de nombres à virgule flottante. - Example: ``temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0))`` +Example: ``temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0))`` - For example, to convert temperature from a Celsius scale to Fahrenheit. +For example, to convert temperature from a Celsius scale to Fahrenheit. - If one of the numbers in the ``to`` parameter is a floating point - (i.e a decimal number like ``10.0``), this function will return a - floating point number. - If they are both integers (i.e ``10``), it will return an integer:: +If one of the numbers in the ``to`` parameter is a floating point +(i.e a decimal number like ``10.0``), this function will return a +floating point number. +If they are both integers (i.e ``10``), it will return an integer:: - returns_int = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255)) + returns_int = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255)) - :param value: A number to convert. - :param from_: A tuple to define the range to convert from. - :param to: A tuple to define the range to convert to. - :return: The ``value`` converted to the ``to`` range. - """ +:param value: Un nombre à convertir. +:param from_: Un tuple qui définit l'intervalle de départ. +:param to: Un tuple qui définit l'intervalle d'arrivée. +:return: The ``value`` converted to the ``to`` range.""" def sleep(n: float) -> None: - """Wait for ``n`` milliseconds. + """Attendre ``n`` millisecondes. - Example: ``sleep(1000)`` +Example: ``sleep(1000)`` - :param n: The number of milliseconds to wait +:param n: Le nombre de millisecondes à attendre - One second is 1000 milliseconds, so:: +One second is 1000 milliseconds, so:: - microbit.sleep(1000) + microbit.sleep(1000) - will pause the execution for one second. - """ +will pause the execution for one second.""" def running_time() -> int: - """Get the running time of the board. + """Obtenir le temps de fonctionnement de la carte. - :return: The number of milliseconds since the board was switched on or restarted. - """ +:return: The number of milliseconds since the board was switched on or restarted.""" def temperature() -> int: - """Get the temperature of the micro:bit in degrees Celsius.""" + """Obtenir la température du micro:bit en degrés Celsius.""" def set_volume(v: int) -> None: - """Sets the volume. + """Définit le volume. - Example: ``set_volume(127)`` +Example: ``set_volume(127)`` - :param v: a value between 0 (low) and 255 (high). +:param v: Une valeur entre 0 (bas) et 255 (haut). - Out of range values will be clamped to 0 or 255. +Out of range values will be clamped to 0 or 255. - **V2** only. - """ +**V2** only.""" ... class Button: - """The class for the buttons ``button_a`` and ``button_b``.""" + """La classe pour les boutons ``button_a`` et ``button_b``.""" def is_pressed(self) -> bool: - """Check if the button is pressed. + """Vérifier si le bouton est appuyé. - :return: ``True`` if the specified button ``button`` is pressed, and ``False`` otherwise. - """ +:return: ``True`` if the specified button ``button`` is pressed, and ``False`` otherwise.""" ... + def was_pressed(self) -> bool: - """Check if the button was pressed since the device started or the last time this method was called. + """Vérifie si le bouton a été pressé depuis que l'appareil a été démarré ou depuis la dernière fois où cette méthode a été appelée. - Calling this method will clear the press state so - that the button must be pressed again before this method will return - ``True`` again. +Calling this method will clear the press state so +that the button must be pressed again before this method will return +``True`` again. - :return: ``True`` if the specified button ``button`` was pressed, and ``False`` otherwise - """ +:return: ``True`` if the specified button ``button`` was pressed, and ``False`` otherwise""" ... + def get_presses(self) -> int: - """Get the running total of button presses, and resets this total - to zero before returning. + """Obtenir le nombre total d'occurrences où le bouton a été appuyé, et réinitialise ce total avant de retourner. - :return: The number of presses since the device started or the last time this method was called - """ +:return: The number of presses since the device started or the last time this method was called""" ... - button_a: Button -"""The left button ``Button`` object.""" - +"""L'objet bouton ``Button`` gauche.""" button_b: Button -"""The right button ``Button`` object.""" +"""L'objet bouton ``Button`` droit.""" class MicroBitDigitalPin: - """A digital pin. - - Some pins support analog and touch features using the ``MicroBitAnalogDigitalPin`` and ``MicroBitTouchPin`` subclasses. - """ + """Une broche numérique. +Some pins support analog and touch features using the ``MicroBitAnalogDigitalPin`` and ``MicroBitTouchPin`` subclasses.""" NO_PULL: int PULL_UP: int PULL_DOWN: int + def read_digital(self) -> int: - """Get the digital value of the pin. + """Récupère la valeur numérique de la broche - Example: ``value = pin0.read_digital()`` +Example: ``value = pin0.read_digital()`` - :return: 1 if the pin is high, and 0 if it's low. - """ +:return: 1 if the pin is high, and 0 if it's low.""" ... + def write_digital(self, value: int) -> None: - """Set the digital value of the pin. + """Définit la valeur numérique de la broche - Example: ``pin0.write_digital(1)`` +Example: ``pin0.write_digital(1)`` - :param value: 1 to set the pin high or 0 to set the pin low""" +:param value: 1 pour définir la broche à un niveau haut ou 0 pour définir la broche à un niveau bas""" ... + def set_pull(self, value: int) -> None: - """Set the pull state to one of three possible values: ``PULL_UP``, ``PULL_DOWN`` or ``NO_PULL``. + """Définissez l'état de tirage sur l'une des trois valeurs possibles\xa0: ``PULL_UP``, ``PULL_DOWN`` ou ``NO_PULL``. - Example: ``pin0.set_pull(pin0.PULL_UP)`` +Example: ``pin0.set_pull(pin0.PULL_UP)`` - :param value: The pull state from the relevant pin, e.g. ``pin0.PULL_UP``. - """ +:param value: L'état de tirage sur la broche correspondante, par exemple ``pin0.PULL_UP``.""" ... + def get_pull(self) -> int: - """Get the pull state on a pin. + """Obtenir l'état de tirage sur une broche. - Example: ``pin0.get_pull()`` +Example: ``pin0.get_pull()`` - :return: ``NO_PULL``, ``PULL_DOWN``, or ``PULL_UP`` +:return: ``NO_PULL``, ``PULL_DOWN``, or ``PULL_UP`` - These are set using the ``set_pull()`` method or automatically configured - when a pin mode requires it. - """ +These are set using the ``set_pull()`` method or automatically configured +when a pin mode requires it.""" ... + def get_mode(self) -> str: - """Returns the pin mode. + """Renvoie le mode de la broche - Example: ``pin0.get_mode()`` +Example: ``pin0.get_mode()`` - When a pin is used for a specific function, like - writing a digital value, or reading an analog value, the pin mode - changes. +When a pin is used for a specific function, like +writing a digital value, or reading an analog value, the pin mode +changes. - :return: ``"unused"``, ``"analog"``, ``"read_digital"``, ``"write_digital"``, ``"display"``, ``"button"``, ``"music"``, ``"audio"``, ``"touch"``, ``"i2c"``, or ``"spi"`` - """ +:return: ``"unused"``, ``"analog"``, ``"read_digital"``, ``"write_digital"``, ``"display"``, ``"button"``, ``"music"``, ``"audio"``, ``"touch"``, ``"i2c"``, or ``"spi"``""" ... + def write_analog(self, value: int) -> None: - """Output a PWM signal on the pin, with the duty cycle proportional to ``value``. + """Sortie d'un signal PWM sur la broche, avec un rapport cyclique proportionnel à ``value``. + +Example: ``pin0.write_analog(254)`` - Example: ``pin0.write_analog(254)`` +:param value: Un entier ou un nombre à virgule flottante entre 0 (rapport cyclique à 0%) et 1023 (rapport cyclique à 100%).""" - :param value: 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. + """Définit la période de sortie du signal PWM à ``period`` en millisecondes. - Example: ``pin0.set_analog_period(10)`` +Example: ``pin0.set_analog_period(10)`` + +:param period: La période en millisecondes avec une valeur minimale valide de 1 ms.""" - :param period: The period in milliseconds with a minimum valid value of 1ms. - """ def set_analog_period_microseconds(self, period: int) -> None: - """Set the period of the PWM signal being output to ``period`` in microseconds. + """Définit la période de sortie du signal PWM à ``period`` en millisecondes. - Example: ``pin0.set_analog_period_microseconds(512)`` +Example: ``pin0.set_analog_period_microseconds(512)`` - :param period: The period in microseconds with a minimum valid value of 256µs. - """ +:param period: La période en microsecondes avec une valeur minimale valide de 256µs.""" class MicroBitAnalogDigitalPin(MicroBitDigitalPin): - """A pin with analog and digital features.""" + """Une broche avec des fonctions analogiques et numériques.""" def read_analog(self) -> int: - """Read the voltage applied to the pin. + """Lit la tension appliquée à la broche. - Example: ``pin0.read_analog()`` +Example: ``pin0.read_analog()`` - :return: An integer between 0 (meaning 0V) and 1023 (meaning 3.3V). - """ +:return: An integer between 0 (meaning 0V) and 1023 (meaning 3.3V).""" class MicroBitTouchPin(MicroBitAnalogDigitalPin): - """A pin with analog, digital and touch features.""" - + """Une broche avec des fonctions analogiques, numériques et tactiles.""" CAPACITIVE: int RESISTIVE: int + def is_touched(self) -> bool: - """Check if the pin is being touched. + """Vérifie si la broche est touchée. - Example: ``pin0.is_touched()`` +Example: ``pin0.is_touched()`` - The default touch mode for the pins on the edge connector is ``resistive``. - The default for the logo pin **V2** is ``capacitive``. +The default touch mode for the pins on the edge connector is ``resistive``. +The default for the logo pin **V2** is ``capacitive``. - **Resistive touch** - This test is done by measuring how much resistance there is between the - pin and ground. A low resistance gives a reading of ``True``. To get - a reliable reading using a finger you may need to touch the ground pin - with another part of your body, for example your other hand. +**Resistive touch** +This test is done by measuring how much resistance there is between the +pin and ground. A low resistance gives a reading of ``True``. To get +a reliable reading using a finger you may need to touch the ground pin +with another part of your body, for example your other hand. - **Capacitive touch** - This test is done by interacting with the electric field of a capacitor - using a finger as a conductor. `Capacitive touch - `_ - does not require you to make a ground connection as part of a circuit. +**Capacitive touch** +This test is done by interacting with the electric field of a capacitor +using a finger as a conductor. `Capacitive touch +`_ +does not require you to make a ground connection as part of a circuit. - :return: ``True`` if the pin is being touched with a finger, otherwise return ``False``. - """ +:return: ``True`` if the pin is being touched with a finger, otherwise return ``False``.""" ... + def set_touch_mode(self, value: int) -> None: - """Set the touch mode for the pin. + """Définit le mode tactile pour la broche. - Example: ``pin0.set_touch_mode(pin0.CAPACITIVE)`` +Example: ``pin0.set_touch_mode(pin0.CAPACITIVE)`` - The default touch mode for the pins on the edge connector is - ``resistive``. The default for the logo pin **V2** is ``capacitive``. +The default touch mode for the pins on the edge connector is +``resistive``. The default for the logo pin **V2** is ``capacitive``. - :param value: ``CAPACITIVE`` or ``RESISTIVE`` from the relevant pin. - """ +:param value: ``CAPACITIVE`` ou ``RESISTIVE`` pour la broche correspondante.""" ... - pin0: MicroBitTouchPin -"""Pin with digital, analog and touch features.""" - +"""Broche avec des fonctionnalités numériques, analogiques, et tactiles.""" pin1: MicroBitTouchPin -"""Pin with digital, analog and touch features.""" - +"""Broche avec des fonctionnalités numériques, analogiques, et tactiles.""" pin2: MicroBitTouchPin -"""Pin with digital, analog and touch features.""" - +"""Broche avec des fonctionnalités numériques, analogiques, et tactiles.""" pin3: MicroBitAnalogDigitalPin -"""Pin with digital and analog features.""" - +"""Broche avec des fonctionnalités numériques et analogiques.""" pin4: MicroBitAnalogDigitalPin -"""Pin with digital and analog features.""" - +"""Broche avec des fonctionnalités numériques et analogiques.""" pin5: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Broche avec des fonctionnalités numériques""" pin6: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Broche avec des fonctionnalités numériques""" pin7: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Broche avec des fonctionnalités numériques""" pin8: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Broche avec des fonctionnalités numériques""" pin9: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Broche avec des fonctionnalités numériques""" pin10: MicroBitAnalogDigitalPin -"""Pin with digital and analog features.""" - +"""Broche avec des fonctionnalités numériques et analogiques.""" pin11: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Broche avec des fonctionnalités numériques""" pin12: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Broche avec des fonctionnalités numériques""" pin13: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Broche avec des fonctionnalités numériques""" pin14: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Broche avec des fonctionnalités numériques""" pin15: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Broche avec des fonctionnalités numériques""" pin16: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Broche avec des fonctionnalités numériques""" pin19: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Broche avec des fonctionnalités numériques""" pin20: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Broche avec des fonctionnalités numériques""" pin_logo: MicroBitTouchPin -"""A touch sensitive logo pin on the front of the micro:bit, which by default is set to capacitive touch mode.""" - +"""Une broche logo sensible au toucher sur l'avant du micro:bit, qui est définie par défaut en mode tactile capacitif.""" pin_speaker: MicroBitAnalogDigitalPin -"""A pin to address the micro:bit speaker. +"""Une broche pour adresser le haut-parleur micro:bit. This API is intended only for use in Pulse-Width Modulation pin operations e.g. pin_speaker.write_analog(128). """ class Image: - """An image to show on the micro:bit LED display. + """Une image à afficher sur l'écran LED du micro:bit. - Given an image object it's possible to display it via the ``display`` API:: - - display.show(Image.HAPPY) - """ +Given an image object it's possible to display it via the ``display`` API:: + display.show(Image.HAPPY)""" HEART: Image - """Heart image.""" - + """Image d'un cœur.""" HEART_SMALL: Image - """Small heart image.""" - + """Petite image d'un cœur""" HAPPY: Image - """Happy face image.""" - + """Image de visage heureux.""" SMILE: Image - """Smiling mouth image.""" - + """Image de visage souriant.""" SAD: Image - """Sad face image.""" - + """Image de visage triste.""" CONFUSED: Image - """Confused face image.""" - + """Image d'un visage perplexe.""" ANGRY: Image - """Angry face image.""" - + """Image de visage en colère.""" ASLEEP: Image - """Sleeping face image.""" - + """Image de visage endormi""" SURPRISED: Image - """Surprised face image.""" - + """Image de visage surpris.""" SILLY: Image - """Silly face image.""" - + """Image de visage absurde.""" FABULOUS: Image - """Sunglasses face image.""" - + """Image de visage avec lunettes de soleil.""" MEH: Image - """Unimpressed face image.""" - + """Image de visage pas impressionné""" YES: Image - """Tick image.""" - + """Image d'une coche.""" NO: Image - """Cross image.""" - + """Image d'une croix.""" CLOCK12: Image - """Image with line pointing to 12 o'clock.""" - + """Image avec une ligne indiquant vers 12 heures.""" CLOCK11: Image - """Image with line pointing to 11 o'clock.""" - + """Image avec une ligne indiquant vers 11 heures.""" CLOCK10: Image - """Image with line pointing to 10 o'clock.""" - + """Image avec une ligne indiquant vers 10 heures.""" CLOCK9: Image - """Image with line pointing to 9 o'clock.""" - + """Image avec une ligne indiquant vers 9 heures.""" CLOCK8: Image - """Image with line pointing to 8 o'clock.""" - + """Image avec une ligne indiquant vers 8 heures.""" CLOCK7: Image - """Image with line pointing to 7 o'clock.""" - + """Image avec une ligne indiquant vers 7 heures.""" CLOCK6: Image - """Image with line pointing to 6 o'clock.""" - + """Image avec une ligne indiquant vers 6 heures.""" CLOCK5: Image - """Image with line pointing to 5 o'clock.""" - + """Image avec une ligne indiquant vers 5 heures.""" CLOCK4: Image - """Image with line pointing to 4 o'clock.""" - + """Image avec une ligne indiquant vers 4 heures.""" CLOCK3: Image - """Image with line pointing to 3 o'clock.""" - + """Image avec une ligne indiquant vers 3 heures.""" CLOCK2: Image - """Image with line pointing to 2 o'clock.""" - + """Image avec une ligne indiquant vers 2 heures.""" CLOCK1: Image - """Image with line pointing to 1 o'clock.""" - + """Image avec une ligne indiquant vers 1 heure.""" ARROW_N: Image - """Image of arrow pointing north.""" - + """Image de flèche pointant vers le nord.""" ARROW_NE: Image - """Image of arrow pointing north east.""" - + """Image de flèche pointant vers le nord est.""" ARROW_E: Image - """Image of arrow pointing east.""" - + """Image de flèche pointant vers l'est.""" ARROW_SE: Image - """Image of arrow pointing south east.""" - + """Image de flèche pointant vers le sud-est.""" ARROW_S: Image - """Image of arrow pointing south.""" - + """Image de flèche pointant vers le sud.""" ARROW_SW: Image - """Image of arrow pointing south west.""" - + """Image de flèche pointant vers le sud-ouest.""" ARROW_W: Image - """Image of arrow pointing west.""" - + """Image de flèche pointant vers l'ouest.""" ARROW_NW: Image - """Image of arrow pointing north west.""" - + """Image de flèche pointant vers le nord ouest.""" TRIANGLE: Image - """Image of a triangle pointing up.""" - + """Image d'un triangle pointant vers le haut.""" TRIANGLE_LEFT: Image - """Image of a triangle in the left corner.""" - + """Image d'un triangle dans le coin gauche.""" CHESSBOARD: Image - """Alternate LEDs lit in a chessboard pattern.""" - + """Éclairage alternatif des LEDs dans un motif d'échiquier.""" DIAMOND: Image - """Diamond image.""" - + """Image de diamant.""" DIAMOND_SMALL: Image - """Small diamond image.""" - + """Petite image de diamant.""" SQUARE: Image - """Square image.""" - + """Image de carré.""" SQUARE_SMALL: Image - """Small square image.""" - + """Petite image de carré.""" RABBIT: Image - """Rabbit image.""" - + """Image de lapin.""" COW: Image - """Cow image.""" - + """Image de vache.""" MUSIC_CROTCHET: Image - """Crotchet note image.""" - + """Image d'une note.""" MUSIC_QUAVER: Image - """Quaver note image.""" - + """Image d'une croche.""" MUSIC_QUAVERS: Image - """Pair of quavers note image.""" - + """Image d'une paire de croche.""" PITCHFORK: Image - """Pitchfork image.""" - + """Image d'une fourche.""" XMAS: Image - """Christmas tree image.""" - + """Image d'un arbre de Noël.""" PACMAN: Image - """Pac-Man arcade character image.""" - + """Image du personnage d'arcade Pac-Man.""" TARGET: Image - """Target image.""" - + """Image d'une cible.""" TSHIRT: Image - """T-shirt image.""" - + """Image de t-shirt.""" ROLLERSKATE: Image - """Rollerskate image.""" - + """Image de patin à roulette.""" DUCK: Image - """Duck image.""" - + """Image de canard.""" HOUSE: Image - """House image.""" - + """Image d'une maison.""" TORTOISE: Image - """Tortoise image.""" - + """Image d'une tortue.""" BUTTERFLY: Image - """Butterfly image.""" - + """Image d'un papillon.""" STICKFIGURE: Image - """Stick figure image.""" - + """Image d'un personnage.""" GHOST: Image - """Ghost image.""" - + """Image de fantôme.""" SWORD: Image - """Sword image.""" - + """Image d'une épée.""" GIRAFFE: Image - """Giraffe image.""" - + """Image d'une girafe.""" SKULL: Image - """Skull image.""" - + """Image d'un crâne.""" UMBRELLA: Image - """Umbrella image.""" - + """Image d'un parapluie.""" SNAKE: Image - """Snake image.""" - + """Image de serpent.""" SCISSORS: Image - """Scissors image.""" - + """Image de ciseaux.""" ALL_CLOCKS: List[Image] - """A list containing all the CLOCK_ images in sequence.""" - + """Une liste contenant toutes les images CLOCK_ en séquence.""" ALL_ARROWS: List[Image] - """A list containing all the ARROW_ images in sequence.""" + """Une liste contenant toutes les images ARROW_ en séquence.""" + @overload def __init__(self, string: str) -> None: - """Create an image from a string describing which LEDs are lit. + """Créer une image à partir d'une chaîne de caractères décrivant quelles LED sont allumées. - ``string`` has to consist of digits 0-9 arranged into lines, - describing the image, for example:: +``string`` has to consist of digits 0-9 arranged into lines, +describing the image, for example:: - image = Image("90009:" - "09090:" - "00900:" - "09090:" - "90009") + 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 newlines (\\n) insead of the colons. +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 newlines (\\n) insead of the colons. - :param string: The string describing the image. - """ +:param string: La chaîne de caractères décrivant l'image.""" ... + @overload - def __init__( - self, width: int = 5, height: int = 5, buffer: ReadableBuffer = None - ) -> None: - """Create an empty image with ``width`` columns and ``height`` rows. + def __init__(self, width: int=5, height: int=5, buffer: ReadableBuffer=None) -> None: + """Créer une image vide avec ``width`` colonnes et ``height`` lignes. - :param width: Optional width of the image - :param height: Optional height of the image - :param buffer: Optional array or bytes of ``width``×``height`` integers in range 0-9 to initialize the image +:param width: Largeur optionnelle de l'image +:param height: Hauteur optionnelle de l'image +:param buffer: Tableau optionnel ou octets de ``width``×``height`` entiers dans la plage 0-9 pour initialiser l'image - Examples:: +Examples:: - Image(2, 2, b'\x08\x08\x08\x08') - Image(2, 2, bytearray([9,9,9,9])) + Image(2, 2, b'\x08\x08\x08\x08') + Image(2, 2, bytearray([9,9,9,9])) - These create 2 x 2 pixel images at full brightness. - """ +These create 2 x 2 pixel images at full brightness.""" ... + def width(self) -> int: - """Get the number of columns. + """Récupère le nombre de colonnes. - :return: The number of columns in the image - """ +:return: The number of columns in the image""" ... + def height(self) -> int: - """Get the number of rows. + """Récupère le nombre de lignes. - :return: The number of rows in the image - """ +:return: The number of rows in the image""" ... + def set_pixel(self, x: int, y: int, value: int) -> None: - """Set the brightness of a pixel. + """Définit la luminosité d'un pixel. - Example: ``my_image.set_pixel(0, 0, 9)`` +Example: ``my_image.set_pixel(0, 0, 9)`` - :param x: The column number - :param y: The row number - :param value: The brightness as an integer between 0 (dark) and 9 (bright) +:param x: Le numéro de colonne +:param y: Le numéro de ligne +:param value: La luminosité sous la forme d'un entier compris entre 0 (sombre) et 9 (lumineux) - This method will raise an exception when called on any of the built-in - read-only images, like ``Image.HEART``. - """ +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: - """Get the brightness of a pixel. + """Récupère la luminosité d'un pixel. - Example: ``my_image.get_pixel(0, 0)`` +Example: ``my_image.get_pixel(0, 0)`` - :param x: The column number - :param y: The row number - :return: The brightness as an integer between 0 and 9. - """ +:param x: Le numéro de colonne +:param y: Le numéro de ligne +:return: The brightness as an integer between 0 and 9.""" ... + def shift_left(self, n: int) -> Image: - """Create a new image by shifting the picture left. + """Créer une nouvelle image en déplaçant l'image à gauche. - Example: ``Image.HEART_SMALL.shift_left(1)`` +Example: ``Image.HEART_SMALL.shift_left(1)`` - :param n: The number of columns to shift by - :return: The shifted image - """ +:param n: Le nombre de colonnes par lequel déplacer +:return: The shifted image""" ... + def shift_right(self, n: int) -> Image: - """Create a new image by shifting the picture right. + """Créer une nouvelle image en déplaçant l'image à droite. - Example: ``Image.HEART_SMALL.shift_right(1)`` +Example: ``Image.HEART_SMALL.shift_right(1)`` - :param n: The number of columns to shift by - :return: The shifted image - """ +:param n: Le nombre de colonnes par lequel déplacer +:return: The shifted image""" ... + def shift_up(self, n: int) -> Image: - """Create a new image by shifting the picture up. + """Créer une nouvelle image en déplaçant l'image vers le haut. - Example: ``Image.HEART_SMALL.shift_up(1)`` +Example: ``Image.HEART_SMALL.shift_up(1)`` - :param n: The number of rows to shift by - :return: The shifted image - """ +:param n: Le nombre de lignes par lequel déplacer +:return: The shifted image""" ... + def shift_down(self, n: int) -> Image: - """Create a new image by shifting the picture down. + """Créer une nouvelle image en déplaçant l'image vers le bas. - Example: ``Image.HEART_SMALL.shift_down(1)`` +Example: ``Image.HEART_SMALL.shift_down(1)`` - :param n: The number of rows to shift by - :return: The shifted image - """ +:param n: Le nombre de lignes par lequel déplacer +:return: The shifted image""" ... + def crop(self, x: int, y: int, w: int, h: int) -> Image: - """Create a new image by cropping the picture. + """Créer une nouvelle image en recadrant l'image. - Example: ``Image.HEART.crop(1, 1, 3, 3)`` +Example: ``Image.HEART.crop(1, 1, 3, 3)`` - :param x: The crop offset column - :param y: The crop offset row - :param w: The crop width - :param h: The crop height - :return: The new image - """ +:param x: Le nombre de colonnes duquel décaler le recadrage +:param y: Le nombre de lignes duquel décaler le recadrage +:param w: La largeur du recadrage +:param h: La hauteur du recadrage +:return: The new image""" ... + def copy(self) -> Image: - """Create an exact copy of the image. + """Créer une copie exacte de l'image. - Example: ``Image.HEART.copy()`` +Example: ``Image.HEART.copy()`` - :return: The new image - """ +:return: The new image""" ... + def invert(self) -> Image: - """Create a new image by inverting the brightness of the pixels in the - source image. + """Créer une nouvelle image en inversant la luminosité des pixels de l'image source. - Example: ``Image.SMALL_HEART.invert()`` +Example: ``Image.SMALL_HEART.invert()`` - :return: The new image. - """ +:return: The new image.""" ... + def fill(self, value: int) -> None: - """Set the brightness of all the pixels in the image. + """Définit la luminosité de tous les pixels de l'image. - Example: ``my_image.fill(5)`` +Example: ``my_image.fill(5)`` - :param value: The new brightness as a number between 0 (dark) and 9 (bright). +:param value: La nouvelle luminosité sous la forme d'un nombre compris entre 0 (sombre) et 9 (lumineux). - This method will raise an exception when called on any of the built-in - read-only images, like ``Image.HEART``. - """ +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 an area from another image into this image. - - Example: ``my_image.blit(Image.HEART, 1, 1, 3, 3, 1, 1)`` - - :param src: The source image - :param x: The starting column offset in the source image - :param y: The starting row offset in the source image - :param w: The number of columns to copy - :param h: The number of rows to copy - :param xdest: The column offset to modify in this image - :param ydest: The row offset to modify in this image - - Pixels outside the source image are treated as having a brightness 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 blit(self, src: Image, x: int, y: int, w: int, h: int, xdest: int=0, ydest: int=0) -> None: + """Copier la zone d'une autre image vers cette image. + +Example: ``my_image.blit(Image.HEART, 1, 1, 3, 3, 1, 1)`` + +:param src: L'image source +:param x: Le décalage de la colonne de départ dans l'image source +:param y: Décalage de la ligne de départ dans l'image source +:param w: Le nombre de colonnes à copier +:param h: Le nombre de lignes à copier +:param xdest: Le décalage de la colonne à modifier dans cette image +:param ydest: Le décalage de la ligne à modifier dans cette image + +Pixels outside the source image are treated as having a brightness 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.""" + """Récupère une représentation de l'image sous forme de texte compact.""" ... + def __str__(self) -> str: - """Get a readable string representation of the image.""" + """Récupère une chaîne de caractères lisible de l'image.""" ... + def __add__(self, other: Image) -> Image: - """Create a new image by adding the brightness values from the two - images for each pixel. + """Crée une nouvelle image en additionnant les valeurs de luminosité des deux images +pour chaque pixel. - Example: ``Image.HEART + Image.HAPPY`` +Example: ``Image.HEART + Image.HAPPY`` - :param other: The image to add. - """ +:param other: L'image à ajouter.""" ... + def __sub__(self, other: Image) -> Image: - """Create a new image by subtracting the brightness values of the - other image from this image. + """Crée une nouvelle image en soustrayant de cette image les valeurs de luminosité de +l'autre image. - Example: ``Image.HEART - Image.HEART_SMALL`` +Example: ``Image.HEART - Image.HEART_SMALL`` - :param other: The image to subtract. - """ +:param other: L'image à soustraire.""" ... + def __mul__(self, n: float) -> Image: - """Create a new image by multiplying the brightness of each pixel by - ``n``. + """Crée une nouvelle image en multipliant la luminosité de chaque pixel par +``n``. - Example: ``Image.HEART * 0.5`` +Example: ``Image.HEART * 0.5`` - :param n: The value to multiply by. - """ +:param n: La valeur par laquelle multiplier.""" ... + def __truediv__(self, n: float) -> Image: - """Create a new image by dividing the brightness of each pixel by - ``n``. + """Crée une nouvelle image en divisant la luminosité de chaque pixel par +``n``. - Example: ``Image.HEART / 2`` +Example: ``Image.HEART / 2`` - :param n: The value to divide by. - """ +:param n: La valeur par laquelle diviser.""" ... class SoundEvent: LOUD: SoundEvent - """Represents the transition of sound events, from ``quiet`` to ``loud`` like clapping or shouting.""" - + """Représente la transition d'événements sonores, de ``quiet`` à ``loud`` comme un clap dans les mains ou un cri.""" QUIET: SoundEvent - """Represents the transition of sound events, from ``loud`` to ``quiet`` like speaking or background music.""" + """Représente la transition d'événements sonores de ``loud`` à ``quiet`` comme parler ou écouter de la musique de fond.""" class Sound: - """The built-in sounds can be called using ``audio.play(Sound.NAME)``.""" - + """Les sons intégrés peuvent être appelés en utilisant ``audio.play(Sound.NAME)``.""" GIGGLE: Sound - """Giggling sound.""" - + """Bruit de gloussement.""" HAPPY: Sound - """Happy sound.""" - + """Son joyeux.""" HELLO: Sound - """Greeting sound.""" - + """Son de salutation.""" MYSTERIOUS: Sound - """Mysterious sound.""" - + """Son mystérieux.""" SAD: Sound - """Sad sound.""" - + """Son triste.""" SLIDE: Sound - """Sliding sound.""" - + """Bruit de glissade.""" SOARING: Sound - """Soaring sound.""" - + """Bruit d'envolée.""" SPRING: Sound - """Spring sound.""" - + """Son d'un ressort.""" TWINKLE: Sound - """Twinkling sound.""" - + """Son de scintillement.""" YAWN: Sound - """Yawning sound.""" + """Son de bâillement.""" \ No newline at end of file diff --git a/lang/fr/typeshed/stdlib/microbit/accelerometer.pyi b/lang/fr/typeshed/stdlib/microbit/accelerometer.pyi index bac82c0..f9f069b 100644 --- a/lang/fr/typeshed/stdlib/microbit/accelerometer.pyi +++ b/lang/fr/typeshed/stdlib/microbit/accelerometer.pyi @@ -1,115 +1,103 @@ -"""Measure the acceleration of the micro:bit and recognise gestures. -""" - +"""Mesurer l'accélération du micro:bit et reconnaitre des mouvements.""" from typing import Tuple def get_x() -> int: - """Get the acceleration measurement in the ``x`` axis in milli-g. + """Récupérer la mesure de l'accélération dans l'axe ``x`` en milli-g. - Example: ``accelerometer.get_x()`` +Example: ``accelerometer.get_x()`` - :return: A positive or negative integer depending on direction in the range +/- 2000mg. - """ +:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" ... def get_y() -> int: - """Get the acceleration measurement in the ``y`` axis in milli-g. + """Récupérer la mesure de l'accélération dans l'axe ``y`` en milli-g. - Example: ``accelerometer.get_y()`` +Example: ``accelerometer.get_y()`` - :return: A positive or negative integer depending on direction in the range +/- 2000mg. - """ +:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" ... def get_z() -> int: - """Get the acceleration measurement in the ``z`` axis in milli-g. + """Récupérer la mesure de l'accélération dans l'axe ``z`` en milli-g. - Example: ``accelerometer.get_z()`` +Example: ``accelerometer.get_z()`` - :return: A positive or negative integer depending on direction in the range +/- 2000mg. - """ +:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" ... def get_values() -> Tuple[int, int, int]: - """Get the acceleration measurements in all axes at once as a tuple. + """Récupérer en une fois les mesures d'accélération dans tous les axes sous forme d'un tuple. - Example: ``x, y, z = accelerometer.get_values()`` +Example: ``x, y, z = accelerometer.get_values()`` - :return: a three-element tuple of integers ordered as X, Y, Z, each value a positive or negative integer depending on direction in the range +/- 2000mg - """ +:return: a three-element tuple of integers ordered as X, Y, Z, each value a positive or negative integer depending on direction in the range +/- 2000mg""" ... def get_strength() -> int: - """Get the acceleration measurement of all axes combined, as a positive integer. This is the Pythagorean sum of the X, Y and Z axes. + """Obtenir la mesure de l'accélération de tous les axes combinés, sous la forme d'un nombre entier positif. C'est la somme pythagoricienne des axes X, Y et Z. - Example: ``accelerometer.get_strength()`` +Example: ``accelerometer.get_strength()`` - :return: The combined acceleration strength of all the axes, in milli-g. - """ +:return: The combined acceleration strength of all the axes, in milli-g.""" ... def current_gesture() -> str: - """Get the name of the current gesture. + """Récupérer le nom du geste actuel. - Example: ``accelerometer.current_gesture()`` +Example: ``accelerometer.current_gesture()`` - 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. +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. - :return: The current gesture - """ +:return: The current gesture""" ... def is_gesture(name: str) -> bool: - """Check if the named gesture is currently active. + """Vérifier si le geste nommé est actif en ce moment. - Example: ``accelerometer.is_gesture('shake')`` +Example: ``accelerometer.is_gesture('shake')`` - 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. +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. - :param name: The gesture name. - :return: ``True`` if the gesture is active, ``False`` otherwise. - """ +:param name: Le nom du geste. +:return: ``True`` if the gesture is active, ``False`` otherwise.""" ... def was_gesture(name: str) -> bool: - """Check if the named gesture was active since the last call. + """Vérifier si le geste nommé a été actif depuis le dernier appel. - Example: ``accelerometer.was_gesture('shake')`` +Example: ``accelerometer.was_gesture('shake')`` - 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. +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. - :param name: The gesture name. - :return: ``True`` if the gesture was active since the last call, ``False`` otherwise. - """ +:param name: Le nom du geste. +:return: ``True`` if the gesture was active since the last call, ``False`` otherwise.""" def get_gestures() -> Tuple[str, ...]: - """Return a tuple of the gesture history. + """Renvoyer un tuple de l'historique des gestes. - Example: ``accelerometer.get_gestures()`` +Example: ``accelerometer.get_gestures()`` - Clears the gesture history before returning. +Clears the gesture history before returning. - Gestures are not updated in the background so there needs to be constant - calls to some accelerometer method to do the gesture detection. Usually - gestures can be detected using a loop with a small :func:`microbit.sleep` delay. +Gestures are not updated in the background so there needs to be constant +calls to some accelerometer method to do the gesture detection. Usually +gestures can be detected using a loop with a small :func:`microbit.sleep` delay. - :return: The history as a tuple, most recent last. - """ +:return: The history as a tuple, most recent last.""" ... def set_range(value: int) -> None: - """Set the accelerometer sensitivity range, in g (standard gravity), to the closest values supported by the hardware, so it rounds to either ``2``, ``4``, or ``8`` g. + """Définir la plage de sensibilité de l'accéléromètre, en g (gravité standard), à la valeur la plus proche supportée par le matériel, l'arrondi se fait soit à ``2``, ``4``, ou ``8`` g. - Example: ``accelerometer.set_range(8)`` +Example: ``accelerometer.set_range(8)`` - :param value: New range for the accelerometer, an integer in ``g``. - """ +:param value: Nouvelle plage pour l'accéléromètre, un entier en ``g``.""" \ No newline at end of file diff --git a/lang/fr/typeshed/stdlib/microbit/audio.pyi b/lang/fr/typeshed/stdlib/microbit/audio.pyi index 3b1e327..4c814a3 100644 --- a/lang/fr/typeshed/stdlib/microbit/audio.pyi +++ b/lang/fr/typeshed/stdlib/microbit/audio.pyi @@ -1,160 +1,124 @@ -"""Play sounds using the micro:bit (import ``audio`` for V1 compatibility). -""" - +"""Jouer des sons en utilisant le micro:bit (importer ``audio`` pour compatibilité V1).""" from ..microbit import MicroBitDigitalPin, Sound, pin0 from typing import ClassVar, Iterable, Union -def play( - source: Union[Iterable[AudioFrame], Sound, SoundEffect], - wait: bool = True, - pin: MicroBitDigitalPin = pin0, - return_pin: Union[MicroBitDigitalPin, None] = None, -) -> None: - """Play a built-in sound, sound effect or custom audio frames. +def play(source: Union[Iterable[AudioFrame], Sound, SoundEffect], wait: bool=True, pin: MicroBitDigitalPin=pin0, return_pin: Union[MicroBitDigitalPin, None]=None) -> None: + """Jouer un son intégré, un effet sonore ou des frames audio personnalisées. - Example: ``audio.play(Sound.GIGGLE)`` +Example: ``audio.play(Sound.GIGGLE)`` - :param source: A built-in ``Sound`` such as ``Sound.GIGGLE``, a ``SoundEffect`` or sample data as an iterable of ``AudioFrame`` objects. - :param wait: If ``wait`` is ``True``, this function will block until the sound is complete. - :param pin: An optional argument to specify the output pin can be used to override the default of ``pin0``. If we do not want any sound to play we can use ``pin=None``. - :param return_pin: Specifies a differential edge connector pin to connect to an external speaker instead of ground. This is ignored for the **V2** revision. - """ +:param source: Un ``Sound`` intégré tel que ``Sound.GIGGLE``, un ``SoundEffect`` ou un échantillon de données sous la forme d'un itérable d'objets ``AudioFrame``. +:param wait: Si ``wait`` est ``True``, cette fonction bloquera jusqu'à ce que le son soit terminé. +:param pin: (broche) Un argument optionnel pour spécifier la broche de sortie, peut être utilisé pour remplacer la valeur par défaut ``pin0``. Si nous ne voulons pas que le son soit joué, il est possible d'utiliser ``pin=None``. +:param return_pin: Spécifie une broche de connecteur de bord différentiel à connecter à un haut-parleur externe au lieu de la masse. Ceci est ignoré dans la révision **V2**.""" def is_playing() -> bool: - """Check whether a sound is playing. + """Vérifier si un son est en train d'être joué. - Example: ``audio.is_playing()`` +Example: ``audio.is_playing()`` - :return: ``True`` if audio is playing, otherwise ``False``.""" +:return: ``True`` if audio is playing, otherwise ``False``.""" ... def stop() -> None: - """Stop all audio playback. + """Arrêter toute lecture audio. - Example: ``audio.stop()`` - """ +Example: ``audio.stop()``""" ... class SoundEffect: - """A sound effect, composed by a set of parameters configured via the constructor or attributes.""" - + """Un effet sonore, composé d'un ensemble de paramètres configurés via le constructeur ou les attributs.""" WAVEFORM_SINE: ClassVar[int] - """Sine wave option used for the ``waveform`` parameter.""" - + """Option d'onde sinusoïdale utilisée pour le paramètre ``waveform``.""" WAVEFORM_SAWTOOTH: ClassVar[int] - """Sawtooth wave option used for the ``waveform`` parameter.""" - + """Optionde forme d'onde en dent de scie utilisée pour le paramètre ``waveform``.""" WAVEFORM_TRIANGLE: ClassVar[int] - """Triangle wave option used for the ``waveform`` parameter.""" - + """Option d'onde triangulaire utilisée pour le paramètre ``waveform``.""" WAVEFORM_SQUARE: ClassVar[int] - """Square wave option used for the ``waveform`` parameter.""" - + """Option d'onde carrée utilisée pour le paramètre ``waveform``.""" WAVEFORM_NOISE: ClassVar[int] - """Noise option used for the ``waveform`` parameter.""" - + """Option d'onde de bruit utilisée pour le paramètre ``waveform``.""" SHAPE_LINEAR: ClassVar[int] - """Linear interpolation option used for the ``shape`` parameter.""" - + """Option d'interpolation linéaire utilisée pour le paramètre ``shape``.""" SHAPE_CURVE: ClassVar[int] - """Curve interpolation option used for the ``shape`` parameter.""" - + """Option d'interpolation courbe utilisée pour le paramètre ``shape``.""" SHAPE_LOG: ClassVar[int] - """Logarithmic interpolation option used for the ``shape`` parameter.""" - + """Option d'interpolation logarithmique utilisée pour le paramètre ``shape``.""" FX_NONE: ClassVar[int] - """No effect option used for the ``fx`` parameter.""" - + """Option sans effet utilisée pour le paramètre ``fx``.""" FX_TREMOLO: ClassVar[int] - """Tremolo effect option used for the ``fx`` parameter.""" - + """Option d'effet tremolo utilisée pour le paramètre ``fx``.""" FX_VIBRATO: ClassVar[int] - """Vibrato effect option used for the ``fx`` parameter.""" - + """Option d'effet vibrato utilisée pour le paramètre ``fx``.""" FX_WARBLE: ClassVar[int] - """Warble effect option used for the ``fx`` parameter.""" - + """Option d'effet de Warble utilisée pour le paramètre ``fx``.""" freq_start: int - """Start frequency in Hertz (Hz), a number between ``0`` and ``9999``""" - + """Fréquence de départ en Hertz (Hz), un nombre compris entre ``0`` et ``9999``""" freq_end: int - """End frequency in Hertz (Hz), a number between ``0`` and ``9999``""" - + """Fréquence de fin en Hertz (Hz), un nombre compris entre ``0`` et ``9999``""" duration: int - """Duration of the sound in milliseconds, a number between ``0`` and ``9999``""" - + """Durée du son en millisecondes, un nombre compris entre ``0`` et ``9999``""" vol_start: int - """Start volume value, a number between ``0`` and ``255``""" - + """Valeur du volume de départ, un nombre compris entre ``0`` et ``255``""" vol_end: int - """End volume value, a number between ``0`` and ``255``""" - + """Valeur du volume à la fin, un nombre compris entre ``0`` et ``255``""" waveform: int - """Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise)""" - + """Type de forme d'onde, une de ces valeurs : ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (bruit généré aléatoirement)""" fx: int - """Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``""" - + """Effet à ajouter au son, l'une des valeurs suivantes : ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, ou ``FX_NONE``""" shape: int - """The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``""" - - def __init__( - self, - freq_start: int = 500, - freq_end: int = 2500, - duration: int = 500, - vol_start: int = 255, - vol_end: int = 0, - waveform: int = WAVEFORM_SQUARE, - fx: int = FX_NONE, - shape: int = SHAPE_LOG, - ): - """Create a new sound effect. - - Example: ``my_effect = SoundEffect(duration=1000)`` - - All the parameters are optional, with default values as shown above, and - they can all be modified via attributes of the same name. For example, we - can first create an effect ``my_effect = SoundEffect(duration=1000)``, - and then change its attributes ``my_effect.duration = 500``. - - :param freq_start: Start frequency in Hertz (Hz), a number between ``0`` and ``9999``. - :param freq_end: End frequency in Hertz (Hz), a number between ``0`` and ``9999``. - :param duration: Duration of the sound in milliseconds, a number between ``0`` and ``9999``. - :param vol_start: Start volume value, a number between ``0`` and ``255``. - :param vol_end: End volume value, a number between ``0`` and ``255``. - :param waveform: Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise). - :param fx: Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``. - :param shape: The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``. - """ + """Le type de la courbe d'interpolation entre les fréquences de début et de fin, les différentes formes d'onde ont des taux de variation de fréquence différents. L'une des valeurs suivantes : ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``""" + + def __init__(self, freq_start: int=500, freq_end: int=2500, duration: int=500, vol_start: int=255, vol_end: int=0, waveform: int=WAVEFORM_SQUARE, fx: int=FX_NONE, shape: int=SHAPE_LOG): + """Créer un nouvel effet sonore. + +Example: ``my_effect = SoundEffect(duration=1000)`` + +All the parameters are optional, with default values as shown above, and +they can all be modified via attributes of the same name. For example, we +can first create an effect ``my_effect = SoundEffect(duration=1000)``, +and then change its attributes ``my_effect.duration = 500``. + +:param freq_start: Fréquence de départ en Hertz (Hz), un nombre compris entre ``0`` et ``9999``. +:param freq_end: Fréquence de fin en Hertz (Hz), un nombre compris entre ``0`` et ``9999``. +:param duration: Durée du son en millisecondes, un nombre compris entre ``0`` et ``9999``. +:param vol_start: Valeur du volume de départ, un nombre compris entre ``0`` et ``255``. +:param vol_end: Valeur du volume à la fin, un nombre compris entre ``0`` et ``255``. +:param waveform: Type de forme d'onde, une de ces valeurs : ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (bruit généré aléatoirement). +:param fx: Effet à ajouter au son, l'une des valeurs suivantes : ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, ou ``FX_NONE``. +:param shape: Le type de la courbe d'interpolation entre les fréquences de début et de fin, les différentes formes d'onde ont des taux de variation de fréquence différents. L'une des valeurs suivantes : ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``.""" + def copy(self) -> SoundEffect: - """Create a copy of this ``SoundEffect``. + """Créer une copie de ce ``SoundEffect``. - Example: ``sound_2 = sound_1.copy()`` +Example: ``sound_2 = sound_1.copy()`` - :return: A copy of the SoundEffect. - """ +:return: A copy of the SoundEffect.""" class AudioFrame: - """An ``AudioFrame`` object is a list of 32 samples each of which is a unsigned byte - (whole number between 0 and 255). + """Un objet ``AudioFrame`` est une liste de 32 échantillons, chacun d'eux étant un octet non signé +(nombre entier entre 0 et 255). - It takes just over 4 ms to play a single frame. +It takes just over 4 ms to play a single frame. - Example:: +Example:: - frame = AudioFrame() - for i in range(len(frame)): - frame[i] = 252 - i * 8 - """ + frame = AudioFrame() + for i in range(len(frame)): + frame[i] = 252 - i * 8""" def copyfrom(self, other: AudioFrame) -> None: - """Overwrite the data in this ``AudioFrame`` with the data from another ``AudioFrame`` instance. + """Écraser les données de ce ``AudioFrame`` avec les données d'une autre instance ``AudioFrame``. + +Example: ``my_frame.copyfrom(source_frame)`` + +:param other: Instance ``AudioFrame`` à partir de laquelle copier les données.""" + + def __len__(self) -> int: + ... - Example: ``my_frame.copyfrom(source_frame)`` + def __setitem__(self, key: int, value: int) -> None: + ... - :param other: ``AudioFrame`` instance from which to copy the data. - """ - def __len__(self) -> int: ... - def __setitem__(self, key: int, value: int) -> None: ... - def __getitem__(self, key: int) -> int: ... + def __getitem__(self, key: int) -> int: + ... \ No newline at end of file diff --git a/lang/fr/typeshed/stdlib/microbit/compass.pyi b/lang/fr/typeshed/stdlib/microbit/compass.pyi index c74a47b..6dfd7d2 100644 --- a/lang/fr/typeshed/stdlib/microbit/compass.pyi +++ b/lang/fr/typeshed/stdlib/microbit/compass.pyi @@ -1,78 +1,70 @@ -"""Use the built-in compass. -""" +"""Utiliser la boussole intégrée.""" def calibrate() -> None: - """Starts the calibration process. + """Démarrer le processus d'étalonnage. - Example: ``compass.calibrate()`` +Example: ``compass.calibrate()`` - 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. - """ +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: - """Check is the compass is calibrated. + """Vérifier si la boussole est étalonnée. - Example: ``compass.is_calibrated()`` +Example: ``compass.is_calibrated()`` - :return: ``True`` if the compass has been successfully calibrated, ``False`` otherwise. - """ +:return: ``True`` if the compass has been successfully calibrated, ``False`` otherwise.""" ... def clear_calibration() -> None: - """Undoes the calibration, making the compass uncalibrated again. + """Annule l'étalonnage, la boussole est ainsi à nouveau non-étalonnée. - Example: ``compass.clear_calibration()`` - """ +Example: ``compass.clear_calibration()``""" ... def get_x() -> int: - """Get the magnetic field strength on the ``x`` axis. + """Obtenir la force du champ magnétique sur l'axe ``x``. - Example: ``compass.get_x()`` +Example: ``compass.get_x()`` - Call ``calibrate`` first or the results will be inaccurate. +Call ``calibrate`` first or the results will be inaccurate. - :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. - """ +:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" ... def get_y() -> int: - """Get the magnetic field strength on the ``y`` axis. + """Obtenir la force du champ magnétique sur l'axe ``y``. - Example: ``compass.get_y()`` +Example: ``compass.get_y()`` - Call ``calibrate`` first or the results will be inaccurate. +Call ``calibrate`` first or the results will be inaccurate. - :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. - """ +:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" ... def get_z() -> int: - """Get the magnetic field strength on the ``z`` axis. + """Obtenir la force du champ magnétique sur l'axe ``z``. - Example: ``compass.get_z()`` +Example: ``compass.get_z()`` - Call ``calibrate`` first or the results will be inaccurate. +Call ``calibrate`` first or the results will be inaccurate. - :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. - """ +:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" ... def heading() -> int: - """Get the compass heading. + """Obtenir le cap de la boussole. - Example: ``compass.heading()`` +Example: ``compass.heading()`` - :return: An integer in the range from 0 to 360, representing the angle in degrees, clockwise, with north as 0. - """ +:return: An integer in the range from 0 to 360, representing the angle in degrees, clockwise, with north as 0.""" ... def get_field_strength() -> int: - """Get the magnitude of the magnetic field around the device. + """Récupère la magnitude du champ magnétique autour de l'appareil. - Example: ``compass.get_field_strength()`` +Example: ``compass.get_field_strength()`` - :return: An integer indication of the magnitude of the magnetic field in nano tesla.""" - ... +:return: An integer indication of the magnitude of the magnetic field in nano tesla.""" + ... \ No newline at end of file diff --git a/lang/fr/typeshed/stdlib/microbit/display.pyi b/lang/fr/typeshed/stdlib/microbit/display.pyi index aa4013e..b3c8311 100644 --- a/lang/fr/typeshed/stdlib/microbit/display.pyi +++ b/lang/fr/typeshed/stdlib/microbit/display.pyi @@ -1,115 +1,92 @@ -"""Show text, images and animations on the 5×5 LED display. -""" - +"""Afficher du texte, des images et des animations sur l'écran LED 5×5.""" from ..microbit import Image from typing import Union, overload, Iterable def get_pixel(x: int, y: int) -> int: - """Get the brightness of the LED at column ``x`` and row ``y``. + """Récupère la luminosité de la LED à la colonne ``x`` et à la ligne ``y``. - Example: ``display.get_pixel(0, 0)`` +Example: ``display.get_pixel(0, 0)`` - :param x: The display column (0..4) - :param y: The display row (0..4) - :return: A number between 0 (off) and 9 (bright) - """ +:param x: La colonne d'affichage (0..4) +:param y: La ligne d'affichage (0..4) +:return: A number 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``. + """Définit la luminosité de la LED à la colonne ``x`` et à la ligne ``y``. - Example: ``display.set_pixel(0, 0, 9)`` +Example: ``display.set_pixel(0, 0, 9)`` - :param x: The display column (0..4) - :param y: The display row (0..4) - :param value: The brightness between 0 (off) and 9 (bright) - """ +:param x: La colonne d'affichage (0..4) +:param y: La ligne d'affichage (0..4) +:param value: La luminosité entre 0 (éteint) et 9 (lumineux)""" ... def clear() -> None: - """Set the brightness of all LEDs to 0 (off). + """Régler la luminosité de toutes les LED à 0 (éteintes). - Example: ``display.clear()`` - """ +Example: ``display.clear()``""" ... -def show( - image: Union[str, float, int, Image, Iterable[Image]], - delay: int = 400, - wait: bool = True, - loop: bool = False, - clear: bool = False, -) -> None: - """Shows images, letters or digits on the LED display. +def show(image: Union[str, float, int, Image, Iterable[Image]], delay: int=400, wait: bool=True, loop: bool=False, clear: bool=False) -> None: + """Afficher des images, des lettres ou des chiffres sur l'affichage LED. - Example: ``display.show(Image.HEART)`` +Example: ``display.show(Image.HEART)`` - When ``image`` is an image or a list of images then each image is displayed in turn. - If ``image`` is a string or number, each letter or digit is displayed in turn. +When ``image`` is an image or a list of images then each image is displayed in turn. +If ``image`` is a string or number, each letter or digit is displayed in turn. - :param image: A string, number, image or list of images to show. - :param delay: Each letter, digit or image is shown with ``delay`` milliseconds between them. - :param wait: If ``wait`` is ``True``, this function will block until the animation is finished, otherwise the animation will happen in the background. - :param loop: If ``loop`` is ``True``, the animation will repeat forever. - :param clear: If ``clear`` is ``True``, the display will be cleared after the sequence has finished. +:param image: Une chaîne de caractères, un nombre, une image ou une liste d'images à afficher. +:param delay: Chaque lettre, chiffre ou image est séparé par un délai de ``delay`` millisecondes. +:param wait: Si ``wait`` est ``True`` cette fonction bloquera jusqu'à la fin de l'animation, sinon l'animation s'effectuera en arrière-plan. +:param loop: Si ``loop`` est ``True``, l'animation se répétera indéfiniment. +:param clear: Si ``clear`` est ``True``, l'affichage sera effacé une fois la séquence terminée. - The ``wait``, ``loop`` and ``clear`` arguments must be specified using their keyword. - """ +The ``wait``, ``loop`` and ``clear`` arguments must be specified using their keyword.""" ... -def scroll( - text: Union[str, float, int], - delay: int = 150, - wait: bool = True, - loop: bool = False, - monospace: bool = False, -) -> None: - """Scrolls a number or text on the LED display. - - Example: ``display.scroll('micro:bit')`` - - :param text: The string to scroll. If ``text`` is an integer or float it is first converted to a string using ``str()``. - :param delay: The ``delay`` parameter controls how fast the text is scrolling. - :param wait: If ``wait`` is ``True``, this function will block until the animation is finished, otherwise the animation will happen in the background. - :param loop: If ``loop`` is ``True``, the animation will repeat forever. - :param monospace: 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. - - The ``wait``, ``loop`` and ``monospace`` arguments must be specified - using their keyword. - """ +def scroll(text: Union[str, float, int], delay: int=150, wait: bool=True, loop: bool=False, monospace: bool=False) -> None: + """Faire défiler un nombre ou un texte sur l'affichage LED. + +Example: ``display.scroll('micro:bit')`` + +:param text: La chaîne de caractères à faire défiler. Si ``text`` est un entier ou un nombre décimal, il sera converti en une chaîne avec ``str()``. +:param delay: Le paramètre ``delay`` contrôle la vitesse de défilement du texte. +:param wait: Si ``wait`` est ``True`` cette fonction bloquera jusqu'à la fin de l'animation, sinon l'animation s'effectuera en arrière-plan. +:param loop: Si ``loop`` est ``True``, l'animation se répétera indéfiniment. +:param monospace: Si ``monospace`` est ``True``, tous les caractères utiliseront 5 pixels en largeur, sinon, exactement 1 colonne de pixel vide sera insérée entre chaque caractère lors du défilement. + +The ``wait``, ``loop`` and ``monospace`` arguments must be specified +using their keyword.""" ... def on() -> None: - """Turn on the LED display. + """Allumer l'écran LED. - Example: ``display.on()`` - """ +Example: ``display.on()``""" ... def off() -> None: - """Turn off the LED display (disabling the display allows you to re-use the GPIO pins for other purposes). + """Eteindre l'écran LED (désactiver l'affichage vous permet de réutiliser les broches GPIO à d'autres fins). - Example: ``display.off()`` - """ +Example: ``display.off()``""" ... def is_on() -> bool: - """Check whether the LED display is enabled. + """Vérifier si l'affichage LED est activé. - Example: ``display.is_on()`` +Example: ``display.is_on()`` - :return: ``True`` if the display is on, otherwise returns ``False``. - """ +:return: ``True`` if the display is on, otherwise returns ``False``.""" ... def read_light_level() -> int: - """Read the light level. + """Lit le niveau de lumière. - Example: ``display.read_light_level()`` +Example: ``display.read_light_level()`` - Uses the display's LEDs in reverse-bias mode to sense the amount of light - falling on the display. +Uses the display's LEDs in reverse-bias mode to sense the amount of light +falling on the display. - :return: An integer between 0 and 255 representing the light level, with larger meaning more light. - """ - ... +:return: An integer between 0 and 255 representing the light level, with larger meaning more light.""" + ... \ No newline at end of file diff --git a/lang/fr/typeshed/stdlib/microbit/i2c.pyi b/lang/fr/typeshed/stdlib/microbit/i2c.pyi index df26efa..dc0230f 100644 --- a/lang/fr/typeshed/stdlib/microbit/i2c.pyi +++ b/lang/fr/typeshed/stdlib/microbit/i2c.pyi @@ -1,57 +1,49 @@ -"""Communicate with devices using the I²C bus protocol. -""" - +"""Communiquer avec les périphériques en utilisant le protocole de bus I²C.""" from _typeshed import ReadableBuffer from ..microbit import MicroBitDigitalPin, pin19, pin20 from typing import List -def init( - freq: int = 100000, sda: MicroBitDigitalPin = pin20, scl: MicroBitDigitalPin = pin19 -) -> None: - """Re-initialize a peripheral. +def init(freq: int=100000, sda: MicroBitDigitalPin=pin20, scl: MicroBitDigitalPin=pin19) -> None: + """Réinitialiser un périphérique. - Example: ``i2c.init()`` +Example: ``i2c.init()`` - :param freq: clock frequency - :param sda: ``sda`` pin (default 20) - :param scl: ``scl`` pin (default 19) +:param freq: fréquence d'horloge +:param sda: Broche ``sda`` (19 par défaut) +:param scl: Broche ``scl`` (19 par défaut) - On a micro:bit V1 board, changing the I²C pins from defaults will make - the accelerometer and compass stop working, as they are connected - internally to those pins. This warning does not apply to the **V2** - revision of the micro:bit as this has `separate I²C lines `_ - for the motion sensors and the edge connector. - """ +On a micro:bit V1 board, changing the I²C pins from defaults will make +the accelerometer and compass stop working, as they are connected +internally to those pins. This warning does not apply to the **V2** +revision of the micro:bit as this has `separate I²C lines `_ +for the motion sensors and the edge connector.""" ... def scan() -> List[int]: - """Scan the bus for devices. + """Scanner le bus pour détecter des périphériques. - Example: ``i2c.scan()`` +Example: ``i2c.scan()`` - :return: A list of 7-bit addresses corresponding to those devices that responded to the scan. - """ +:return: A list of 7-bit addresses corresponding to those devices that responded to the scan.""" ... -def read(addr: int, n: int, repeat: bool = False) -> bytes: - """Read bytes from a device. +def read(addr: int, n: int, repeat: bool=False) -> bytes: + """Lire des octets depuis un périphérique. - Example: ``i2c.read(0x50, 64)`` +Example: ``i2c.read(0x50, 64)`` - :param addr: The 7-bit address of the device - :param n: The number of bytes to read - :param repeat: If ``True``, no stop bit will be sent - :return: The bytes read - """ +:param addr: L'adresse 7-bit du périphérique +:param n: Le nombre d'octets à lire +:param repeat: Si ``True``, aucun bit d'arrêt ne sera envoyé +:return: The bytes read""" ... -def write(addr: int, buf: ReadableBuffer, repeat: bool = False) -> None: - """Write bytes to a device. +def write(addr: int, buf: ReadableBuffer, repeat: bool=False) -> None: + """Écrire des octets sur un périphérique. - Example: ``i2c.write(0x50, bytes([1, 2, 3]))`` +Example: ``i2c.write(0x50, bytes([1, 2, 3]))`` - :param addr: The 7-bit address of the device - :param buf: A buffer containing the bytes to write - :param repeat: If ``True``, no stop bit will be sent - """ - ... +:param addr: L'adresse 7-bit du périphérique +:param buf: Un buffer contenant les octets à écrire +:param repeat: Si ``True``, aucun bit d'arrêt ne sera envoyé""" + ... \ No newline at end of file diff --git a/lang/fr/typeshed/stdlib/microbit/microphone.pyi b/lang/fr/typeshed/stdlib/microbit/microphone.pyi index 68e8f3a..f8071e7 100644 --- a/lang/fr/typeshed/stdlib/microbit/microphone.pyi +++ b/lang/fr/typeshed/stdlib/microbit/microphone.pyi @@ -1,70 +1,62 @@ -"""Respond to sound using the built-in microphone (V2 only). -""" - +"""Réagir à du son en utilisant le microphone intégré (V2 uniquement).""" from typing import Optional, Tuple from ..microbit import SoundEvent def current_event() -> Optional[SoundEvent]: - """Get the last recorded sound event + """Récupérer le dernier événement sonore enregistré - Example: ``microphone.current_event()`` +Example: ``microphone.current_event()`` - :return: The event, ``SoundEvent('loud')`` or ``SoundEvent('quiet')``. - """ +:return: The event, ``SoundEvent('loud')`` or ``SoundEvent('quiet')``.""" ... def was_event(event: SoundEvent) -> bool: - """Check if a sound was heard at least once since the last call. + """Vérifier si un son a été entendu au moins une fois depuis le dernier appel. - Example: ``microphone.was_event(SoundEvent.LOUD)`` +Example: ``microphone.was_event(SoundEvent.LOUD)`` - This call clears the sound history before returning. +This call clears the sound history before returning. - :param event: The event to check for, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET`` - :return: ``True`` if sound was heard at least once since the last call, otherwise ``False``. - """ +:param event: L'événement à vérifier, tel que ``SoundEvent.LOUD`` ou ``SoundEvent.QUIET`` +:return: ``True`` if sound was heard at least once since the last call, otherwise ``False``.""" ... def is_event(event: SoundEvent) -> bool: - """Check the most recent sound event detected. + """Vérifier l'événement sonore le plus récent détecté. - Example: ``microphone.is_event(SoundEvent.LOUD)`` +Example: ``microphone.is_event(SoundEvent.LOUD)`` - This call does not clear the sound event history. +This call does not clear the sound event history. - :param event: The event to check for, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET`` - :return: ``True`` if sound was the most recent heard, ``False`` otherwise. - """ +:param event: L'événement à vérifier, tel que ``SoundEvent.LOUD`` ou ``SoundEvent.QUIET`` +:return: ``True`` if sound was the most recent heard, ``False`` otherwise.""" ... def get_events() -> Tuple[SoundEvent, ...]: - """Get the sound event history as a tuple. + """Récupérer l'historique des événements sonores en tant que tuple. - Example: ``microphone.get_events()`` +Example: ``microphone.get_events()`` - This call clears the sound history before returning. +This call clears the sound history before returning. - :return: A tuple of the event history with the most recent event last. - """ +:return: A tuple of the event history with the most recent event last.""" ... def set_threshold(event: SoundEvent, value: int) -> None: - """Set the threshold for a sound event. + """Définir le seuil pour un événement sonore. - Example: ``microphone.set_threshold(SoundEvent.LOUD, 250)`` +Example: ``microphone.set_threshold(SoundEvent.LOUD, 250)`` - A high threshold means the event will only trigger if the sound is very loud (>= 250 in the example). +A high threshold means the event will only trigger if the sound is very loud (>= 250 in the example). - :param event: A sound event, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET``. - :param value: The threshold level in the range 0-255. - """ +:param event: Un événement sonore, tel que ``SoundEvent.LOUD`` ou ``SoundEvent.QUIET``. +:param value: Le niveau du seuil dans la plage 0-255.""" ... def sound_level() -> int: - """Get the sound pressure level. + """Obtenir le niveau de pression acoustique. - Example: ``microphone.sound_level()`` +Example: ``microphone.sound_level()`` - :return: A representation of the sound pressure level in the range 0 to 255. - """ - ... +:return: A representation of the sound pressure level in the range 0 to 255.""" + ... \ No newline at end of file diff --git a/lang/fr/typeshed/stdlib/microbit/speaker.pyi b/lang/fr/typeshed/stdlib/microbit/speaker.pyi index 5a74a4d..07024ed 100644 --- a/lang/fr/typeshed/stdlib/microbit/speaker.pyi +++ b/lang/fr/typeshed/stdlib/microbit/speaker.pyi @@ -1,18 +1,15 @@ -"""Control the built-in speaker (V2 only). -""" +"""Contrôler le haut-parleur intégré (V2 uniquement).""" def off() -> None: - """Turn the speaker off. + """Éteindre le haut-parleur. - Example: ``speaker.off()`` +Example: ``speaker.off()`` - This does not disable sound output to an edge connector pin. - """ +This does not disable sound output to an edge connector pin.""" ... def on() -> None: - """Turn the speaker on. + """Activer le haut-parleur. - Example: ``speaker.on()`` - """ - ... +Example: ``speaker.on()``""" + ... \ No newline at end of file diff --git a/lang/fr/typeshed/stdlib/microbit/spi.pyi b/lang/fr/typeshed/stdlib/microbit/spi.pyi index 09c4046..226bcf0 100644 --- a/lang/fr/typeshed/stdlib/microbit/spi.pyi +++ b/lang/fr/typeshed/stdlib/microbit/spi.pyi @@ -1,60 +1,47 @@ -"""Communicate with devices using the serial peripheral interface (SPI) bus. -""" - +"""Communiquer avec les périphériques à l'aide du bus SPI (Serial Peripheral Interface).""" from _typeshed import ReadableBuffer, WriteableBuffer from ..microbit import pin13, pin14, pin15, MicroBitDigitalPin -def init( - baudrate: int = 1000000, - bits: int = 8, - mode: int = 0, - sclk: MicroBitDigitalPin = pin13, - mosi: MicroBitDigitalPin = pin15, - miso: MicroBitDigitalPin = pin14, -) -> None: - """Initialize SPI communication. - - Example: ``spi.init()`` - - For correct communication, the parameters have to be the same on both communicating devices. - - :param baudrate: The speed of communication. - :param bits: The width in bits of each transfer. Currently only ``bits=8`` is supported. However, this may change in the future. - :param mode: Determines the combination of clock polarity and phase - `see online table `_. - :param sclk: sclk pin (default 13) - :param mosi: mosi pin (default 15) - :param miso: miso pin (default 14) - """ +def init(baudrate: int=1000000, bits: int=8, mode: int=0, sclk: MicroBitDigitalPin=pin13, mosi: MicroBitDigitalPin=pin15, miso: MicroBitDigitalPin=pin14) -> None: + """Initialiser la communication SPI. + +Example: ``spi.init()`` + +For correct communication, the parameters have to be the same on both communicating devices. + +:param baudrate: La vitesse de communication. +:param bits: La largeur en bits de chaque transfert. Actuellement, seul ``bits=8`` est pris en charge. Cependant, cela peut évoluer à l'avenir. +:param mode: Détermine la combinaison de la polarité et de la phase de l'horloge. - `voir le tableau en ligne `_. +:param sclk: Broche sclk (13 par défaut) +:param mosi: Broche mosi (15 par défaut) +:param miso: Broche miso (14 par défaut)""" ... -def read(nbytes: int, out: int = 0) -> bytes: - """Read at most ``nbytes`` while continuously writing the single byte given by ``out``. +def read(nbytes: int, out: int=0) -> bytes: + """Lire des octets. - Example: ``spi.read(64)`` +Example: ``spi.read(64)`` - :param nbytes: Maximum number of bytes to read. - :param out: The byte value to write (default 0). - :return: The bytes read. - """ +:param nbytes: Nombre maximal d'octets à lire. +:param out: (Sortie) La valeur d'octet à écrire (0 par défaut). +:return: The bytes read.""" ... def write(buffer: ReadableBuffer) -> None: - """Write bytes to the bus. + """Écrire des octets sur le bus. - Example: ``spi.write(bytes([1, 2, 3]))`` +Example: ``spi.write(bytes([1, 2, 3]))`` - :param buffer: A buffer to read data from. - """ +:param buffer: Un buffer à partir duquel lire les données.""" ... def write_readinto(out: WriteableBuffer, in_: ReadableBuffer) -> None: - """Write the ``out`` buffer to the bus and read any response into the ``in_`` buffer. + """Ecrire le buffer ``out`` sur le bus et lire toute réponse dans le buffer ``in_``. - Example: ``spi.write_readinto(out_buffer, in_buffer)`` +Example: ``spi.write_readinto(out_buffer, in_buffer)`` - The length of the buffers should be the same. The buffers can be the same object. +The length of the buffers should be the same. The buffers can be the same object. - :param out: The buffer to write any response to. - :param in_: The buffer to read data from. - """ - ... +:param out: Le buffer vers lequel écrire une réponse. +:param in_: Le buffer depuis lequel lire les données.""" + ... \ No newline at end of file diff --git a/lang/fr/typeshed/stdlib/microbit/uart.pyi b/lang/fr/typeshed/stdlib/microbit/uart.pyi index 2ab650f..6d566a9 100644 --- a/lang/fr/typeshed/stdlib/microbit/uart.pyi +++ b/lang/fr/typeshed/stdlib/microbit/uart.pyi @@ -1,96 +1,79 @@ -"""Communicate with a device using a serial interface. -""" - +"""Communiquer avec un périphérique à l'aide d'une interface série.""" from _typeshed import WriteableBuffer from ..microbit import MicroBitDigitalPin from typing import Optional, Union - ODD: int -"""Odd parity""" - +"""Parité impaire""" EVEN: int -"""Even parity""" - -def init( - baudrate: int = 9600, - bits: int = 8, - parity: Optional[int] = None, - stop: int = 1, - tx: Optional[MicroBitDigitalPin] = None, - rx: Optional[MicroBitDigitalPin] = None, -) -> None: - """Initialize serial communication. - - Example: ``uart.init(115200, tx=pin0, rx=pin1)`` - - :param baudrate: The speed of communication. - :param bits: The size of bytes being transmitted. micro:bit only supports 8. - :param parity: How parity is checked, ``None``, ``uart.ODD`` or ``uart.EVEN``. - :param stop: The number of stop bits, has to be 1 for micro:bit. - :param tx: Transmitting pin. - :param rx: Receiving pin. - - 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. - - For more details see `the online documentation `_. - """ +"""Parité paire""" + +def init(baudrate: int=9600, bits: int=8, parity: Optional[int]=None, stop: int=1, tx: Optional[MicroBitDigitalPin]=None, rx: Optional[MicroBitDigitalPin]=None) -> None: + """Initialiser la communication série. + +Example: ``uart.init(115200, tx=pin0, rx=pin1)`` + +:param baudrate: La vitesse de communication. +:param bits: La taille des octets transmis. micro:bit ne prend en charge que 8. +:param parity: Comment la parité est vérifiée, ``None``, ``uart.ODD`` ou ``uart.EVEN``. +:param stop: Le nombre de bits d'arrêt, doit être 1 pour micro:bit. +:param tx: Broche de transmission. +:param rx: Broche de réception. + +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. + +For more details see `the online documentation `_.""" ... def any() -> bool: - """Check if any data is waiting. + """Vérifier s'il y a des données en attente. - Example: ``uart.any()`` +Example: ``uart.any()`` - :return: ``True`` if any data is waiting, else ``False``. - """ +:return: ``True`` if any data is waiting, else ``False``.""" ... -def read(nbytes: Optional[int] = None) -> Optional[bytes]: - """Read bytes. +def read(nbytes: Optional[int]=None) -> Optional[bytes]: + """Lire des octets. - Example: ``uart.read()`` +Example: ``uart.read()`` - :param nbytes: If ``nbytes`` is specified then read at most that many bytes, otherwise read as many bytes as possible - :return: A bytes object or ``None`` on timeout - """ +:param nbytes: Si ``nbytes`` est spécifié, alors lire au maximum cette quantité d'octets, sinon lire autant d'octets que possible +:return: A bytes object or ``None`` on timeout""" ... -def readinto(buf: WriteableBuffer, nbytes: Optional[int] = None) -> Optional[int]: - """Read bytes into the ``buf``. +def readinto(buf: WriteableBuffer, nbytes: Optional[int]=None) -> Optional[int]: + """Lire les octets dans le ``buf``. - Example: ``uart.readinto(input_buffer)`` +Example: ``uart.readinto(input_buffer)`` - :param buf: The buffer to write to. - :param nbytes: If ``nbytes`` is specified then read at most that many bytes, otherwise read ``len(buf)`` bytes. - :return: number of bytes read and stored into ``buf`` or ``None`` on timeout. - """ +:param buf: Le buffer dans lequel écrire. +:param nbytes: Si ``nbytes`` est spécifié, alors lire au maximum cette quantité d'octets, sinon lire ``len(buf)`` octets. +:return: number of bytes read and stored into ``buf`` or ``None`` on timeout.""" ... def readline() -> Optional[bytes]: - """Read a line, ending in a newline character. + """Lire une ligne terminée par un caractère de nouvelle ligne. - Example: ``uart.readline()`` +Example: ``uart.readline()`` - :return: The line read or ``None`` on timeout. The newline character is included in the returned bytes. - """ +:return: The line read or ``None`` on timeout. The newline character is included in the returned bytes.""" ... def write(buf: Union[bytes, str]) -> Optional[int]: - """Write a buffer to the bus. + """Écrire un buffer sur un bus - Example: ``uart.write('hello world')`` +Example: ``uart.write('hello world')`` - :param buf: A bytes object or a string. - :return: The number of bytes written, or ``None`` on timeout. +:param buf: Un objet d'octets ou une chaîne de caractères. +:return: The number of bytes written, or ``None`` on timeout. - Examples:: +Examples:: - uart.write('hello world') - uart.write(b'hello world') - uart.write(bytes([1, 2, 3])) - """ - ... + uart.write('hello world') + uart.write(b'hello world') + uart.write(bytes([1, 2, 3]))""" + ... \ No newline at end of file diff --git a/lang/fr/typeshed/stdlib/micropython.pyi b/lang/fr/typeshed/stdlib/micropython.pyi index 7a6079f..1ea05cc 100644 --- a/lang/fr/typeshed/stdlib/micropython.pyi +++ b/lang/fr/typeshed/stdlib/micropython.pyi @@ -1,144 +1,132 @@ -"""MicroPython internals.""" - +"""Les coulisses de MicroPython.""" from typing import Any, TypeVar, overload - -_T = TypeVar("_T") +_T = TypeVar('_T') def const(expr: _T) -> _T: - """Used to declare that the expression is a constant so that the compiler can - optimise it. + """Utilisé pour déclarer que l'expression est une constante afin que le compilateur puisse +l'optimiser. - The use of this function should be as follows:: +The use of this function should be as follows:: - from micropython import const - CONST_X = const(123) - CONST_Y = const(2 * CONST_X + 1) + from micropython import const + CONST_X = const(123) + CONST_Y = const(2 * CONST_X + 1) - Constants declared this way are still accessible as global variables from - outside the module they are declared in. On the other hand, if a constant - begins with an underscore then it is hidden, it is not available as a - global variable, and does not take up any memory during execution. +Constants declared this way are still accessible as global variables from +outside the module they are declared in. On the other hand, if a constant +begins with an underscore then it is hidden, it is not available as a +global variable, and does not take up any memory during execution. - :param expr: A constant expression. - """ +:param expr: Une expression constante.""" ... @overload def opt_level() -> int: - """Get the current optimisation level for the compilation of scripts. + """Récupère le niveau d'optimisation actuel pour la compilation des scripts. - Example: ``micropython.opt_level()`` +Example: ``micropython.opt_level()`` - The optimisation level controls the following compilation features: +The optimisation level controls the following compilation features: - - Assertions: at level 0 assertion statements are enabled and compiled - into the bytecode; at levels 1 and higher assertions are not compiled. +- Assertions: at level 0 assertion statements are enabled and compiled + into the bytecode; at levels 1 and higher assertions are not compiled. - - Built-in ``__debug__`` variable: at level 0 this variable expands to - True; at levels 1 and higher it expands to False. +- Built-in ``__debug__`` variable: at level 0 this variable expands to + True; at levels 1 and higher it expands to False. - - Source-code line numbers: at levels 0, 1 and 2 source-code line number - are stored along with the bytecode so that exceptions can report the - line number they occurred at; at levels 3 and higher line numbers are - not stored. +- Source-code line numbers: at levels 0, 1 and 2 source-code line number + are stored along with the bytecode so that exceptions can report the + line number they occurred at; at levels 3 and higher line numbers are + not stored. - :return: An integer representing the current level. - """ +:return: An integer representing the current level.""" ... @overload def opt_level(level: int) -> None: - """Sets the optimisation level for subsequent compilation of scripts. + """Définir le niveau d'optimisation pour la compilation ultérieure des scripts. - Example: ``micropython.opt_level(1)`` +Example: ``micropython.opt_level(1)`` - The optimisation level controls the following compilation features: +The optimisation level controls the following compilation features: - - Assertions: at level 0 assertion statements are enabled and compiled - into the bytecode; at levels 1 and higher assertions are not compiled. +- Assertions: at level 0 assertion statements are enabled and compiled + into the bytecode; at levels 1 and higher assertions are not compiled. - - Built-in ``__debug__`` variable: at level 0 this variable expands to - True; at levels 1 and higher it expands to False. +- Built-in ``__debug__`` variable: at level 0 this variable expands to + True; at levels 1 and higher it expands to False. - - Source-code line numbers: at levels 0, 1 and 2 source-code line number - are stored along with the bytecode so that exceptions can report the - line number they occurred at; at levels 3 and higher line numbers are - not stored. +- Source-code line numbers: at levels 0, 1 and 2 source-code line number + are stored along with the bytecode so that exceptions can report the + line number they occurred at; at levels 3 and higher line numbers are + not stored. - The default optimisation level is usually level 0. +The default optimisation level is usually level 0. - :param level: An integer optimisation level. - """ +:param level: Un entier indiquant le niveau d'optimisation.""" ... -def mem_info(verbose: Any = None) -> None: - """Print information about currently used memory. +def mem_info(verbose: Any=None) -> None: + """Afficher des informations sur la mémoire actuellement utilisée. - Example: ``micropython.mem_info()`` +Example: ``micropython.mem_info()`` - :param verbose: If the ``verbose`` argument is given then extra information is printed. - """ +:param verbose: Si l'argument ``verbose`` est spécifié, des informations supplémentaires seront affichées.""" ... -def qstr_info(verbose: Any = None) -> None: - """Print information about currently interned strings. +def qstr_info(verbose: Any=None) -> None: + """Affiche des informations sur les chaînes de caractères internalisées. - Example: ``micropython.qstr_info()`` +Example: ``micropython.qstr_info()`` - :param verbose: If the ``verbose`` argument is given then extra information is printed. +:param verbose: Si l'argument ``verbose`` est spécifié, des informations supplémentaires seront affichées. - The information that is printed is implementation dependent, but currently - includes the number of interned strings and the amount of RAM they use. In - verbose mode it prints out the names of all RAM-interned strings. - """ +The information that is printed is implementation dependent, but currently +includes the number of interned strings and the amount of RAM they use. In +verbose mode it prints out the names of all RAM-interned strings.""" ... def stack_use() -> int: - """Return an integer representing the current amount of stack that is being - used. + """Renvoie un nombre entier représentant la taille de la pile en cours d'utilisation. - Example: ``micropython.stack_use()`` +Example: ``micropython.stack_use()`` - The absolute value of this is not particularly useful, rather it - should be used to compute differences in stack usage at different points. +The absolute value of this is not particularly useful, rather it +should be used to compute differences in stack usage at different points. - :return: An integer representing current stack use. - """ +:return: An integer representing current stack use.""" ... def heap_lock() -> None: - """Lock the heap. + """Verrouille le tas (heap). - Example: ``micropython.heap_lock()`` +Example: ``micropython.heap_lock()`` - When locked no memory allocation can occur and a ``MemoryError`` will be - raised if any heap allocation is attempted. - """ +When locked no memory allocation can occur and a ``MemoryError`` will be +raised if any heap allocation is attempted.""" ... def heap_unlock() -> None: - """Unlock the heap. + """Déverrouille le tas (heap). - Example: ``micropython.heap_unlock()`` +Example: ``micropython.heap_unlock()`` - When locked no memory allocation can occur and a ``MemoryError`` will be - raised if any heap allocation is attempted. - """ +When locked no memory allocation can occur and a ``MemoryError`` will be +raised if any heap allocation is attempted.""" ... def kbd_intr(chr: int) -> None: - """Set the character that will raise a ``KeyboardInterrupt`` exception. + """Définir le caractère qui lèvera une exception ``KeyboardInterrupt``. - Example: ``micropython.kbd_intr(-1)`` +Example: ``micropython.kbd_intr(-1)`` - :param chr: Character code to raise the interrupt or -1 to disable capture of Ctrl-C. +:param chr: Code de caractère pour générer l'interruption ou -1 pour désactiver la capture de Ctrl-C. - By default this is set to 3 during script execution, corresponding to Ctrl-C. - Passing -1 to this function will disable capture of Ctrl-C, and passing 3 - will restore it. +By default this is set to 3 during script execution, corresponding to Ctrl-C. +Passing -1 to this function will disable capture of Ctrl-C, and passing 3 +will restore it. - This function can be used to prevent the capturing of Ctrl-C on the - incoming stream of characters that is usually used for the REPL, in case - that stream is used for other purposes. - """ - ... +This function can be used to prevent the capturing of Ctrl-C on the +incoming stream of characters that is usually used for the REPL, in case +that stream is used for other purposes.""" + ... \ No newline at end of file diff --git a/lang/fr/typeshed/stdlib/music.pyi b/lang/fr/typeshed/stdlib/music.pyi index 5f4778b..cf7e2fc 100644 --- a/lang/fr/typeshed/stdlib/music.pyi +++ b/lang/fr/typeshed/stdlib/music.pyi @@ -1,167 +1,128 @@ -"""Create and play melodies. -""" +"""Créer et jouer des mélodies.""" from typing import Optional, Tuple, Union, List - from .microbit import MicroBitDigitalPin, pin0 - DADADADUM: Tuple[str, ...] -"""Melody: the opening to Beethoven’s 5th Symphony in C minor.""" - +"""Mélodie : l'ouverture de la 5e symphonie en do mineur de Beethoven.""" ENTERTAINER: Tuple[str, ...] -"""Melody: the opening fragment of Scott Joplin’s Ragtime classic “The Entertainer”.""" - +"""Mélodie : le fragment d'ouverture du classique de ragtime "The Entertainer" de Scott Joplin.""" PRELUDE: Tuple[str, ...] -"""Melody: the opening of the first Prelude in C Major of J.S.Bach’s 48 Preludes and Fugues.""" - +"""Mélodie : le prélude et fugue en ut majeur (BWV 846) de Jean-Sébastien Bach.""" ODE: Tuple[str, ...] -"""Melody: the “Ode to Joy” theme from Beethoven’s 9th Symphony in D minor.""" - +"""Mélodie : le thème de l'"Ode à la joie" de la 9e symphonie en ré mineur de Beethoven.""" NYAN: Tuple[str, ...] -"""Melody: the Nyan Cat theme (http://www.nyan.cat/). +"""Mélodie : le thème de Nyan Cat (http://www.nyan.cat/). The composer is unknown. This is fair use for educational porpoises (as they say in New York).""" - RINGTONE: Tuple[str, ...] -"""Melody: something that sounds like a mobile phone ringtone. +"""Mélodie : son qui ressemble à une sonnerie de téléphone mobile. To be used to indicate an incoming message. """ - FUNK: Tuple[str, ...] -"""Melody: a funky bass line for secret agents and criminal masterminds.""" - +"""Mélodie : une ligne de basse funky pour les agents secrets et les cerveaux criminels.""" BLUES: Tuple[str, ...] -"""Melody: a boogie-woogie 12-bar blues walking bass.""" - +"""Mélodie : une walking bass blues de boogie-woogie à 12 mesures.""" BIRTHDAY: Tuple[str, ...] -"""Melody: “Happy Birthday to You…” +"""Mélodie : « Joyeux anniversaire…» For copyright status see: http://www.bbc.co.uk/news/world-us-canada-34332853 """ - WEDDING: Tuple[str, ...] -"""Melody: the bridal chorus from Wagner’s opera “Lohengrin”.""" - +"""Mélodie : la marche nuptiale de l'opéra "Lohengrin" de Wagner.""" FUNERAL: Tuple[str, ...] -"""Melody: the “funeral march” otherwise known as Frédéric Chopin’s Piano Sonata No. 2 in B♭ minor, Op. 35.""" - +"""Mélodie : la "marche funèbre " aussi connue sous le nom de Sonate pour piano n° 2 en B♭ mineur, opus 35 de Frédéric Chopin.""" PUNCHLINE: Tuple[str, ...] -"""Melody: a fun fragment that signifies a joke has been made.""" - +"""Mélodie : un extrait amusant qui signifie qu'une blague a été faite.""" PYTHON: Tuple[str, ...] -"""Melody: John Philip Sousa’s march “Liberty Bell” aka, the theme for “Monty Python’s Flying Circus” (after which the Python programming language is named).""" - +"""Mélodie : La marche "Liberty Bell" de John Philip Sousa, alias le thème du "Monty Python's Flying Circus" (qui a donné son nom au langage de programmation Python).""" BADDY: Tuple[str, ...] -"""Melody: silent movie era entrance of a baddy.""" - +"""Mélodie\xa0: entrée d'un méchant à l'époque des films muets.""" CHASE: Tuple[str, ...] -"""Melody: silent movie era chase scene.""" - +"""Mélodie : scène de poursuite à l'époque du film muet.""" BA_DING: Tuple[str, ...] -"""Melody: a short signal to indicate something has happened.""" - +"""Mélodie : un signal court pour indiquer que quelque chose s'est produit.""" WAWAWAWAA: Tuple[str, ...] -"""Melody: a very sad trombone.""" - +"""Mélodie : un trombone très triste.""" JUMP_UP: Tuple[str, ...] -"""Melody: for use in a game, indicating upward movement.""" - +"""Mélodie\xa0: pour une utilisation dans un jeu, indiquant un mouvement vers le haut.""" JUMP_DOWN: Tuple[str, ...] -"""Melody: for use in a game, indicating downward movement.""" - +"""Mélodie\xa0: pour une utilisation dans un jeu, indiquant un mouvement vers le bas.""" POWER_UP: Tuple[str, ...] -"""Melody: a fanfare to indicate an achievement unlocked.""" - +"""Mélodie : une fanfare pour indiquer un succès débloqué.""" POWER_DOWN: Tuple[str, ...] -"""Melody: a sad fanfare to indicate an achievement lost.""" +"""Mélodie : une fanfare triste pour indiquer un succès manqué.""" -def set_tempo(ticks: int = 4, bpm: int = 120) -> None: - """Sets the approximate tempo for playback. +def set_tempo(ticks: int=4, bpm: int=120) -> None: + """Définir le tempo approximatif pour la lecture. - Example: ``music.set_tempo(bpm=120)`` +Example: ``music.set_tempo(bpm=120)`` - :param ticks: The number of ticks constituting a beat. - :param bpm: An integer determining how many beats per minute. +:param ticks: Le nombre de ticks constituant un battement. +:param bpm: Un entier déterminant le nombre de battements par minute. - Suggested default values allow the following useful behaviour: +Suggested default values allow the following useful behaviour: - - music.set_tempo() – reset the tempo to default of ticks = 4, bpm = 120 - - music.set_tempo(ticks=8) – change the “definition” of a beat - - music.set_tempo(bpm=180) – just change the tempo +- music.set_tempo() – reset the tempo to default of ticks = 4, bpm = 120 +- music.set_tempo(ticks=8) – change the “definition” of a beat +- music.set_tempo(bpm=180) – just change the tempo - To work out the length of a tick in milliseconds is very simple arithmetic: - 60000/bpm/ticks_per_beat. For the default values that’s - 60000/120/4 = 125 milliseconds or 1 beat = 500 milliseconds. - """ +To work out the length of a tick in milliseconds is very simple arithmetic: +60000/bpm/ticks_per_beat. For the default values that’s +60000/120/4 = 125 milliseconds or 1 beat = 500 milliseconds.""" ... def get_tempo() -> Tuple[int, int]: - """Gets the current tempo as a tuple of integers: ``(ticks, bpm)``. + """Récupérer le tempo actuel sous la forme d'un tuple d'entiers : ``(ticks, bpm)``. - Example: ``ticks, beats = music.get_tempo()`` +Example: ``ticks, beats = music.get_tempo()`` - :return: The temp as a tuple with two integer values, the ticks then the beats per minute. - """ +:return: The temp as a tuple with two integer values, the ticks then the beats per minute.""" ... -def play( - music: Union[str, List[str], Tuple[str, ...]], - pin: Optional[MicroBitDigitalPin] = pin0, - wait: bool = True, - loop: bool = False, -) -> None: - """Plays music. +def play(music: Union[str, List[str], Tuple[str, ...]], pin: Optional[MicroBitDigitalPin]=pin0, wait: bool=True, loop: bool=False) -> None: + """Jouer de la musique. - Example: ``music.play(music.NYAN)`` +Example: ``music.play(music.NYAN)`` - :param music: music specified in `a special notation `_ - :param pin: the output pin for use with an external speaker (default ``pin0``), ``None`` for no sound. - :param wait: If ``wait`` is set to ``True``, this function is blocking. - :param loop: If ``loop`` is set to ``True``, the tune repeats until ``stop`` is called or the blocking call is interrupted. +:param music: musique spécifiée dans `une notation spéciale `_ +:param pin: (broche) la broche de sortie à utiliser avec un haut-parleur externe (par défaut ``pin0``), ``None`` pour aucun son. +:param wait: Si ``wait`` est défini à ``True``, cette fonction est bloquante. +:param loop: Si ``loop`` est défini à ``True``, la mélodie se répète jusqu'à ce que ``stop`` soit appelé, ou que l'appel bloquant soit interrompu. - Many built-in melodies are defined in this module. - """ +Many built-in melodies are defined in this module.""" ... -def pitch( - frequency: int, - duration: int = -1, - pin: Optional[MicroBitDigitalPin] = pin0, - wait: bool = True, -) -> None: - """Play a note. +def pitch(frequency: int, duration: int=-1, pin: Optional[MicroBitDigitalPin]=pin0, wait: bool=True) -> None: + """Jouer une note. (tangage) - Example: ``music.pitch(185, 1000)`` +Example: ``music.pitch(185, 1000)`` - :param frequency: An integer frequency - :param duration: A millisecond duration. If negative then sound is continuous until the next call or a call to ``stop``. - :param pin: Optional output pin (default ``pin0``). - :param wait: If ``wait`` is set to ``True``, this function is blocking. +:param frequency: (fréquence) Une fréquence entière +:param duration: Une durée en milliseconde. Si la valeur est négative alors le son sera continu jusqu'au prochain appel, ou jusqu'à un appel à ``stop``. +:param pin: (broche) Broche de sortie optionnelle (par défaut ``pin0``). +:param wait: Si ``wait`` est défini à ``True``, cette fonction est bloquante. - For example, if the frequency is set to 440 and the length to - 1000 then we hear a standard concert A for one second. +For example, if the frequency is set to 440 and the length to +1000 then we hear a standard concert A for one second. - You can only play one pitch on one pin at any one time. - """ +You can only play one pitch on one pin at any one time.""" ... -def stop(pin: Optional[MicroBitDigitalPin] = pin0) -> None: - """Stops all music playback on the built-in speaker and any pin outputting sound. +def stop(pin: Optional[MicroBitDigitalPin]=pin0) -> None: + """Met fin à toute lecture de musique sur le haut-parleur intégré et à tout son en sortie sur la broche. - Example: ``music.stop()`` +Example: ``music.stop()`` - :param pin: An optional argument can be provided to specify a pin, e.g. ``music.stop(pin1)``. - """ +:param pin: (broche) Un argument optionnel peut être spécifié pour indiquer une broche, par exemple ``music.stop(pin1)``.""" def reset() -> None: - """Resets ticks, bpm, duration and octave to their default values. + """Réinitialiser les ticks, bpm, durée et octave à leurs valeurs par défaut. - Example: ``music.reset()`` +Example: ``music.reset()`` - Values: - - ``ticks = 4`` - - ``bpm = 120`` - - ``duration = 4`` - - ``octave = 4`` - """ - ... +Values: +- ``ticks = 4`` +- ``bpm = 120`` +- ``duration = 4`` +- ``octave = 4``""" + ... \ No newline at end of file diff --git a/lang/fr/typeshed/stdlib/neopixel.pyi b/lang/fr/typeshed/stdlib/neopixel.pyi index 2d5a749..cbe90e5 100644 --- a/lang/fr/typeshed/stdlib/neopixel.pyi +++ b/lang/fr/typeshed/stdlib/neopixel.pyi @@ -1,82 +1,81 @@ -"""Individually addressable RGB and RGBW LED strips. -""" +"""Bandes LED RGB et RGBW individuellement adressables.""" from .microbit import MicroBitDigitalPin from typing import Tuple class NeoPixel: - def __init__(self, pin: MicroBitDigitalPin, n: int, bpp: int = 3) -> None: - """Initialise a new strip of neopixel LEDs controlled via a pin. - Example: ``np = neopixel.NeoPixel(pin0, 8)`` + def __init__(self, pin: MicroBitDigitalPin, n: int, bpp: int=3) -> None: + """Initialiser une nouvelle bande de LEDs neopixel contrôlée via une broche. - To support RGBW neopixels, a third argument can be passed to - ``NeoPixel`` to indicate the number of bytes per pixel (``bpp``). - For RGBW, this is is 4 rather than the default of 3 for RGB and GRB. +Example: ``np = neopixel.NeoPixel(pin0, 8)`` - Each pixel is addressed by a position (starting from 0). Neopixels are - given RGB (red, green, blue) / RGBW (red, green, blue, white) values - between 0-255 as a tuple. For example, in RGB, ``(255,255,255)`` is - white. In RGBW, ``(255,255,255,0)`` or ``(0,0,0,255)`` is white. +To support RGBW neopixels, a third argument can be passed to +``NeoPixel`` to indicate the number of bytes per pixel (``bpp``). +For RGBW, this is is 4 rather than the default of 3 for RGB and GRB. - See `the online docs `_ for warnings and other advice. +Each pixel is addressed by a position (starting from 0). Neopixels are +given RGB (red, green, blue) / RGBW (red, green, blue, white) values +between 0-255 as a tuple. For example, in RGB, ``(255,255,255)`` is +white. In RGBW, ``(255,255,255,0)`` or ``(0,0,0,255)`` is white. - :param pin: The pin controlling the neopixel strip. - :param n: The number of neopixels in the strip. - :param bpp: Bytes per pixel. For RGBW neopixel support, pass 4 rather than the default of 3 for RGB and GRB. - """ +See `the online docs `_ for warnings and other advice. + +:param pin: (broche) La broche qui contrôle la bande neopixel. +:param n: Le nombre de neopixels sur la bande. +:param bpp: Octets par pixel. Pour le support du neopixel RGBW, passez 4 plutôt que la valeur par défaut 3 pour RGB et GRB.""" ... + def clear(self) -> None: - """Clear all the pixels. + """Effacer tous les pixels. - Example: ``np.clear()`` - """ +Example: ``np.clear()``""" ... + def show(self) -> None: - """Show the pixels. + """Afficher les pixels. - Example: ``np.show()`` +Example: ``np.show()`` - Must be called for any updates to become visible. - """ +Must be called for any updates to become visible.""" ... + def write(self) -> None: - """Show the pixels (micro:bit V2 only). + """Afficher les pixels (micro:bit V2 uniquement). - Example: ``np.write()`` +Example: ``np.write()`` - Must be called for any updates to become visible. +Must be called for any updates to become visible. - Equivalent to ``show``. - """ +Equivalent to ``show``.""" ... + def fill(self, colour: Tuple[int, ...]) -> None: - """Colour all pixels a given RGB/RGBW value (micro:bit V2 only). + """Colorer tous les pixels d'une valeur RGB/RGBW donnée (micro:bit V2 uniquement). - Example: ``np.fill((0, 0, 255))`` +Example: ``np.fill((0, 0, 255))`` - :param colour: A tuple of the same length as the number of bytes per pixel (bpp). +:param colour: Un tuple de la même longueur que le nombre d'octets par pixel (bpp). - Use in conjunction with ``show()`` to update the neopixels. - """ +Use in conjunction with ``show()`` to update the neopixels.""" ... + def __setitem__(self, key: int, value: Tuple[int, ...]) -> None: - """Set a pixel colour. + """Définit une couleur de pixel. - Example: ``np[0] = (255, 0, 0)`` +Example: ``np[0] = (255, 0, 0)`` + +:param key: Le numéro du pixel +:param value: La couleur.""" - :param key: The pixel number. - :param value: The colour. - """ def __getitem__(self, key: int) -> Tuple[int, ...]: - """Get a pixel colour. + """Récupère la couleur d'un pixel + +Example: ``r, g, b = np[0]`` - Example: ``r, g, b = np[0]`` +:param key: Le numéro du pixel +:return: The colour tuple.""" - :param key: The pixel number. - :return: The colour tuple. - """ def __len__(self) -> int: - """Get length of this pixel strip. + """Récupère la longueur de cette bande de pixels. - Example: ``len(np)`` - """ +Example: ``len(np)``""" \ No newline at end of file diff --git a/lang/fr/typeshed/stdlib/os.pyi b/lang/fr/typeshed/stdlib/os.pyi index 2f2db77..091695a 100644 --- a/lang/fr/typeshed/stdlib/os.pyi +++ b/lang/fr/typeshed/stdlib/os.pyi @@ -1,73 +1,63 @@ -"""Access the file system. -""" - +"""Accéder au système de fichiers.""" from typing import Tuple from typing import List def listdir() -> List[str]: - """List files. + """Lister les fichiers. - Example: ``os.listdir()`` +Example: ``os.listdir()`` - :return: A list of the names of all the files contained within the local - persistent on-device file system. - """ +:return: A list of the names of all the files contained within the local +persistent on-device file system.""" ... def remove(filename: str) -> None: - """Remove (delete) a file. + """Supprimer (effacer) un fichier. - Example: ``os.remove('data.txt')`` +Example: ``os.remove('data.txt')`` - :param filename: The file to delete. +:param filename: Le fichier à effacer. - If the file does not exist an ``OSError`` exception will occur. - """ +If the file does not exist an ``OSError`` exception will occur.""" ... def size(filename: str) -> int: - """Returns the size of a file. + """Retourne la taille d'un fichier. - Example: ``os.size('data.txt')`` +Example: ``os.size('data.txt')`` - :param filename: The file - :return: The size in bytes. +:param filename: Le fichier +:return: The size in bytes. - If the file does not exist an ``OSError`` exception will occur. - """ +If the file does not exist an ``OSError`` exception will occur.""" class uname_result(Tuple[str, str, str, str, str]): - """Result of ``os.uname()``""" + """Résultat de ``os.uname()``""" sysname: str - """Operating system name.""" - + """Nom du système d'exploitation.""" nodename: str - """Name of machine on network (implementation-defined).""" - + """Nom de la machine sur le réseau (selon implémentation).""" release: str - """Operating system release.""" - + """La release du système d'exploitation""" version: str - """Operating system version.""" - + """Version du système d'exploitation""" machine: str - """Hardware identifier.""" + """Identifiant matériel.""" def uname() -> uname_result: - """Returns information identifying the current operating system. + """Retourne les informations identifiant le système d'exploitation actuel. - Example: ``os.uname()`` +Example: ``os.uname()`` - The return value is an object with five attributes: +The return value is an object with five attributes: - - ``sysname`` - operating system name - - ``nodename`` - name of machine on network (implementation-defined) - - ``release`` - operating system release - - ``version`` - operating system version - - ``machine`` - hardware identifier +- ``sysname`` - operating system name +- ``nodename`` - name of machine on network (implementation-defined) +- ``release`` - operating system release +- ``version`` - operating system version +- ``machine`` - hardware identifier - There is no underlying operating system in MicroPython. As a result the - information returned by the ``uname`` function is mostly useful for - versioning details. - """ - ... +There is no underlying operating system in MicroPython. As a result the +information returned by the ``uname`` function is mostly useful for +versioning details.""" + ... \ No newline at end of file diff --git a/lang/fr/typeshed/stdlib/radio.pyi b/lang/fr/typeshed/stdlib/radio.pyi index 8dd0267..256533d 100644 --- a/lang/fr/typeshed/stdlib/radio.pyi +++ b/lang/fr/typeshed/stdlib/radio.pyi @@ -1,152 +1,130 @@ -"""Communicate between micro:bits with the built-in radio. -""" - +"""Communiquer entre micro:bits avec la radio intégrée.""" from _typeshed import WriteableBuffer from typing import Optional, Tuple - RATE_1MBIT: int -"""Constant used to indicate a throughput of 1 MBit a second.""" - +"""Constante utilisée pour indiquer un débit de 1 MBit par seconde.""" RATE_2MBIT: int -"""Constant used to indicate a throughput of 2 MBit a second.""" +"""Constante utilisée pour indiquer un débit de 2 MBit par seconde.""" def on() -> None: - """Turns the radio on. + """Allume la radio. - Example: ``radio.on()`` +Example: ``radio.on()`` - This needs to be explicitly called since the radio draws power and takes - up memory that you may otherwise need. - """ +This needs to be explicitly called since the radio draws power and takes +up memory that you may otherwise need.""" ... def off() -> None: - """Turns off the radio, saving power and memory. + """Désactive la radio, économisant ainsi de l'énergie et de la mémoire. - Example: ``radio.off()`` - """ +Example: ``radio.off()``""" ... -def config( - length: int = 32, - queue: int = 3, - channel: int = 7, - power: int = 6, - address: int = 0x75626974, - group: int = 0, - data_rate: int = RATE_1MBIT, -) -> None: - """Configures the radio. - - Example: ``radio.config(group=42)`` - - The default configuration is suitable for most use. - - :param length: (default=32) defines the maximum length, in bytes, of a message sent via the radio. - It can be up to 251 bytes long (254 - 3 bytes for S0, LENGTH and S1 preamble). - :param queue: (default=3) specifies the number of messages that can be stored on the incoming message queue. - If there are no spaces left on the queue for incoming messages, then the incoming message is dropped. - :param channel: (default=7) an integer value from 0 to 83 (inclusive) that defines an arbitrary "channel" to which the radio is tuned. - Messages will be sent via this channel and only messages received via this channel will be put onto the incoming message queue. Each step is 1MHz wide, based at 2400MHz. - :param power: (default=6) is an integer value from 0 to 7 (inclusive) to indicate the strength of signal used when broadcasting a message. - The higher the value the stronger the signal, but the more power is consumed by the device. The numbering translates to positions in the following list of dBm (decibel milliwatt) values: -30, -20, -16, -12, -8, -4, 0, 4. - :param address: (default=0x75626974) an arbitrary name, expressed as a 32-bit address, that's used to filter incoming packets at the hardware level, keeping only those that match the address you set. - The default used by other micro:bit related platforms is the default setting used here. - :param group: (default=0) an 8-bit value (0-255) used with the ``address`` when filtering messages. - Conceptually, "address" is like a house/office address and "group" is like the person at that address to which you want to send your message. - :param data_rate: (default=``radio.RATE_1MBIT``) indicates the speed at which data throughput takes place. - Can be one of the following constants defined in the ``radio`` module: ``RATE_250KBIT``, ``RATE_1MBIT`` or ``RATE_2MBIT``. - - If ``config`` is not called then the defaults described above are assumed. - """ +def config(length: int=32, queue: int=3, channel: int=7, power: int=6, address: int=1969383796, group: int=0, data_rate: int=RATE_1MBIT) -> None: + """Configure la radio. + +Example: ``radio.config(group=42)`` + +The default configuration is suitable for most use. + +:param length: (par défaut=32) définit la longueur maximale en octets d'un message envoyé via la radio. +Il peut faire jusqu'à 251 octets de long (254 - 3 octets pour S0, LENGTH et préambule S1). +:param queue: (par défaut=3) spécifie le nombre de messages qui peuvent être stockés dans la file d'attente des messages entrants. +S'il n'y a plus de place dans la file d'attente des messages entrants, alors le message entrant est abandonné. +:param channel: (par défaut=7) une valeur entière comprise entre 0 et 83 (y compris) qui définit un « canal » arbitraire sur lequel la radio est réglée. +Les messages seront envoyés via ce canal et seuls les messages reçus via ce canal seront placés dans la file d'attente des messages entrants. Chaque incrément est de 1 MHz de largeur, basé à 2400 MHz. +:param power: (par défaut=6) est une valeur entière comprise entre 0 et 7 (y compris) pour indiquer la force du signal utilisé lors de la diffusion d'un message. +Plus la valeur est élevée, plus le signal est fort, mais plus les besoins en alimentation sont élevés. La numérotation se traduit par des positions dans la liste suivante de valeurs en dBm (décibel milliwatt) : -30, -20, -16, -12, -8, -4, 0, 4. +:param address: (par défaut=0x75626974) un nom arbitraire, exprimé sous la forme d'une adresse 32-bit, utilisé pour filtrer au niveau matériel les paquet entrants, seuls les paquets correspondant à l'adresse définie seront conservés. +La valeur par défaut utilisée par d'autres plateformes liées au micro:bit est celle indiquée ici. +:param group: (par défaut=0) une valeur de 8 bits (0-255) utilisée avec ``address`` lors du filtrage des messages. +Conceptuellement, "adress" est comme l'adresse d'une maison ou d'un bureau, et "group" est comme la personne à laquelle vous voulez envoyer votre message. +:param data_rate: (par défaut=``radio.RATE_1MBIT``) indique la vitesse à laquelle le débit de données a lieu. +Peut être une des constantes suivantes définies dans le module ``radio``\xa0: ``RATE_250KBIT``, ``RATE_1MBIT`` ou ``RATE_2MBIT``. + +If ``config`` is not called then the defaults described above are assumed.""" ... def reset() -> None: - """Reset the settings to their default values. + """Réinitialiser les paramètres à leurs valeurs par défaut. - Example: ``radio.reset()`` +Example: ``radio.reset()`` - The defaults as as per the ``config`` function above. - """ +The defaults as as per the ``config`` function above.""" ... def send_bytes(message: bytes) -> None: - """Sends a message containing bytes. + """Envoie un message contenant des octets. - Example: ``radio.send_bytes(b'hello')`` +Example: ``radio.send_bytes(b'hello')`` - :param message: The bytes to send. - """ +:param message: Les octets à envoyer.""" ... def receive_bytes() -> Optional[bytes]: - """Receive the next incoming message on the message queue. + """Recevoir le message entrant suivant dans la file d'attente des messages. - Example: ``radio.receive_bytes()`` +Example: ``radio.receive_bytes()`` - :return: The message bytes if any, otherwise ``None``. - """ +:return: The message bytes if any, otherwise ``None``.""" ... def receive_bytes_into(buffer: WriteableBuffer) -> Optional[int]: - """Copy the next incoming message on the message queue into a buffer. + """Copier le message entrant suivant de la file d'attente des messages vers un buffer. - Example: ``radio.receive_bytes_info(buffer)`` +Example: ``radio.receive_bytes_info(buffer)`` - :param buffer: The target buffer. The message is truncated if larger than the buffer. - :return: ``None`` if there are no pending messages, otherwise it returns the length of the message (which might be more than the length of the buffer). - """ +:param buffer: Le buffer cible. Le message est tronqué s'il est plus grand que le buffer. +:return: ``None`` if there are no pending messages, otherwise it returns the length of the message (which might be more than the length of the buffer).""" ... def send(message: str) -> None: - """Sends a message string. + """Envoie un message avec une chaîne de caractères. - Example: ``radio.send('hello')`` +Example: ``radio.send('hello')`` - This is the equivalent of ``radio.send_bytes(bytes(message, 'utf8'))`` but with ``b'\x01\x00\x01'`` - prepended to the front (to make it compatible with other platforms that target the micro:bit). +This is the equivalent of ``radio.send_bytes(bytes(message, 'utf8'))`` but with ``b'\x01\x00\x01'`` +prepended to the front (to make it compatible with other platforms that target the micro:bit). - :param message: The string to send. - """ +:param message: Le texte à envoyer.""" ... def receive() -> Optional[str]: - """Works in exactly the same way as ``receive_bytes`` but returns whatever was sent. + """Fonctionne exactement de la même manière que ``receive_bytes`` mais retourne ce qui a été envoyé. - Example: ``radio.receive()`` +Example: ``radio.receive()`` - Equivalent to ``str(receive_bytes(), 'utf8')`` but with a check that the the first - three bytes are ``b'\x01\x00\x01'`` (to make it compatible with other platforms that - may target the micro:bit). +Equivalent to ``str(receive_bytes(), 'utf8')`` but with a check that the the first +three bytes are ``b'\x01\x00\x01'`` (to make it compatible with other platforms that +may target the micro:bit). - :return: The message with the prepended bytes stripped and converted to a string. +:return: The message with the prepended bytes stripped and converted to a string. - A ``ValueError`` exception is raised if conversion to string fails. - """ +A ``ValueError`` exception is raised if conversion to string fails.""" ... def receive_full() -> Optional[Tuple[bytes, int, int]]: - """Returns a tuple containing three values representing the next incoming message on the message queue. + """Retourne un tuple contenant trois valeurs qui représentent le prochain message entrant dans la file d'attente. - Example: ``radio.receive_full()`` +Example: ``radio.receive_full()`` - If there are no pending messages then ``None`` is returned. +If there are no pending messages then ``None`` is returned. - The three values in the tuple represent: +The three values in the tuple represent: - - the next incoming message on the message queue as bytes. - - the RSSI (signal strength): a value between 0 (strongest) and -255 (weakest) as measured in dBm. - - a microsecond timestamp: the value returned by ``time.ticks_us()`` when the message was received. +- the next incoming message on the message queue as bytes. +- the RSSI (signal strength): a value between 0 (strongest) and -255 (weakest) as measured in dBm. +- a microsecond timestamp: the value returned by ``time.ticks_us()`` when the message was received. - For example:: +For example:: - details = radio.receive_full() - if details: - msg, rssi, timestamp = details + details = radio.receive_full() + if details: + msg, rssi, timestamp = details - This function is useful for providing information needed for triangulation - and/or trilateration with other micro:bit devices. +This function is useful for providing information needed for triangulation +and/or trilateration with other micro:bit devices. - :return: ``None`` if there is no message, otherwise a tuple of length three with the bytes, strength and timestamp values. - """ - ... +:return: ``None`` if there is no message, otherwise a tuple of length three with the bytes, strength and timestamp values.""" + ... \ No newline at end of file diff --git a/lang/fr/typeshed/stdlib/random.pyi b/lang/fr/typeshed/stdlib/random.pyi index a2c2ef3..ffd86c1 100644 --- a/lang/fr/typeshed/stdlib/random.pyi +++ b/lang/fr/typeshed/stdlib/random.pyi @@ -1,93 +1,80 @@ -"""Generate random numbers. -""" +"""Générer des nombres aléatoires.""" from typing import TypeVar, Sequence, Union, overload def getrandbits(n: int) -> int: - """Generate an integer with ``n`` random bits. + """Générer un entier avec ``n`` bits aléatoires. - Example: ``random.getrandbits(1)`` +Example: ``random.getrandbits(1)`` - :param n: A value between 1-30 (inclusive). - """ +:param n: Une valeur comprise entre 1-30 (inclus).""" ... def seed(n: int) -> None: - """Initialize the random number generator. + """Initialiser le générateur de nombres aléatoires. - Example: ``random.seed(0)`` +Example: ``random.seed(0)`` - :param n: The integer seed +:param n: La graine aléatoire - This will give you reproducibly deterministic randomness from a given starting - state (``n``). - """ +This will give you reproducibly deterministic randomness from a given starting +state (``n``).""" ... def randint(a: int, b: int) -> int: - """Choose a random integer between ``a`` and ``b`` inclusive. + """Choisir un entier aléatoire entre ``a`` et ``b`` inclus. - Example: ``random.randint(0, 9)`` +Example: ``random.randint(0, 9)`` - :param a: Start value for the range (inclusive) - :param b: End value for the range (inclusive) +:param a: Valeur de départ pour l'intervalle (inclus) +:param b: Valeur de fin pour l'intervalle (inclus) - Alias for ``randrange(a, b + 1)``. - """ +Alias for ``randrange(a, b + 1)``.""" ... @overload def randrange(stop: int) -> int: - """Choose a randomly selected integer between zero and up to (but not - including) ``stop``. + """Choisir un entier aléatoirement entre zéro et ``stop`` (mais sans inclure ce dernier). - Example: ``random.randrange(10)`` +Example: ``random.randrange(10)`` - :param stop: End value for the range (exclusive) - """ +:param stop: Valeur de fin pour l'intervalle (exclusif)""" ... @overload -def randrange(start: int, stop: int, step: int = 1) -> int: - """ - Choose a randomly selected element from ``range(start, stop, step)``. +def randrange(start: int, stop: int, step: int=1) -> int: + """Choisir un élément sélectionné aléatoirement dans ``range(start, stop, step)``. - Example: ``random.randrange(0, 10)`` +Example: ``random.randrange(0, 10)`` - :param start: The start of the range (inclusive) - :param stop: The end of the range (exclusive) - :param step: The step. - """ +:param start: Le début de la plage (inclus) +:param stop: La fin de l'intervalle (exclusif) +:param step: L'incrément.""" ... - -_T = TypeVar("_T") +_T = TypeVar('_T') def choice(seq: Sequence[_T]) -> _T: - """Choose a random element from the non-empty sequence ``seq``. + """Choisir un élément aléatoire dans la séquence non vide ``seq``. - Example: ``random.choice([Image.HAPPY, Image.SAD])`` +Example: ``random.choice([Image.HAPPY, Image.SAD])`` - :param seq: A sequence. +:param seq: Une séquence. - If ``seq`` is empty, raises ``IndexError``. - """ +If ``seq`` is empty, raises ``IndexError``.""" ... def random() -> float: - """Generate a random floating point number in the range [0.0, 1.0). + """Générer un nombre aléatoire à virgule flottante [0.0, 1.0). - Example: ``random.random()`` +Example: ``random.random()`` - :return: The random floating point number - """ +:return: The random floating point number""" ... def uniform(a: float, b: float) -> float: - """ - Return a random floating point number between ``a`` and ``b`` inclusive. + """Renvoie un nombre aléatoire à virgule flottante entre ``a`` et ``b`` inclus. - Example: ``random.uniform(0, 9)`` +Example: ``random.uniform(0, 9)`` - :param a: Start value for the range (inclusive) - :param b: End value for the range (inclusive) - """ - ... +:param a: Valeur de départ pour l'intervalle (inclus) +:param b: Valeur de fin pour l'intervalle (inclus)""" + ... \ No newline at end of file diff --git a/lang/fr/typeshed/stdlib/speech.pyi b/lang/fr/typeshed/stdlib/speech.pyi index 349d188..5a9ac34 100644 --- a/lang/fr/typeshed/stdlib/speech.pyi +++ b/lang/fr/typeshed/stdlib/speech.pyi @@ -1,106 +1,79 @@ -"""Make the micro:bit talk, sing and make other speech like sounds. -""" - +"""Faites parler ou chanter le micro:bit, ainsi que d'autres sons liés à la parole.""" from typing import Optional from .microbit import MicroBitDigitalPin, pin0 def translate(words: str) -> str: - """Translate English words to phonemes. + """Traduire les mots anglais en phonèmes. - Example: ``speech.translate('hello world')`` +Example: ``speech.translate('hello world')`` - :param words: A string of English words. - :return: A string containing a best guess at the appropriate phonemes to pronounce. - The output is generated from this `text to phoneme translation table `_. +:param words: Une chaîne de caractères de mots anglais. +:return: A string containing a best guess at the appropriate phonemes to pronounce. +The output is generated from this `text to phoneme translation table `_. - This function should be used to generate a first approximation of phonemes - that can be further hand-edited to improve accuracy, inflection and - emphasis. +This function should be used to generate a first approximation of phonemes +that can be further hand-edited to improve accuracy, inflection and +emphasis. - See `the online documentation `_ for detailed information. - """ +See `the online documentation `_ for detailed information.""" ... -def pronounce( - phonemes: str, - pitch: int = 64, - speed: int = 72, - mouth: int = 128, - throat: int = 128, - pin: Optional[MicroBitDigitalPin] = pin0, -) -> None: - """Pronounce phonemes. - - Example: ``speech.pronounce(' /HEHLOW WERLD')`` - - :param phonemes: The string of phonemes to pronounce - :param pitch: A number representing the pitch of the voice - :param speed: A number representing the speed of the voice - :param mouth: A number representing the mouth of the voice - :param throat: A number representing the throat of the voice - :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. - If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. - - Override the optional pitch, speed, mouth and throat settings to change the - timbre (quality) of the voice. - - See `the online documentation `_ for detailed information. - """ - ... +def pronounce(phonemes: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: Optional[MicroBitDigitalPin]=pin0) -> None: + """Prononcer les phonèmes. + +Example: ``speech.pronounce(' /HEHLOW WERLD')`` + +:param phonemes: La chaîne de phonèmes à prononcer +:param pitch: (tangage) Un nombre représentant le ton de la voix +:param speed: Un nombre représentant la vitesse de la voix +:param mouth: Un nombre représentant la bouche de la voix +:param throat: Un nombre représentant la gorge de la voix +:param pin: (broche) Argument optionnel pour spécifier la broche de sortie. Peut être utilisé pour remplacer la valeur par défaut de ``pin0``. +Pour empêcher l'émission d'un son via les broches, il est possible d'utiliser ``pin=None``. micro:bit V2 seulement. -def say( - words: str, - pitch: int = 64, - speed: int = 72, - mouth: int = 128, - throat: int = 128, - pin: MicroBitDigitalPin = pin0, -) -> None: - """Say English words. - - Example: ``speech.say('hello world')`` - - :param words: The string of words to say. - :param pitch: A number representing the pitch of the voice - :param speed: A number representing the speed of the voice - :param mouth: A number representing the mouth of the voice - :param throat: A number representing the throat of the voice - :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. - If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. - - The result is semi-accurate for English. Override the optional pitch, speed, - mouth and throat settings to change the timbre (quality) of the voice. - - This is a short-hand equivalent of: - ``speech.pronounce(speech.translate(words))`` - - See `the online documentation `_ for detailed information. - """ +Override the optional pitch, speed, mouth and throat settings to change the +timbre (quality) of the voice. + +See `the online documentation `_ for detailed information.""" ... -def sing( - phonemes: str, - pitch: int = 64, - speed: int = 72, - mouth: int = 128, - throat: int = 128, - pin: MicroBitDigitalPin = pin0, -) -> None: - """Sing phonemes. - - Example: ``speech.sing(' /HEHLOW WERLD')`` - - :param phonemes: The string of words to sing. - :param pitch: A number representing the pitch of the voice - :param speed: A number representing the speed of the voice - :param mouth: A number representing the mouth of the voice - :param throat: A number representing the throat of the voice - :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. - If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. - - Override the optional pitch, speed, mouth and throat settings to change - the timbre (quality) of the voice. - - See `the online documentation `_ for detailed information. - """ +def say(words: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: MicroBitDigitalPin=pin0) -> None: + """Dire des mots anglais. + +Example: ``speech.say('hello world')`` + +:param words: La chaîne de mots à dire. +:param pitch: (tangage) Un nombre représentant le ton de la voix +:param speed: Un nombre représentant la vitesse de la voix +:param mouth: Un nombre représentant la bouche de la voix +:param throat: Un nombre représentant la gorge de la voix +:param pin: (broche) Argument optionnel pour spécifier la broche de sortie. Peut être utilisé pour remplacer la valeur par défaut de ``pin0``. +Pour empêcher l'émission d'un son via les broches, il est possible d'utiliser ``pin=None``. micro:bit V2 seulement. + +The result is semi-accurate for English. Override the optional pitch, speed, +mouth and throat settings to change the timbre (quality) of the voice. + +This is a short-hand equivalent of: +``speech.pronounce(speech.translate(words))`` + +See `the online documentation `_ for detailed information.""" ... + +def sing(phonemes: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: MicroBitDigitalPin=pin0) -> None: + """Chanter des phonèmes. + +Example: ``speech.sing(' /HEHLOW WERLD')`` + +:param phonemes: La chaîne de mots à chanter. +:param pitch: (tangage) Un nombre représentant le ton de la voix +:param speed: Un nombre représentant la vitesse de la voix +:param mouth: Un nombre représentant la bouche de la voix +:param throat: Un nombre représentant la gorge de la voix +:param pin: (broche) Argument optionnel pour spécifier la broche de sortie. Peut être utilisé pour remplacer la valeur par défaut de ``pin0``. +Pour empêcher l'émission d'un son via les broches, il est possible d'utiliser ``pin=None``. micro:bit V2 seulement. + +Override the optional pitch, speed, mouth and throat settings to change +the timbre (quality) of the voice. + +See `the online documentation `_ for detailed information.""" + ... \ No newline at end of file diff --git a/lang/fr/typeshed/stdlib/struct.pyi b/lang/fr/typeshed/stdlib/struct.pyi index 53b3e0b..efffeb6 100644 --- a/lang/fr/typeshed/stdlib/struct.pyi +++ b/lang/fr/typeshed/stdlib/struct.pyi @@ -1,65 +1,56 @@ -"""Pack and unpack primitive data types. -""" - +"""Rassembler et désassembler des types de données primitives.""" from _typeshed import ReadableBuffer, WriteableBuffer from typing import Any, Tuple, Union def calcsize(fmt: str) -> int: - """Get the number of bytes needed to store the given ``fmt``. + """Récupère le nombre d'octets nécessaires pour stocker le ``fmt`` donné. - Example: ``struct.calcsize('hf')`` +Example: ``struct.calcsize('hf')`` - :param fmt: A format string. - :return The number of bytes needed to store such a value. - """ +:param fmt: Une chaîne de mise en forme. +:return The number of bytes needed to store such a value.""" ... def pack(fmt: str, v1: Any, *vn: Any) -> bytes: - """Pack values according to a format string. + """Rassembler les valeurs selon une chaîne de mise en forme. - Example: ``struct.pack('hf', 1, 3.1415)`` +Example: ``struct.pack('hf', 1, 3.1415)`` - :param fmt: The format string. - :param v1: The first value. - :param *vn: The remaining values. - :return A bytes object encoding the values. - """ +:param fmt: La chaîne de mise en forme. +:param v1: La première valeur. +:param *vn: Les valeurs restantes. +:return A bytes object encoding the values.""" ... -def pack_into( - fmt: str, buffer: WriteableBuffer, offset: int, v1: Any, *vn: Any -) -> None: - """Pack values according to a format string. +def pack_into(fmt: str, buffer: WriteableBuffer, offset: int, v1: Any, *vn: Any) -> None: + """Rassembler les valeurs selon une chaîne de format. (Rassembler dans) - Example: ``struct.pack_info('hf', buffer, 1, 3.1415)`` +Example: ``struct.pack_info('hf', buffer, 1, 3.1415)`` - :param fmt: The format string. - :param buffer: The target buffer to write into. - :param offset: The offset into the buffer. May be negative to count from the end of the buffer. - :param v1: The first value. - :param *vn: The remaining values. - """ +:param fmt: La chaîne de format. +:param buffer: Le tampon cible dans lequel écrire. +:param offset: Le décalage dans le tampon. Peut être négatif pour compter à partir de la fin du tampon. +:param v1: La première valeur. +:param *vn: Les valeurs restantes.""" ... def unpack(fmt: str, data: ReadableBuffer) -> Tuple[Any, ...]: - """Unpack data according to a format string. + """Décompacter les données selon une chaîne de format. - Example: ``v1, v2 = struct.unpack('hf', buffer)`` +Example: ``v1, v2 = struct.unpack('hf', buffer)`` - :param fmt: The format string. - :param data: The data. - :return: A tuple of the unpacked values. - """ +:param fmt: La chaîne de format. +:param data: Les données. +:return: A tuple of the unpacked values.""" ... -def unpack_from(fmt: str, buffer: ReadableBuffer, offset: int = 0) -> Tuple: - """Unpack data from a buffer according to a format string. +def unpack_from(fmt: str, buffer: ReadableBuffer, offset: int=0) -> Tuple: + """Décompacter les données d'un tampon selon une chaîne de format. - Example: ``v1, v2 = struct.unpack_from('hf', buffer)`` +Example: ``v1, v2 = struct.unpack_from('hf', buffer)`` - :param fmt: The format string. - :param buffer: The source buffer to read from. - :param offset: The offset into the buffer. May be negative to count from the end of the buffer. - :return: A tuple of the unpacked values. - """ - ... +:param fmt: La chaîne de format. +:param buffer: Le tampon source à partir duquel lire. +:param offset: Le décalage dans le tampon. Peut être négatif pour compter à partir de la fin du tampon. +:return: A tuple of the unpacked values.""" + ... \ No newline at end of file diff --git a/lang/fr/typeshed/stdlib/sys.pyi b/lang/fr/typeshed/stdlib/sys.pyi index 320bac9..acb99fe 100644 --- a/lang/fr/typeshed/stdlib/sys.pyi +++ b/lang/fr/typeshed/stdlib/sys.pyi @@ -1,43 +1,36 @@ -"""System specific functions""" - +"""Fonctions spécifiques au système""" from typing import Any, Dict, List, NoReturn, TextIO, Tuple -def exit(retval: object = ...) -> NoReturn: - """Terminate current program with a given exit code. +def exit(retval: object=...) -> NoReturn: + """Terminer le programme en cours avec un code de sortie donné. - Example: ``sys.exit(1)`` +Example: ``sys.exit(1)`` - This function raises a ``SystemExit`` exception. If an argument is given, its - value given as an argument to ``SystemExit``. +This function raises a ``SystemExit`` exception. If an argument is given, its +value given as an argument to ``SystemExit``. - :param retval: The exit code or message. - """ +:param retval: Le code de sortie ou le message.""" ... def print_exception(exc: Exception) -> None: - """ - Print an exception with a traceback. - - Example: ``sys.print_exception(e)`` + """Imprime une exception avec une pile d'appels. - :param exc: The exception to print +Example: ``sys.print_exception(e)`` - This is simplified version of a function which appears in the - ``traceback`` module in CPython. - """ +:param exc: L'exception à imprimer +This is simplified version of a function which appears in the +``traceback`` module in CPython.""" argv: List[str] -"""A mutable list of arguments the current program was started with.""" - +"""Une liste mutable d'arguments avec lesquels le programme courant a été démarré.""" byteorder: str -"""The byte order of the system (``"little"`` or ``"big"``).""" +"""L'ordre des octets du système (``"little"`` ou ``"big"``).""" class _implementation: name: str version: Tuple[int, int, int] - implementation: _implementation -"""Object with information about the current Python implementation. +"""Objet avec des informations sur l'implémentation actuelle de Python. For MicroPython, it has following attributes: @@ -51,13 +44,12 @@ minimal ports). CPython mandates more attributes for this object, but the actual useful bare minimum is implemented in MicroPython. """ - maxsize: int """ -Maximum value which a native integer type can hold on the current platform, -or maximum value representable by MicroPython integer type, if it's smaller -than platform max value (that is the case for MicroPython ports without -long int support). +Valeur maximale qu'un entier natif peut stocker sur la plate-forme courante, +ou valeur maximale représentable par le type entier de MicroPython, si elle est plus petite +que la valeur maximale de la plate-forme (c'est le cas pour les portages MicroPython sans support +des entiers long). This attribute is useful for detecting "bitness" of a platform (32-bit vs 64-bit, etc.). It's recommended to not compare this attribute to some @@ -77,17 +69,14 @@ value directly, but instead count number of bits in it:: # (e.g. 31) due to peculiarities described above, so use "> 16", # "> 32", "> 64" style of comparisons. """ - modules: Dict[str, Any] -"""Dictionary of loaded modules. +"""Dictionnaire des modules chargés. On some ports, it may not include builtin modules.""" - path: List[str] -"""A mutable list of directories to search for imported modules.""" - +"""Une liste mutable de répertoires dans lesquels rechercher des modules importés.""" platform: str -"""The platform that MicroPython is running on. +"""La plate-forme sur laquelle MicroPython s'exécute. For OS/RTOS ports, this is usually an identifier of the OS, e.g. ``"linux"``. For baremetal ports it is an identifier of a board, e.g. ``"pyboard"`` for @@ -97,13 +86,11 @@ distinguish one board from another. If you need to check whether your program runs on MicroPython (vs other Python implementation), use ``sys.implementation`` instead. """ - version: str -"""Python language version that this implementation conforms to, as a string.""" - +"""Version du langage Python à laquelle cette implémentation correspond, sous la forme d'une chaîne de caractères .""" version_info: Tuple[int, int, int] -"""Python language version that this implementation conforms to, as a tuple of ints. +"""Version du langage Python à laquelle cette implémentation correspond, sous forme d'un tuple d'entiers. Only the first three version numbers (major, minor, micro) are supported and they can be referenced only by index, not by name. -""" +""" \ No newline at end of file diff --git a/lang/fr/typeshed/stdlib/time.pyi b/lang/fr/typeshed/stdlib/time.pyi index 598c483..349a64b 100644 --- a/lang/fr/typeshed/stdlib/time.pyi +++ b/lang/fr/typeshed/stdlib/time.pyi @@ -1,132 +1,115 @@ -"""Measure time and add delays to programs. -""" - +"""Mesurer le temps et ajouter des retards aux programmes.""" from typing import Union def sleep(seconds: Union[int, float]) -> None: - """ - Delay a number of seconds. + """Temporiser d'un certain nombre de secondes. - Example: ``time.sleep(1)`` +Example: ``time.sleep(1)`` - :param seconds: The number of seconds to sleep for. - Use a floating-point number to sleep for a fractional number of seconds. - """ +:param seconds: Le nombre de secondes pendant lesquelles dormir. +Utiliser un nombre à virgule flottante pour dormir pendant un nombre fractionnaire de secondes.""" ... def sleep_ms(ms: int) -> None: - """ - Delay for given number of milliseconds. + """Temporiser pour un nombre donné de millisecondes. - Example: ``time.sleep_ms(1_000_000)`` +Example: ``time.sleep_ms(1_000_000)`` - :param ms: The number of milliseconds delay (>= 0). - """ +:param ms: Le nombre de millisecondes à attendre (>= 0).""" ... def sleep_us(us: int) -> None: - """ - Delay for given number of microseconds. + """Temporiser pour un nombre donné de microsecondes. - Example: ``time.sleep_us(1000)`` +Example: ``time.sleep_us(1000)`` - :param us: The number of microseconds delay (>= 0). - """ +:param us: Le nombre de microsecondes à attendre (>= 0).""" ... def ticks_ms() -> int: - """ - Get an increasing, millisecond counter with an arbitrary reference point, - that wraps around after some value. + """Obtenir un compteur croissant en millisecondes avec un point de référence arbitraire. +Le compteur revient à zéro après une certaine valeur. - Example: ``time.ticks_ms()`` +Example: ``time.ticks_ms()`` - :return: The counter value in milliseconds. - """ +:return: The counter value in milliseconds.""" ... def ticks_us() -> int: - """ - Get an increasing, microsecond counter with an arbitrary reference point, - that wraps around after some value. + """Obtenir un compteur croissant en microsecondes avec un point de référence arbitraire. +Le compteur revient à zéro après une certaine valeur. - Example: ``time.ticks_us()`` +Example: ``time.ticks_us()`` - :return: The counter value in microseconds. - """ +:return: The counter value in microseconds.""" ... def ticks_add(ticks: int, delta: int) -> int: - """ - Offset ticks value by a given number, which can be either positive or - negative. + """Décaler les ticks par un nombre donné, positif ou négatif. - Example: ``time.ticks_add(time.ticks_ms(), 200)`` +Example: ``time.ticks_add(time.ticks_ms(), 200)`` - Given a ticks value, this function allows to calculate ticks - value delta ticks before or after it, following modular-arithmetic - definition of tick values. +Given a ticks value, this function allows to calculate ticks +value delta ticks before or after it, following modular-arithmetic +definition of tick values. - :param ticks: A ticks value - :param delta: An integer offset +:param ticks: Une valeur de ticks +:param delta: Un entier représentant le décalage - Example:: +Example:: - # Find out what ticks value there was 100ms ago - print(ticks_add(time.ticks_ms(), -100)) + # Find out what ticks value there was 100ms ago + print(ticks_add(time.ticks_ms(), -100)) - # Calculate deadline for operation and test for it - deadline = ticks_add(time.ticks_ms(), 200) - while ticks_diff(deadline, time.ticks_ms()) > 0: - do_a_little_of_something() + # Calculate deadline for operation and test for it + deadline = ticks_add(time.ticks_ms(), 200) + while ticks_diff(deadline, time.ticks_ms()) > 0: + do_a_little_of_something() - # Find out TICKS_MAX used by this port - print(ticks_add(0, -1)) - """ + # Find out TICKS_MAX used by this port + print(ticks_add(0, -1))""" ... def ticks_diff(ticks1: int, ticks2: int) -> int: - """ - Measure ticks difference between values returned from - ``time.ticks_ms()`` or ``ticks_us()``, as a signed value - which may wrap around. - - Example: ``time.ticks_diff(scheduled_time, now)`` - - :param ticks1: The value to subtract from - :param ticks2: The value to subtract - - The argument order is the same as for subtraction operator, - ``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. - - ``ticks_diff()`` is designed to accommodate various usage - patterns, among them: - - Polling with timeout. In this case, the order of events is known, and you - will deal only with positive results of :func:`time.ticks_diff()`:: - - # Wait for GPIO pin to be asserted, but at most 500us - start = time.ticks_us() - while pin.value() == 0: - if time.ticks_diff(time.ticks_us(), start) > 500: - raise TimeoutError - - - Scheduling events. In this case, :func:`time.ticks_diff()` result may be - negative if an event is overdue:: - - # This code snippet is not optimized - now = time.ticks_ms() - scheduled_time = task.scheduled_time() - if ticks_diff(scheduled_time, now) > 0: - print("Too early, let's nap") - sleep_ms(ticks_diff(scheduled_time, now)) - task.run() - elif ticks_diff(scheduled_time, now) == 0: - print("Right at time!") - task.run() - elif ticks_diff(scheduled_time, now) < 0: - print("Oops, running late, tell task to run faster!") - task.run(run_faster=True) - """ - ... + """Mesurer la différence des ticks entre les valeurs retournées par +``time.ticks_ms()`` ou ``ticks_us()``, sous la forme d'une valeur signée +qui peut passer plusieurs fois par zéro. + +Example: ``time.ticks_diff(scheduled_time, now)`` + +:param ticks1: La valeur à partir de laquelle soustraire +:param ticks2: La valeur à soustraire + +The argument order is the same as for subtraction operator, +``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. + +``ticks_diff()`` is designed to accommodate various usage +patterns, among them: + +Polling with timeout. In this case, the order of events is known, and you +will deal only with positive results of :func:`time.ticks_diff()`:: + + # Wait for GPIO pin to be asserted, but at most 500us + start = time.ticks_us() + while pin.value() == 0: + if time.ticks_diff(time.ticks_us(), start) > 500: + raise TimeoutError + + +Scheduling events. In this case, :func:`time.ticks_diff()` result may be +negative if an event is overdue:: + + # This code snippet is not optimized + now = time.ticks_ms() + scheduled_time = task.scheduled_time() + if ticks_diff(scheduled_time, now) > 0: + print("Too early, let's nap") + sleep_ms(ticks_diff(scheduled_time, now)) + task.run() + elif ticks_diff(scheduled_time, now) == 0: + print("Right at time!") + task.run() + elif ticks_diff(scheduled_time, now) < 0: + print("Oops, running late, tell task to run faster!") + task.run(run_faster=True)""" + ... \ No newline at end of file diff --git a/lang/ja/typeshed/stdlib/gc.pyi b/lang/ja/typeshed/stdlib/gc.pyi index 1370abf..31e433d 100644 --- a/lang/ja/typeshed/stdlib/gc.pyi +++ b/lang/ja/typeshed/stdlib/gc.pyi @@ -1,73 +1,68 @@ -"""Control the garbage collector""" - +"""ガベージコレクターを制御します。""" from typing import overload def enable() -> None: - """Enable automatic garbage collection.""" + """自動ガベージコレクションを有効にします。""" ... def disable() -> None: - """Disable automatic garbage collection. + """自動ガベージコレクションを無効にします。 - Heap memory can still be allocated, - and garbage collection can still be initiated manually using ``gc.collect``.""" +Heap memory can still be allocated, +and garbage collection can still be initiated manually using ``gc.collect``.""" def collect() -> None: - """Run a garbage collection.""" + """ガベージコレクションを実行します。""" ... def mem_alloc() -> int: - """Get the number of bytes of heap RAM that are allocated. + """割り当てられているヒープRAMのバイト数を取得します。 - :return: The number of bytes allocated. +:return: The number of bytes allocated. - This function is MicroPython extension. - """ +This function is MicroPython extension.""" ... def mem_free() -> int: - """Get the number of bytes of available heap RAM, or -1 if this amount is not known. + """使用可能なヒープRAMのバイト数を取得します。この量が不明の場合は -1が返されます。 - :return: The number of bytes free. +:return: The number of bytes free. - This function is MicroPython extension. - """ +This function is MicroPython extension.""" ... @overload def threshold() -> int: - """Query the additional GC allocation threshold. + """追加のGC 割り当てしきい値を照会します。 - :return: The GC allocation threshold. +:return: The GC allocation threshold. - This function is a MicroPython extension. CPython has a similar - function - ``set_threshold()``, but due to different GC - implementations, its signature and semantics are different. - """ +This function is a MicroPython extension. CPython has a similar +function - ``set_threshold()``, but due to different GC +implementations, its signature and semantics are different.""" ... @overload def threshold(amount: int) -> None: - """Set the additional GC allocation threshold. - - Normally, a collection is triggered only when a new allocation - cannot be satisfied, i.e. on an out-of-memory (OOM) condition. - If this function is called, in addition to OOM, a collection - will be triggered each time after ``amount`` bytes have been - allocated (in total, since the previous time such an amount of bytes - have been allocated). ``amount`` is usually specified as less than the - full heap size, with the intention to trigger a collection earlier than when the - heap becomes exhausted, and in the hope that an early collection will prevent - excessive memory fragmentation. This is a heuristic measure, the effect - of which will vary from application to application, as well as - the optimal value of the ``amount`` parameter. - - A value of -1 means a disabled allocation threshold. - - This function is a MicroPython extension. CPython has a similar - function - ``set_threshold()``, but due to different GC - implementations, its signature and semantics are different. - - :param amount: The number of bytes after which a garbage collection should be triggered. - """ - ... + """追加の GC 割り当てしきい値を設定します。 + +Normally, a collection is triggered only when a new allocation +cannot be satisfied, i.e. on an out-of-memory (OOM) condition. +If this function is called, in addition to OOM, a collection +will be triggered each time after ``amount`` bytes have been +allocated (in total, since the previous time such an amount of bytes +have been allocated). ``amount`` is usually specified as less than the +full heap size, with the intention to trigger a collection earlier than when the +heap becomes exhausted, and in the hope that an early collection will prevent +excessive memory fragmentation. This is a heuristic measure, the effect +of which will vary from application to application, as well as +the optimal value of the ``amount`` parameter. + +A value of -1 means a disabled allocation threshold. + +This function is a MicroPython extension. CPython has a similar +function - ``set_threshold()``, but due to different GC +implementations, its signature and semantics are different. + +:param amount: ガベージコレクションを起こすバイト数。""" + ... \ No newline at end of file diff --git a/lang/ja/typeshed/stdlib/log.pyi b/lang/ja/typeshed/stdlib/log.pyi index c9870fa..ed5ff86 100644 --- a/lang/ja/typeshed/stdlib/log.pyi +++ b/lang/ja/typeshed/stdlib/log.pyi @@ -1,104 +1,89 @@ -"""Log data to your micro:bit V2.""" - +"""micro:bit V2のログにデータを記録します。""" from typing import Literal, Mapping, Optional, Union, overload - MILLISECONDS = 1 -"""Milliseconds timestamp format.""" - +"""ミリ秒単位の日時フォーマット。""" SECONDS = 10 -"""Seconds timestamp format.""" - +"""秒単位の日時フォーマット。""" MINUTES = 600 -"""Minutes timestamp format.""" - +"""分単位の日時フォーマット。""" HOURS = 36000 -"""Hours timestamp format.""" - +"""時間単位の日時フォーマット。""" DAYS = 864000 -"""Days timestamp format.""" +"""日単位の日時フォーマット。""" -def set_labels( - *labels: str, timestamp: Optional[Literal[1, 10, 36000, 864000]] = SECONDS -) -> None: - """Set up the log file header. +def set_labels(*labels: str, timestamp: Optional[Literal[1, 10, 36000, 864000]]=SECONDS) -> None: + """ログファイルのヘッダーを設定します。 - Example: ``log.set_labels('X', 'Y', 'Z', timestamp=log.MINUTES)`` +Example: ``log.set_labels('X', 'Y', 'Z', timestamp=log.MINUTES)`` - Ideally this function should be called a single time, before any data is - logged, to configure the data table header once. +Ideally this function should be called a single time, before any data is +logged, to configure the data table header once. - If a log file already exists when the program starts, or if this function - is called multiple times, it will check the labels already defined in the - log file. If this function call contains any new labels not already - present, it will generate a new header row with the additional columns. +If a log file already exists when the program starts, or if this function +is called multiple times, it will check the labels already defined in the +log file. If this function call contains any new labels not already +present, it will generate a new header row with the additional columns. - By default the first column contains a timestamp for each row. The time - unit can be selected via the timestamp argument. +By default the first column contains a timestamp for each row. The time +unit can be selected via the timestamp argument. - :param *labels: Any number of positional arguments, each corresponding to an entry in the log header. - :param timestamp: Select the timestamp unit that will be automatically added as the first column in every row. Timestamp values can be one of ``log.MILLISECONDS``, ``log.SECONDS``, ``log.MINUTES``, ``log.HOURS``, ``log.DAYS`` or ``None`` to disable the timestamp. The default value is ``log.SECONDS``. - """ +:param *labels: 任意の数の位置引数で。それぞれがログヘッダの見出しになります。 +:param timestamp: すべての行の最初の列として自動的に追加されるタイムスタンプの単位を選択します。タイムスタンプの値は ``log.MILLISECONDS``、 ``log.SECONDS``、``log.MINUTES``、``log.HOURS``、``log.DAYS`` またはタイムスタンプを無効にする ``None`` のうちのいずれかである必要があります。デフォルト値は ``log.SECONDS`` です。""" ... @overload -def add( - data_dictionary: Optional[Mapping[str, Union[str, int, float]]], -) -> None: - """Add a data row to the log by passing a dictionary of headers and values. +def add(data_dictionary: Optional[Mapping[str, Union[str, int, float]]]) -> None: + """ヘッダーと値の辞書を渡すことにより、ログにデータ行を追加します。 - Example: ``log.add({ 'temp': temperature() })`` +Example: ``log.add({ 'temp': temperature() })`` - Each call to this function adds a row to the log. +Each call to this function adds a row to the log. - New labels not previously specified via the set_labels function, or by a - previous call to this function, will trigger a new header entry to be added - to the log with the extra labels. +New labels not previously specified via the set_labels function, or by a +previous call to this function, will trigger a new header entry to be added +to the log with the extra labels. - Labels previously specified and not present in a call to this function will - be skipped with an empty value in the log row. +Labels previously specified and not present in a call to this function will +be skipped with an empty value in the log row. - :param data_dictionary: The data to log as a dictionary with a key for each header. - """ +:param data_dictionary: (data dictionary とはデータ辞書の意味です) 記録するデータを辞書で指定します。辞書の各キーが見出しを表します。""" ... @overload def add(**kwargs: Union[str, int, float]) -> None: - """Add a data row to the log using keyword arguments. + """キーワード引数でログにデータ行を追加します。 - Example: ``log.add(temp=temperature())`` +Example: ``log.add(temp=temperature())`` - Each call to this function adds a row to the log. +Each call to this function adds a row to the log. - New labels not previously specified via the set_labels function, or by a - previous call to this function, will trigger a new header entry to be added - to the log with the extra labels. +New labels not previously specified via the set_labels function, or by a +previous call to this function, will trigger a new header entry to be added +to the log with the extra labels. - Labels previously specified and not present in a call to this function will - be skipped with an empty value in the log row. - """ +Labels previously specified and not present in a call to this function will +be skipped with an empty value in the log row.""" ... def delete(full=False): - """Deletes the contents of the log, including headers. + """ログの内容を、ヘッダーもあわせて削除します。 - Example: ``log.delete()`` +Example: ``log.delete()`` - To add the log headers again the ``set_labels`` function should to be called after this function. +To add the log headers again the ``set_labels`` function should to be called after this function. - There are two erase modes; “full” completely removes the data from the physical storage, - and “fast” invalidates the data without removing it. +There are two erase modes; “full” completely removes the data from the physical storage, +and “fast” invalidates the data without removing it. - :param full: ``True`` selects a “full” erase and ``False`` selects the “fast” erase method. - """ +:param full: ``True`` を指定すると「完全」消去になり、``False`` を指定すると「高速」消去になります。""" ... def set_mirroring(serial: bool): - """Configure mirroring of the data logging activity to the serial output. + """ログのデータ記録をシリアル出力にミラーリングするかを設定します。 - Example: ``log.set_mirroring(True)`` +Example: ``log.set_mirroring(True)`` - Serial mirroring is disabled by default. When enabled, it will print to serial each row logged into the log file. +Serial mirroring is disabled by default. When enabled, it will print to serial each row logged into the log file. - :param serial: ``True`` enables mirroring data to the serial output. - """ - ... +:param serial: ``True`` を指定するとシリアル出力にデータをミラーリングします。""" + ... \ No newline at end of file diff --git a/lang/ja/typeshed/stdlib/machine.pyi b/lang/ja/typeshed/stdlib/machine.pyi index 2e82f5b..dc84b74 100644 --- a/lang/ja/typeshed/stdlib/machine.pyi +++ b/lang/ja/typeshed/stdlib/machine.pyi @@ -1,97 +1,84 @@ -"""Low-level utilities. -""" +"""低レベルユーティリティ""" from typing import Any from .microbit import MicroBitDigitalPin def unique_id() -> bytes: - """Get a byte string with a unique identifier of a board. + """ボードの一意の識別子を持つバイト列を取得します。 - Example: ``machine.unique_id()`` +Example: ``machine.unique_id()`` - :return: An identifier that varies from one board instance to another. - """ +:return: An identifier that varies from one board instance to another.""" ... def reset() -> None: - """Reset the device in a manner similar to pushing the external RESET button. + """外部のRESETボタンを押したと同様にデバイスをリセットします。 - Example: ``machine.reset()`` - """ +Example: ``machine.reset()``""" ... def freq() -> int: - """Get the CPU frequency in hertz. + """CPU周波数をヘルツ単位で取得します。 - Example: ``machine.freq()`` +Example: ``machine.freq()`` - :return: The CPU frequency. - """ +:return: The CPU frequency.""" ... def disable_irq() -> Any: - """Disable interrupt requests. + """割り込み要求を無効にします。 - Example: ``interrupt_state = machine.disable_irq()`` +Example: ``interrupt_state = machine.disable_irq()`` - :return: the previous IRQ state which should be considered an opaque value +:return: the previous IRQ state which should be considered an opaque value - The return value should be passed to the ``enable_irq`` function to restore - interrupts to their original state. - """ +The return value should be passed to the ``enable_irq`` function to restore +interrupts to their original state.""" ... def enable_irq(state: Any) -> None: - """Re-enable interrupt requests. + """割り込み要求を再度有効にします。 - Example: ``machine.enable_irq(interrupt_state)`` +Example: ``machine.enable_irq(interrupt_state)`` - :param state: The value that was returned from the most recent call to the ``disable_irq`` function. - """ +:param state: ``disable_irq`` 関数の最も最近の呼び出しから返された値。""" ... -def time_pulse_us( - pin: MicroBitDigitalPin, pulse_level: int, timeout_us: int = 1000000 -) -> int: - """Time a pulse on a pin. +def time_pulse_us(pin: MicroBitDigitalPin, pulse_level: int, timeout_us: int=1000000) -> int: + """端子のパルス時間を計測します。 - Example: ``time_pulse_us(pin0, 1)`` +Example: ``time_pulse_us(pin0, 1)`` - If the current input value of the pin is different to ``pulse_level``, the - function first waits until the pin input becomes equal to - ``pulse_level``, then times the duration that the pin is equal to - ``pulse_level``. If the pin is already equal to ``pulse_level`` then timing - starts straight away. +If the current input value of the pin is different to ``pulse_level``, the +function first waits until the pin input becomes equal to +``pulse_level``, then times the duration that the pin is equal to +``pulse_level``. If the pin is already equal to ``pulse_level`` then timing +starts straight away. - :param pin: The pin to use - :param pulse_level: 0 to time a low pulse or 1 to time a high pulse - :param timeout_us: A microsecond timeout - :return: The duration of the pulse in microseconds, or -1 for a timeout waiting for the level to match ``pulse_level``, or -2 on timeout waiting for the pulse to end - """ +:param pin: (ピン) 計測対象の端子 +:param pulse_level: 低パルスの時間計測で 0、高パルスの時間計測で 1 を指定 +:param timeout_us: マイクロ秒単位のタイムアウト時間 +:return: The duration of the pulse in microseconds, or -1 for a timeout waiting for the level to match ``pulse_level``, or -2 on timeout waiting for the pulse to end""" ... class mem: - """The class for the ``mem8``, ``mem16`` and ``mem32`` memory views.""" + """``mem8``、``mem16``、``mem32`` メモリビューのクラス。""" def __getitem__(self, address: int) -> int: - """Access a value from memory. + """メモリにある値を参照します。 - :param address: The memory address. - :return: The value at that address as an integer. - """ +:param address: メモリのアドレス。 +:return: The value at that address as an integer.""" ... + def __setitem__(self, address: int, value: int) -> None: - """Set a value at the given address. + """指定アドレスに値を設定します。 - :param address: The memory address. - :param value: The integer value to set. - """ +:param address: メモリのアドレス。 +:param value: 設定する整数値。""" ... - mem8: mem -"""8-bit (byte) view of memory.""" - +"""メモリの8ビット(バイト)ビュー。""" mem16: mem -"""16-bit view of memory.""" - +"""メモリの16ビットビュー。""" mem32: mem -"""32-bit view of memory.""" +"""メモリの32ビットビュー。""" \ No newline at end of file diff --git a/lang/ja/typeshed/stdlib/math.pyi b/lang/ja/typeshed/stdlib/math.pyi index f82d4de..7753a13 100644 --- a/lang/ja/typeshed/stdlib/math.pyi +++ b/lang/ja/typeshed/stdlib/math.pyi @@ -1,273 +1,246 @@ -"""Mathematical functions. -""" - +"""数学関数。""" from typing import Tuple def acos(x: float) -> float: - """Calculate the inverse cosine. + """逆余弦を算出します。 - Example: ``math.acos(1)`` +Example: ``math.acos(1)`` - :param x: A number - :return: The inverse cosine of ``x`` - """ +:param x: 数値 +:return: The inverse cosine of ``x``""" ... def asin(x: float) -> float: - """Calculate the inverse sine. + """逆正弦を算出します。 - Example: ``math.asin(0)`` +Example: ``math.asin(0)`` - :param x: A number - :return: The inverse sine of ``x`` - """ +:param x: 数値 +:return: The inverse sine of ``x``""" ... def atan(x: float) -> float: - """Calculate the inverse tangent. + """逆正接を算出します。 - Example: ``math.atan(0)`` +Example: ``math.atan(0)`` - :param x: A number - :return: The inverse tangent of ``x`` - """ +:param x: 数値 +:return: The inverse tangent of ``x``""" ... def atan2(y: float, x: float) -> float: - """Calculate the principal value of the inverse tangent of ``y/x``. + """``y/x`` の逆正接の主値を算出します。 - Example: ``math.atan2(0, -1)`` +Example: ``math.atan2(0, -1)`` - :param y: A number - :param x: A number - :return: The principal value of the inverse tangent of ``y/x`` - """ +:param y: 数値 +:param x: 数値 +:return: The principal value of the inverse tangent of ``y/x``""" ... def ceil(x: float) -> float: - """Round a number towards positive infinity. + """正の無限大方向に数値を丸めます。 - Example: ``math.ceil(0.1)`` +Example: ``math.ceil(0.1)`` - :param x: A number - :return: ``x`` rounded towards positive infinity. - """ +:param x: 数値 +:return: ``x`` rounded towards positive infinity.""" ... def copysign(x: float, y: float) -> float: - """Calculate ``x`` with the sign of ``y``. + """``y`` の符号で ``x`` を算出します。 - Example: ``math.copysign(1, -1)`` +Example: ``math.copysign(1, -1)`` - :param x: A number - :param y: The source of the sign for the return value - :return: ``x`` with the sign of ``y`` - """ +:param x: 数値 +:param y: 戻り値の符号の元になる値 +:return: ``x`` with the sign of ``y``""" ... def cos(x: float) -> float: - """Calculate the cosine of ``x``. + """``x`` の余弦を算出します。 - Example: ``math.cos(0)`` +Example: ``math.cos(0)`` - :param x: A number - :return: The cosine of ``x`` - """ +:param x: 数値 +:return: The cosine of ``x``""" ... def degrees(x: float) -> float: - """Convert radians to degrees. + """ラジアンを度に変換します。 (゜(度)) - Example: ``math.degrees(2 * math.pi)`` +Example: ``math.degrees(2 * math.pi)`` - :param x: A value in radians - :return: The value converted to degrees""" +:param x: ラジアン単位の値 +:return: The value converted to degrees""" ... def exp(x: float) -> float: - """Calculate the exponential of ``x``. + """``x`` の指数を算出します。 - Example: ``math.exp(1)`` +Example: ``math.exp(1)`` - :param x: A number - :return: The exponential of ``x``. - """ +:param x: 数値 +:return: The exponential of ``x``.""" ... def fabs(x: float) -> float: - """Return the absolute value of ``x``. + """``x`` の絶対値を返します。 - Example: ``math.fabs(-0.1)`` +Example: ``math.fabs(-0.1)`` - :param x: A number - :return: The absolute value of ``x`` - """ +:param x: 数値 +:return: The absolute value of ``x``""" ... def floor(x: float) -> int: - """Round a number towards negative infinity. + """負の無限大方向に数値を丸めます。 - Example: ``math.floor(0.9)`` +Example: ``math.floor(0.9)`` - :param x: A number - :return: ``x`` rounded towards negative infinity. - """ +:param x: 数値 +:return: ``x`` rounded towards negative infinity.""" ... def fmod(x: float, y: float) -> float: - """Calculate the remainder of ``x/y``. + """``x/y`` の剰余を算出します。 - Example: ``math.fmod(10, 3)`` +Example: ``math.fmod(10, 3)`` - :param x: The numerator - :param y: The denominator - """ +:param x: 分子の値 +:param y: 分母の値""" ... def frexp(x: float) -> Tuple[float, int]: - """Decomposes a floating-point number into its mantissa and exponent. + """浮動小数点数を仮数部と指数部に分解します。 - Example: ``mantissa, exponent = math.frexp(2)`` +Example: ``mantissa, exponent = math.frexp(2)`` - The returned value is the tuple ``(m, e)`` such that ``x == m * 2**e`` - exactly. If ``x == 0`` then the function returns ``(0.0, 0)``, otherwise - the relation ``0.5 <= abs(m) < 1`` holds. +The returned value is the tuple ``(m, e)`` such that ``x == m * 2**e`` +exactly. If ``x == 0`` then the function returns ``(0.0, 0)``, otherwise +the relation ``0.5 <= abs(m) < 1`` holds. - :param x: A floating-point number - :return: A tuple of length two containing its mantissa then exponent - """ +:param x: 浮動小数点数 +:return: A tuple of length two containing its mantissa then exponent""" ... def isfinite(x: float) -> bool: - """Check if a value is finite. + """有限数かどうかを確認します。 - Example: ``math.isfinite(float('inf'))`` +Example: ``math.isfinite(float('inf'))`` - :param x: A number. - :return: ``True`` if ``x`` is finite, ``False`` otherwise. - """ +:param x: 数値。 +:return: ``True`` if ``x`` is finite, ``False`` otherwise.""" ... def isinf(x: float) -> bool: - """Check if a value is infinite. + """無限数かどうかを確認します。 - Example: ``math.isinf(float('-inf'))`` +Example: ``math.isinf(float('-inf'))`` - :param x: A number. - :return: ``True`` if ``x`` is infinite, ``False`` otherwise. - """ +:param x: 数値。 +:return: ``True`` if ``x`` is infinite, ``False`` otherwise.""" ... def isnan(x: float) -> bool: - """Check if a value is not-a-number (NaN). + """非数(NaN: Not-a-Number)かどうかを確認します。 - Example: ``math.isnan(float('nan'))`` +Example: ``math.isnan(float('nan'))`` - :param x: A number - :return: ``True`` if ``x`` is not-a-number (NaN), ``False`` otherwise.""" +:param x: 数値 +:return: ``True`` if ``x`` is not-a-number (NaN), ``False`` otherwise.""" ... def ldexp(x: float, exp: int) -> float: - """Calculate ``x * (2**exp)``. + """``x * (2**exp)`` を算出します。 - Example: ``math.ldexp(0.5, 2)`` +Example: ``math.ldexp(0.5, 2)`` - :param x: A number - :param exp: Integer exponent - :return: ``x * (2**exp)`` - """ +:param x: 数値 +:param exp: 整数の指数 +:return: ``x * (2**exp)``""" ... -def log(x: float, base: float = e) -> float: - """Calculate the logarithm of ``x`` to the given base (defaults to natural logorithm). +def log(x: float, base: float=e) -> float: + """``x`` の対数を指定された底(デフォルトは自然対数)で算出します。 - Example: ``math.log(math.e)`` +Example: ``math.log(math.e)`` - With one argument, return the natural logarithm of x (to base e). +With one argument, return the natural logarithm of x (to base e). - With two arguments, return the logarithm of x to the given base, calculated as ``log(x)/log(base)``. +With two arguments, return the logarithm of x to the given base, calculated as ``log(x)/log(base)``. - :param x: A number - :param base: The base to use - :return: The natural logarithm of ``x`` - """ +:param x: 数値 +:param base: 使用する底 +:return: The natural logarithm of ``x``""" ... def modf(x: float) -> Tuple[float, float]: - """Calculate the fractional and integral parts of ``x``. + """``x`` の整数部分と小数部分を返します。 - Example: ``fractional, integral = math.modf(1.5)`` +Example: ``fractional, integral = math.modf(1.5)`` - :param x: A number - :return: A tuple of two floats representing the fractional then integral parts of ``x``. +:param x: 数値 +:return: A tuple of two floats representing the fractional then integral parts of ``x``. - Both the fractional and integral values have the same sign as ``x``. - """ +Both the fractional and integral values have the same sign as ``x``.""" ... def pow(x: float, y: float) -> float: - """Returns ``x`` to the power of ``y``. + """``x`` の ``y`` 乗を返します。 - Example: ``math.pow(4, 0.5)`` +Example: ``math.pow(4, 0.5)`` - :param x: A number - :param y: The exponent - :return: ``x`` to the power of ``y`` - """ +:param x: 数値 +:param y: 指数 +:return: ``x`` to the power of ``y``""" ... def radians(x: float) -> float: - """Convert a degrees to radians. + """度をラジアンに変換します。 - Example: ``math.radians(360)`` +Example: ``math.radians(360)`` - :param x: A value in degrees - :return: The value converted to radians - """ +:param x: 度単位の角度 +:return: The value converted to radians""" ... def sin(x: float) -> float: - """Calculate the sine of ``x``. + """``x`` の正弦を算出します。 - Example: ``math.sin(math.pi/2)`` +Example: ``math.sin(math.pi/2)`` - :param x: A number - :return: The sine of ``x`` - """ +:param x: 数値 +:return: The sine of ``x``""" ... def sqrt(x: float) -> float: - """Calculate the square root of ``x``. + """``x`` の平方根を算出します。 - Example: ``math.sqrt(4)`` +Example: ``math.sqrt(4)`` - :param x: A number - :return: The square root of ``x`` - """ +:param x: 数値 +:return: The square root of ``x``""" ... def tan(x: float) -> float: - """Calculate the tangent of ``x``. + """``x`` の正接を算出します。 - Example: ``math.tan(0)`` +Example: ``math.tan(0)`` - :param x: A number - :return: The tangent of ``x``. - """ +:param x: 数値 +:return: The tangent of ``x``.""" ... def trunc(x: float) -> int: - """Round a number towards 0. + """0 方向に数値を丸めます。 - Example: ``math.trunc(-0.9)`` +Example: ``math.trunc(-0.9)`` - :param x: A number - :return: ``x`` rounded towards zero. - """ +:param x: 数値 +:return: ``x`` rounded towards zero.""" ... - e: float -"""Base of the natural logarithm""" - +"""自然対数の底""" pi: float -"""The ratio of a circle's circumference to its diameter""" +"""円の円周と直径の比""" \ No newline at end of file diff --git a/lang/ja/typeshed/stdlib/microbit/__init__.pyi b/lang/ja/typeshed/stdlib/microbit/__init__.pyi index f12158f..06c42bb 100644 --- a/lang/ja/typeshed/stdlib/microbit/__init__.pyi +++ b/lang/ja/typeshed/stdlib/microbit/__init__.pyi @@ -1,11 +1,6 @@ -"""Pins, images, sounds, temperature and volume. -""" - +"""端子、イメージ、サウンド、温度と音量。""" from typing import Any, Callable, List, Optional, Tuple, Union, overload - from _typeshed import ReadableBuffer - -# V2 only from . import accelerometer as accelerometer from . import audio as audio from . import compass as compass @@ -16,831 +11,696 @@ from . import speaker as speaker from . import spi as spi from . import uart as uart -def run_every( - callback: Optional[Callable[[], None]] = None, - days: int = 0, - h: int = 0, - min: int = 0, - s: int = 0, - ms: int = 0, -) -> Callable[[Callable[[], None]], Callable[[], None]]: - """Schedule to run a function at the interval specified by the time arguments **V2 only**. +def run_every(callback: Optional[Callable[[], None]]=None, days: int=0, h: int=0, min: int=0, s: int=0, ms: int=0) -> Callable[[Callable[[], None]], Callable[[], None]]: + """time 引数で指定した間隔で関数を実行するようスケジュールします。 **V2** のみで使えます。 - Example: ``run_every(my_logging, min=5)`` +Example: ``run_every(my_logging, min=5)`` - ``run_every`` can be used in two ways: +``run_every`` can be used in two ways: - As a Decorator - placed on top of the function to schedule. For example:: +As a Decorator - placed on top of the function to schedule. For example:: - @run_every(h=1, min=20, s=30, ms=50) - def my_function(): - # Do something here + @run_every(h=1, min=20, s=30, ms=50) + def my_function(): + # Do something here - As a Function - passing the callback as a positional argument. For example:: +As a Function - passing the callback as a positional argument. For example:: - def my_function(): - # Do something here - run_every(my_function, s=30) + def my_function(): + # Do something here + run_every(my_function, s=30) - Each argument corresponds to a different time unit and they are additive. - So ``run_every(min=1, s=30)`` schedules the callback every minute and a half. +Each argument corresponds to a different time unit and they are additive. +So ``run_every(min=1, s=30)`` schedules the callback every minute and a half. - When an exception is thrown inside the callback function it deschedules the - function. To avoid this you can catch exceptions with ``try/except``. +When an exception is thrown inside the callback function it deschedules the +function. To avoid this you can catch exceptions with ``try/except``. - :param callback: Function to call at the provided interval. Omit when using as a decorator. - :param days: Sets the day mark for the scheduling. - :param h: Sets the hour mark for the scheduling. - :param min: Sets the minute mark for the scheduling. - :param s: Sets the second mark for the scheduling. - :param ms: Sets the millisecond mark for the scheduling. - """ +:param callback: 指定した間隔で呼び出す関数。デコレータとして使う場合は省略してください。 +:param days: スケジューリングのための日数を設定します。 +:param h: スケジューリングのための時間を設定します。 +:param min: スケジューリングのための分を設定します。 +:param s: スケジューリングのための秒を設定します。 +:param ms: スケジューリングのためのミリ秒を設定します。""" def panic(n: int) -> None: - """Enter a panic mode. + """パニックモードに入ります。 - Example: ``panic(127)`` +Example: ``panic(127)`` - :param n: An arbitrary integer <= 255 to indicate a status. +:param n: 状態を示す 255 以下の任意の整数。 - Requires restart. - """ +Requires restart.""" def reset() -> None: - """Restart the board.""" - + """ボードを再起動します。""" @overload def scale(value: float, from_: Tuple[float, float], to: Tuple[int, int]) -> int: - """Converts a value from a range to an integer range. + """ある整数区間から別の整数区間に値を変換します。 - Example: ``volume = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255))`` +Example: ``volume = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255))`` - For example, to convert an accelerometer X value to a speaker volume. +For example, to convert an accelerometer X value to a speaker volume. - If one of the numbers in the ``to`` parameter is a floating point - (i.e a decimal number like ``10.0``), this function will return a - floating point number. +If one of the numbers in the ``to`` parameter is a floating point +(i.e a decimal number like ``10.0``), this function will return a +floating point number. - temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0)) + temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0)) - :param value: A number to convert. - :param from_: A tuple to define the range to convert from. - :param to: A tuple to define the range to convert to. - :return: The ``value`` converted to the ``to`` range. - """ +:param value: 変換する数値。 +:param from_: 変換元の区間を定義するためのタプル。 +:param to: 変換先の区間を定義するためのタプル。 +:return: The ``value`` converted to the ``to`` range.""" @overload def scale(value: float, from_: Tuple[float, float], to: Tuple[float, float]) -> float: - """Converts a value from a range to a floating point range. + """ある浮動小数点数区間から別の浮動小数点数区間に値を変換します。 - Example: ``temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0))`` +Example: ``temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0))`` - For example, to convert temperature from a Celsius scale to Fahrenheit. +For example, to convert temperature from a Celsius scale to Fahrenheit. - If one of the numbers in the ``to`` parameter is a floating point - (i.e a decimal number like ``10.0``), this function will return a - floating point number. - If they are both integers (i.e ``10``), it will return an integer:: +If one of the numbers in the ``to`` parameter is a floating point +(i.e a decimal number like ``10.0``), this function will return a +floating point number. +If they are both integers (i.e ``10``), it will return an integer:: - returns_int = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255)) + returns_int = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255)) - :param value: A number to convert. - :param from_: A tuple to define the range to convert from. - :param to: A tuple to define the range to convert to. - :return: The ``value`` converted to the ``to`` range. - """ +:param value: 変換する数値。 +:param from_: 変換元の区間を定義するためのタプル。 +:param to: 変換先の区間を定義するためのタプル。 +:return: The ``value`` converted to the ``to`` range.""" def sleep(n: float) -> None: - """Wait for ``n`` milliseconds. + """``n`` ミリ秒待機します。 - Example: ``sleep(1000)`` +Example: ``sleep(1000)`` - :param n: The number of milliseconds to wait +:param n: ミリ秒単位の待機時間 - One second is 1000 milliseconds, so:: +One second is 1000 milliseconds, so:: - microbit.sleep(1000) + microbit.sleep(1000) - will pause the execution for one second. - """ +will pause the execution for one second.""" def running_time() -> int: - """Get the running time of the board. + """ボードの実行時間を取得します。 - :return: The number of milliseconds since the board was switched on or restarted. - """ +:return: The number of milliseconds since the board was switched on or restarted.""" def temperature() -> int: - """Get the temperature of the micro:bit in degrees Celsius.""" + """micro:bitの温度を摂氏で取得します。 (温度)""" def set_volume(v: int) -> None: - """Sets the volume. + """音量を設定します。 - Example: ``set_volume(127)`` +Example: ``set_volume(127)`` - :param v: a value between 0 (low) and 255 (high). +:param v: 0(下限)から 255(上限)までの間の値。 - Out of range values will be clamped to 0 or 255. +Out of range values will be clamped to 0 or 255. - **V2** only. - """ +**V2** only.""" ... class Button: - """The class for the buttons ``button_a`` and ``button_b``.""" + """ボタン ``button_a`` と ``button_b`` のクラス。""" def is_pressed(self) -> bool: - """Check if the button is pressed. + """ボタンが押されているかどうかを確認します。 - :return: ``True`` if the specified button ``button`` is pressed, and ``False`` otherwise. - """ +:return: ``True`` if the specified button ``button`` is pressed, and ``False`` otherwise.""" ... + def was_pressed(self) -> bool: - """Check if the button was pressed since the device started or the last time this method was called. + """デバイスが起動されてから、もしくは前回このメソッドが呼び出されてからボタンが押されたかどうかを確認します。 - Calling this method will clear the press state so - that the button must be pressed again before this method will return - ``True`` again. +Calling this method will clear the press state so +that the button must be pressed again before this method will return +``True`` again. - :return: ``True`` if the specified button ``button`` was pressed, and ``False`` otherwise - """ +:return: ``True`` if the specified button ``button`` was pressed, and ``False`` otherwise""" ... + def get_presses(self) -> int: - """Get the running total of button presses, and resets this total - to zero before returning. + """ボタンを押した回数の合計を取得し、返す前に回数をゼロにリセットします。 - :return: The number of presses since the device started or the last time this method was called - """ +:return: The number of presses since the device started or the last time this method was called""" ... - button_a: Button -"""The left button ``Button`` object.""" - +"""左のボタン ``Button`` オブジェクト。""" button_b: Button -"""The right button ``Button`` object.""" +"""右のボタン ``Button`` オブジェクト。""" class MicroBitDigitalPin: - """A digital pin. - - Some pins support analog and touch features using the ``MicroBitAnalogDigitalPin`` and ``MicroBitTouchPin`` subclasses. - """ + """デジタル端子。 +Some pins support analog and touch features using the ``MicroBitAnalogDigitalPin`` and ``MicroBitTouchPin`` subclasses.""" NO_PULL: int PULL_UP: int PULL_DOWN: int + def read_digital(self) -> int: - """Get the digital value of the pin. + """端子のデジタル値を取得します。 - Example: ``value = pin0.read_digital()`` +Example: ``value = pin0.read_digital()`` - :return: 1 if the pin is high, and 0 if it's low. - """ +:return: 1 if the pin is high, and 0 if it's low.""" ... + def write_digital(self, value: int) -> None: - """Set the digital value of the pin. + """端子のデジタル値を設定します。 - Example: ``pin0.write_digital(1)`` +Example: ``pin0.write_digital(1)`` - :param value: 1 to set the pin high or 0 to set the pin low""" +:param value: 端子をハイにするには 1 、ローにするには 0 を指定""" ... + def set_pull(self, value: int) -> None: - """Set the pull state to one of three possible values: ``PULL_UP``, ``PULL_DOWN`` or ``NO_PULL``. + """プル状態を ``PULL_UP``、``PULL_DOWN``、``NO_PULL`` の3つの値のいずれかに設定します。 - Example: ``pin0.set_pull(pin0.PULL_UP)`` +Example: ``pin0.set_pull(pin0.PULL_UP)`` - :param value: The pull state from the relevant pin, e.g. ``pin0.PULL_UP``. - """ +:param value: ``pin0.PULL_UP`` などの関連する端子のプル状態。""" ... + def get_pull(self) -> int: - """Get the pull state on a pin. + """端子のプル状態を取得します。 - Example: ``pin0.get_pull()`` +Example: ``pin0.get_pull()`` - :return: ``NO_PULL``, ``PULL_DOWN``, or ``PULL_UP`` +:return: ``NO_PULL``, ``PULL_DOWN``, or ``PULL_UP`` - These are set using the ``set_pull()`` method or automatically configured - when a pin mode requires it. - """ +These are set using the ``set_pull()`` method or automatically configured +when a pin mode requires it.""" ... + def get_mode(self) -> str: - """Returns the pin mode. + """端子のモードを返します。 - Example: ``pin0.get_mode()`` +Example: ``pin0.get_mode()`` - When a pin is used for a specific function, like - writing a digital value, or reading an analog value, the pin mode - changes. +When a pin is used for a specific function, like +writing a digital value, or reading an analog value, the pin mode +changes. - :return: ``"unused"``, ``"analog"``, ``"read_digital"``, ``"write_digital"``, ``"display"``, ``"button"``, ``"music"``, ``"audio"``, ``"touch"``, ``"i2c"``, or ``"spi"`` - """ +:return: ``"unused"``, ``"analog"``, ``"read_digital"``, ``"write_digital"``, ``"display"``, ``"button"``, ``"music"``, ``"audio"``, ``"touch"``, ``"i2c"``, or ``"spi"``""" ... + def write_analog(self, value: int) -> None: - """Output a PWM signal on the pin, with the duty cycle proportional to ``value``. + """PWM 信号を端子に出力します。時間幅周期は ``value`` に比例します。 + +Example: ``pin0.write_analog(254)`` - Example: ``pin0.write_analog(254)`` +:param value: 0(時間幅周期 0%)から 1023(時間幅周期 100%)までの整数または浮動小数点数。""" - :param value: 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. + """出力されるPWM信号の周期を ``period`` にミリ秒単位で設定します。 - Example: ``pin0.set_analog_period(10)`` +Example: ``pin0.set_analog_period(10)`` + +:param period: 周期をミリ秒単位で指定。有効な最小値は1ms。""" - :param period: The period in milliseconds with a minimum valid value of 1ms. - """ def set_analog_period_microseconds(self, period: int) -> None: - """Set the period of the PWM signal being output to ``period`` in microseconds. + """出力されるPWM信号の周期を ``period`` にマイクロ秒単位で設定します。 - Example: ``pin0.set_analog_period_microseconds(512)`` +Example: ``pin0.set_analog_period_microseconds(512)`` - :param period: The period in microseconds with a minimum valid value of 256µs. - """ +:param period: 周期をマイクロ秒単位で指定。有効な最小値は256µs。""" class MicroBitAnalogDigitalPin(MicroBitDigitalPin): - """A pin with analog and digital features.""" + """アナログとデジタル機能を備えた端子。""" def read_analog(self) -> int: - """Read the voltage applied to the pin. + """端子にかかっている電圧を読み取ります。 - Example: ``pin0.read_analog()`` +Example: ``pin0.read_analog()`` - :return: An integer between 0 (meaning 0V) and 1023 (meaning 3.3V). - """ +:return: An integer between 0 (meaning 0V) and 1023 (meaning 3.3V).""" class MicroBitTouchPin(MicroBitAnalogDigitalPin): - """A pin with analog, digital and touch features.""" - + """アナログ、デジタル、タッチ機能を備えた端子。""" CAPACITIVE: int RESISTIVE: int + def is_touched(self) -> bool: - """Check if the pin is being touched. + """端子にタッチしているかどうかを確認します。 - Example: ``pin0.is_touched()`` +Example: ``pin0.is_touched()`` - The default touch mode for the pins on the edge connector is ``resistive``. - The default for the logo pin **V2** is ``capacitive``. +The default touch mode for the pins on the edge connector is ``resistive``. +The default for the logo pin **V2** is ``capacitive``. - **Resistive touch** - This test is done by measuring how much resistance there is between the - pin and ground. A low resistance gives a reading of ``True``. To get - a reliable reading using a finger you may need to touch the ground pin - with another part of your body, for example your other hand. +**Resistive touch** +This test is done by measuring how much resistance there is between the +pin and ground. A low resistance gives a reading of ``True``. To get +a reliable reading using a finger you may need to touch the ground pin +with another part of your body, for example your other hand. - **Capacitive touch** - This test is done by interacting with the electric field of a capacitor - using a finger as a conductor. `Capacitive touch - `_ - does not require you to make a ground connection as part of a circuit. +**Capacitive touch** +This test is done by interacting with the electric field of a capacitor +using a finger as a conductor. `Capacitive touch +`_ +does not require you to make a ground connection as part of a circuit. - :return: ``True`` if the pin is being touched with a finger, otherwise return ``False``. - """ +:return: ``True`` if the pin is being touched with a finger, otherwise return ``False``.""" ... + def set_touch_mode(self, value: int) -> None: - """Set the touch mode for the pin. + """端子のタッチモードを設定します。 - Example: ``pin0.set_touch_mode(pin0.CAPACITIVE)`` +Example: ``pin0.set_touch_mode(pin0.CAPACITIVE)`` - The default touch mode for the pins on the edge connector is - ``resistive``. The default for the logo pin **V2** is ``capacitive``. +The default touch mode for the pins on the edge connector is +``resistive``. The default for the logo pin **V2** is ``capacitive``. - :param value: ``CAPACITIVE`` or ``RESISTIVE`` from the relevant pin. - """ +:param value: 関連する端子の ``CAPACITIVE`` または ``RESISTIVE``。""" ... - pin0: MicroBitTouchPin -"""Pin with digital, analog and touch features.""" - +"""デジタル、アナログ、タッチ機能を備えた端子。""" pin1: MicroBitTouchPin -"""Pin with digital, analog and touch features.""" - +"""デジタル、アナログ、タッチ機能を備えた端子。""" pin2: MicroBitTouchPin -"""Pin with digital, analog and touch features.""" - +"""デジタル、アナログ、タッチ機能を備えた端子。""" pin3: MicroBitAnalogDigitalPin -"""Pin with digital and analog features.""" - +"""デジタルとアナログ機能を備えた端子。""" pin4: MicroBitAnalogDigitalPin -"""Pin with digital and analog features.""" - +"""デジタルとアナログ機能を備えた端子。""" pin5: MicroBitDigitalPin -"""Pin with digital features.""" - +"""デジタル機能を備えた端子。""" pin6: MicroBitDigitalPin -"""Pin with digital features.""" - +"""デジタル機能を備えた端子。""" pin7: MicroBitDigitalPin -"""Pin with digital features.""" - +"""デジタル機能を備えた端子。""" pin8: MicroBitDigitalPin -"""Pin with digital features.""" - +"""デジタル機能を備えた端子。""" pin9: MicroBitDigitalPin -"""Pin with digital features.""" - +"""デジタル機能を備えた端子。""" pin10: MicroBitAnalogDigitalPin -"""Pin with digital and analog features.""" - +"""デジタルとアナログ機能を備えた端子。""" pin11: MicroBitDigitalPin -"""Pin with digital features.""" - +"""デジタル機能を備えた端子。""" pin12: MicroBitDigitalPin -"""Pin with digital features.""" - +"""デジタル機能を備えた端子。""" pin13: MicroBitDigitalPin -"""Pin with digital features.""" - +"""デジタル機能を備えた端子。""" pin14: MicroBitDigitalPin -"""Pin with digital features.""" - +"""デジタル機能を備えた端子。""" pin15: MicroBitDigitalPin -"""Pin with digital features.""" - +"""デジタル機能を備えた端子。""" pin16: MicroBitDigitalPin -"""Pin with digital features.""" - +"""デジタル機能を備えた端子。""" pin19: MicroBitDigitalPin -"""Pin with digital features.""" - +"""デジタル機能を備えた端子。""" pin20: MicroBitDigitalPin -"""Pin with digital features.""" - +"""デジタル機能を備えた端子。""" pin_logo: MicroBitTouchPin -"""A touch sensitive logo pin on the front of the micro:bit, which by default is set to capacitive touch mode.""" - +"""micro:bitの前面にあるタッチセンサー機能のあるロゴの端子です。デフォルトでは静電容量方式タッチモードになっています。""" pin_speaker: MicroBitAnalogDigitalPin -"""A pin to address the micro:bit speaker. +"""micro:bitスピーカーをアドレスするための端子。 This API is intended only for use in Pulse-Width Modulation pin operations e.g. pin_speaker.write_analog(128). """ class Image: - """An image to show on the micro:bit LED display. + """micro:bitのLEDディスプレイに表示するイメージ。 - Given an image object it's possible to display it via the ``display`` API:: - - display.show(Image.HAPPY) - """ +Given an image object it's possible to display it via the ``display`` API:: + display.show(Image.HAPPY)""" HEART: Image - """Heart image.""" - + """「ハート」イメージ。""" HEART_SMALL: Image - """Small heart image.""" - + """「小さいハート」イメージ。""" HAPPY: Image - """Happy face image.""" - + """「うれしい顔」イメージ。""" SMILE: Image - """Smiling mouth image.""" - + """「笑顔」イメージ。""" SAD: Image - """Sad face image.""" - + """「かなしい顔」イメージ。""" CONFUSED: Image - """Confused face image.""" - + """「こまり顔」イメージ。""" ANGRY: Image - """Angry face image.""" - + """「おこり顔」イメージ。""" ASLEEP: Image - """Sleeping face image.""" - + """「ねてる顔」イメージ。""" SURPRISED: Image - """Surprised face image.""" - + """「びっくり顔」イメージ。""" SILLY: Image - """Silly face image.""" - + """「へん顔」イメージ。""" FABULOUS: Image - """Sunglasses face image.""" - + """「サングラスの笑顔」イメージ。""" MEH: Image - """Unimpressed face image.""" - + """「ふーん」イメージ""" YES: Image - """Tick image.""" - + """「チェック」イメージ。""" NO: Image - """Cross image.""" - + """「バツ」イメージ。""" CLOCK12: Image - """Image with line pointing to 12 o'clock.""" - + """「12時を指す線」イメージ。""" CLOCK11: Image - """Image with line pointing to 11 o'clock.""" - + """「11時を指す線」イメージ。""" CLOCK10: Image - """Image with line pointing to 10 o'clock.""" - + """「10時を指す線」イメージ。""" CLOCK9: Image - """Image with line pointing to 9 o'clock.""" - + """「9時を指す線」イメージ。""" CLOCK8: Image - """Image with line pointing to 8 o'clock.""" - + """「8時を指す線」イメージ。""" CLOCK7: Image - """Image with line pointing to 7 o'clock.""" - + """「7時を指す線」イメージ。""" CLOCK6: Image - """Image with line pointing to 6 o'clock.""" - + """「6時を指す線」イメージ。""" CLOCK5: Image - """Image with line pointing to 5 o'clock.""" - + """「5時を指す線」イメージ。""" CLOCK4: Image - """Image with line pointing to 4 o'clock.""" - + """「4時を指す線」イメージ。""" CLOCK3: Image - """Image with line pointing to 3 o'clock.""" - + """「3時を指す線」イメージ。""" CLOCK2: Image - """Image with line pointing to 2 o'clock.""" - + """「2時を指す線」イメージ。""" CLOCK1: Image - """Image with line pointing to 1 o'clock.""" - + """「1時を指す線」イメージ。""" ARROW_N: Image - """Image of arrow pointing north.""" - + """「北を指す矢印」イメージ。""" ARROW_NE: Image - """Image of arrow pointing north east.""" - + """「北東を指す矢印」イメージ。""" ARROW_E: Image - """Image of arrow pointing east.""" - + """「西を指す矢印」イメージ。""" ARROW_SE: Image - """Image of arrow pointing south east.""" - + """「南東を指す矢印」イメージ。""" ARROW_S: Image - """Image of arrow pointing south.""" - + """「南を指す矢印」イメージ。""" ARROW_SW: Image - """Image of arrow pointing south west.""" - + """「南西を指す矢印」イメージ。""" ARROW_W: Image - """Image of arrow pointing west.""" - + """「西を指す矢印」イメージ。""" ARROW_NW: Image - """Image of arrow pointing north west.""" - + """「北西を指す矢印」イメージ。""" TRIANGLE: Image - """Image of a triangle pointing up.""" - + """「上向きの三角形」イメージ""" TRIANGLE_LEFT: Image - """Image of a triangle in the left corner.""" - + """「左向き三角」イメージ。""" CHESSBOARD: Image - """Alternate LEDs lit in a chessboard pattern.""" - + """チェス盤パターンで交互に点灯するLED。""" DIAMOND: Image - """Diamond image.""" - + """「ダイヤモンド」イメージ。""" DIAMOND_SMALL: Image - """Small diamond image.""" - + """「小さいダイヤモンド」イメージ。""" SQUARE: Image - """Square image.""" - + """「四角」イメージ。""" SQUARE_SMALL: Image - """Small square image.""" - + """「小さい四角」イメージ。""" RABBIT: Image - """Rabbit image.""" - + """「うさぎ」イメージ。""" COW: Image - """Cow image.""" - + """「うし」イメージ。""" MUSIC_CROTCHET: Image - """Crotchet note image.""" - + """「4分音符」イメージ。""" MUSIC_QUAVER: Image - """Quaver note image.""" - + """「8分音符」イメージ。""" MUSIC_QUAVERS: Image - """Pair of quavers note image.""" - + """「連結した8分音符」イメージ。""" PITCHFORK: Image - """Pitchfork image.""" - + """「くまで」イメージ。""" XMAS: Image - """Christmas tree image.""" - + """「クリスマスツリー」イメージ。""" PACMAN: Image - """Pac-Man arcade character image.""" - + """「パックマン」イメージ。""" TARGET: Image - """Target image.""" - + """「まと」イメージ。""" TSHIRT: Image - """T-shirt image.""" - + """「Tシャツ」イメージ。""" ROLLERSKATE: Image - """Rollerskate image.""" - + """「ローラースケート」イメージ。""" DUCK: Image - """Duck image.""" - + """「あひる」イメージ。""" HOUSE: Image - """House image.""" - + """「家」イメージ。""" TORTOISE: Image - """Tortoise image.""" - + """「かめ」イメージ。""" BUTTERFLY: Image - """Butterfly image.""" - + """「ちょうちょ」イメージ。""" STICKFIGURE: Image - """Stick figure image.""" - + """「棒人間」イメージ。""" GHOST: Image - """Ghost image.""" - + """「おばけ」イメージ。""" SWORD: Image - """Sword image.""" - + """「剣」イメージ。""" GIRAFFE: Image - """Giraffe image.""" - + """「きりん」イメージ。""" SKULL: Image - """Skull image.""" - + """「がいこつ」イメージ。""" UMBRELLA: Image - """Umbrella image.""" - + """「かさ」イメージ。""" SNAKE: Image - """Snake image.""" - + """「へび」イメージ。""" SCISSORS: Image - """Scissors image.""" - + """「はさみ」イメージ。""" ALL_CLOCKS: List[Image] - """A list containing all the CLOCK_ images in sequence.""" - + """すべての時計イメージを順番に並べたリスト。""" ALL_ARROWS: List[Image] - """A list containing all the ARROW_ images in sequence.""" + """すべての矢印イメージを順番に並べたリスト。""" + @overload def __init__(self, string: str) -> None: - """Create an image from a string describing which LEDs are lit. + """LEDの点灯パターンを示す文字列からイメージを作成します。 - ``string`` has to consist of digits 0-9 arranged into lines, - describing the image, for example:: +``string`` has to consist of digits 0-9 arranged into lines, +describing the image, for example:: - image = Image("90009:" - "09090:" - "00900:" - "09090:" - "90009") + 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 newlines (\\n) insead of the colons. +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 newlines (\\n) insead of the colons. - :param string: The string describing the image. - """ +:param string: イメージについて記述する文字列。""" ... + @overload - def __init__( - self, width: int = 5, height: int = 5, buffer: ReadableBuffer = None - ) -> None: - """Create an empty image with ``width`` columns and ``height`` rows. + def __init__(self, width: int=5, height: int=5, buffer: ReadableBuffer=None) -> None: + """``width`` 列と ``height`` 行からなる空のイメージを作成します。 - :param width: Optional width of the image - :param height: Optional height of the image - :param buffer: Optional array or bytes of ``width``×``height`` integers in range 0-9 to initialize the image +:param width: イメージの幅を指定するオプション +:param height: イメージの高さを指定するオプション +:param buffer: イメージを初期化するために、整数値(0~9)を ``width``×``height`` 個並べた配列またはバイト列を指定します - Examples:: +Examples:: - Image(2, 2, b'\x08\x08\x08\x08') - Image(2, 2, bytearray([9,9,9,9])) + Image(2, 2, b'\x08\x08\x08\x08') + Image(2, 2, bytearray([9,9,9,9])) - These create 2 x 2 pixel images at full brightness. - """ +These create 2 x 2 pixel images at full brightness.""" ... + def width(self) -> int: - """Get the number of columns. + """列数を取得します。 - :return: The number of columns in the image - """ +:return: The number of columns in the image""" ... + def height(self) -> int: - """Get the number of rows. + """行数を取得します。 - :return: The number of rows in the image - """ +:return: The number of rows in the image""" ... + def set_pixel(self, x: int, y: int, value: int) -> None: - """Set the brightness of a pixel. + """1ピクセルの明るさを設定します。 - Example: ``my_image.set_pixel(0, 0, 9)`` +Example: ``my_image.set_pixel(0, 0, 9)`` - :param x: The column number - :param y: The row number - :param value: The brightness as an integer between 0 (dark) and 9 (bright) +:param x: 列数 +:param y: 行数 +:param value: 明るさを 0(暗い)から 9(明るい)までの整数値で指定します - This method will raise an exception when called on any of the built-in - read-only images, like ``Image.HEART``. - """ +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: - """Get the brightness of a pixel. + """1ピクセルの明るさを取得します。 - Example: ``my_image.get_pixel(0, 0)`` +Example: ``my_image.get_pixel(0, 0)`` - :param x: The column number - :param y: The row number - :return: The brightness as an integer between 0 and 9. - """ +:param x: 列数 +:param y: 行数 +:return: The brightness as an integer between 0 and 9.""" ... + def shift_left(self, n: int) -> Image: - """Create a new image by shifting the picture left. + """画像を左にシフトした新しいイメージを作成します。 - Example: ``Image.HEART_SMALL.shift_left(1)`` +Example: ``Image.HEART_SMALL.shift_left(1)`` - :param n: The number of columns to shift by - :return: The shifted image - """ +:param n: シフトする列数 +:return: The shifted image""" ... + def shift_right(self, n: int) -> Image: - """Create a new image by shifting the picture right. + """画像を右にシフトした新しいイメージを作成します。 - Example: ``Image.HEART_SMALL.shift_right(1)`` +Example: ``Image.HEART_SMALL.shift_right(1)`` - :param n: The number of columns to shift by - :return: The shifted image - """ +:param n: シフトする列数 +:return: The shifted image""" ... + def shift_up(self, n: int) -> Image: - """Create a new image by shifting the picture up. + """画像を上にシフトした新しいイメージを作成します。 - Example: ``Image.HEART_SMALL.shift_up(1)`` +Example: ``Image.HEART_SMALL.shift_up(1)`` - :param n: The number of rows to shift by - :return: The shifted image - """ +:param n: シフトする行数 +:return: The shifted image""" ... + def shift_down(self, n: int) -> Image: - """Create a new image by shifting the picture down. + """画像を下にシフトした新しいイメージを作成します。 - Example: ``Image.HEART_SMALL.shift_down(1)`` +Example: ``Image.HEART_SMALL.shift_down(1)`` - :param n: The number of rows to shift by - :return: The shifted image - """ +:param n: シフトする行数 +:return: The shifted image""" ... + def crop(self, x: int, y: int, w: int, h: int) -> Image: - """Create a new image by cropping the picture. + """画像をトリミングした新しいイメージを作成します。 - Example: ``Image.HEART.crop(1, 1, 3, 3)`` +Example: ``Image.HEART.crop(1, 1, 3, 3)`` - :param x: The crop offset column - :param y: The crop offset row - :param w: The crop width - :param h: The crop height - :return: The new image - """ +:param x: トリミングするオフセット列 +:param y: トリミングするオフセット行 +:param w: トリミングする幅 +:param h: トリミングする高さ +:return: The new image""" ... + def copy(self) -> Image: - """Create an exact copy of the image. + """イメージ全体のコピーを作成します。 - Example: ``Image.HEART.copy()`` +Example: ``Image.HEART.copy()`` - :return: The new image - """ +:return: The new image""" ... + def invert(self) -> Image: - """Create a new image by inverting the brightness of the pixels in the - source image. + """元イメージのピクセルの明るさを反転した新しいイメージ作成します。 - Example: ``Image.SMALL_HEART.invert()`` +Example: ``Image.SMALL_HEART.invert()`` - :return: The new image. - """ +:return: The new image.""" ... + def fill(self, value: int) -> None: - """Set the brightness of all the pixels in the image. + """イメージのすべてのピクセルの明るさを設定します。 - Example: ``my_image.fill(5)`` +Example: ``my_image.fill(5)`` - :param value: The new brightness as a number between 0 (dark) and 9 (bright). +:param value: 0(暗い)から 9(明るい)までの数値で新しい明るさを指定します。 - This method will raise an exception when called on any of the built-in - read-only images, like ``Image.HEART``. - """ +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 an area from another image into this image. - - Example: ``my_image.blit(Image.HEART, 1, 1, 3, 3, 1, 1)`` - - :param src: The source image - :param x: The starting column offset in the source image - :param y: The starting row offset in the source image - :param w: The number of columns to copy - :param h: The number of rows to copy - :param xdest: The column offset to modify in this image - :param ydest: The row offset to modify in this image - - Pixels outside the source image are treated as having a brightness 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 blit(self, src: Image, x: int, y: int, w: int, h: int, xdest: int=0, ydest: int=0) -> None: + """このイメージに別のイメージから領域をコピーします。 + +Example: ``my_image.blit(Image.HEART, 1, 1, 3, 3, 1, 1)`` + +:param src: 元イメージ +:param x: 元イメージの開始列オフセット +:param y: 元イメージの開始行オフセット +:param w: コピーする列数 +:param h: コピーする行数 +:param xdest: このイメージで変更する列オフセット +:param ydest: このイメージで変更する行オフセット + +Pixels outside the source image are treated as having a brightness 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. + """2つのイメージの各ピクセルの明るさを足した新しいイメージを作成します。 - Example: ``Image.HEART + Image.HAPPY`` +Example: ``Image.HEART + Image.HAPPY`` - :param other: The image to add. - """ +:param other: 加算するイメージ。""" ... + def __sub__(self, other: Image) -> Image: - """Create a new image by subtracting the brightness values of the - other image from this image. + """このイメージから他のイメージの明るさの値を引いた新しいイメージを作成します。 - Example: ``Image.HEART - Image.HEART_SMALL`` +Example: ``Image.HEART - Image.HEART_SMALL`` - :param other: The image to subtract. - """ +:param other: 減算するイメージ。""" ... + def __mul__(self, n: float) -> Image: - """Create a new image by multiplying the brightness of each pixel by - ``n``. + """各ピクセルの明るさを ``n`` 倍した新しいイメージを作成します。 - Example: ``Image.HEART * 0.5`` +Example: ``Image.HEART * 0.5`` - :param n: The value to multiply by. - """ +:param n: 乗算する値。""" ... + def __truediv__(self, n: float) -> Image: - """Create a new image by dividing the brightness of each pixel by - ``n``. + """各ピクセルの明るさを ``n`` で割った新しいイメージを作成します。 - Example: ``Image.HEART / 2`` +Example: ``Image.HEART / 2`` - :param n: The value to divide by. - """ +:param n: 除算する値。""" ... class SoundEvent: LOUD: SoundEvent - """Represents the transition of sound events, from ``quiet`` to ``loud`` like clapping or shouting.""" - + """拍手や叫び声などで ``quiet`` から ``loud`` へのサウンドイベントの変化を表します。""" QUIET: SoundEvent - """Represents the transition of sound events, from ``loud`` to ``quiet`` like speaking or background music.""" + """発話やBGMなどで ``loud`` から ``quiet`` へのサウンドイベントの変化を表します。""" class Sound: - """The built-in sounds can be called using ``audio.play(Sound.NAME)``.""" - + """内蔵のサウンドは ``audio.play(Sound.NAME)`` で呼び出すことができます。""" GIGGLE: Sound - """Giggling sound.""" - + """「くすくす笑う」サウンド。""" HAPPY: Sound - """Happy sound.""" - + """「ハッピー」サウンド。""" HELLO: Sound - """Greeting sound.""" - + """「ハロー」サウンド""" MYSTERIOUS: Sound - """Mysterious sound.""" - + """「ミステリアス」サウンド。""" SAD: Sound - """Sad sound.""" - + """「悲しい」サウンド。""" SLIDE: Sound - """Sliding sound.""" - + """「するする動く」サウンド。""" SOARING: Sound - """Soaring sound.""" - + """「舞い上がる」サウンド。""" SPRING: Sound - """Spring sound.""" - + """「バネ」サウンド。""" TWINKLE: Sound - """Twinkling sound.""" - + """「キラキラ」サウンド。""" YAWN: Sound - """Yawning sound.""" + """「あくび」サウンド。""" \ No newline at end of file diff --git a/lang/ja/typeshed/stdlib/microbit/accelerometer.pyi b/lang/ja/typeshed/stdlib/microbit/accelerometer.pyi index bac82c0..8f689c7 100644 --- a/lang/ja/typeshed/stdlib/microbit/accelerometer.pyi +++ b/lang/ja/typeshed/stdlib/microbit/accelerometer.pyi @@ -1,115 +1,103 @@ -"""Measure the acceleration of the micro:bit and recognise gestures. -""" - +"""micro:bitの加速度測定とジェスチャー認識をします。""" from typing import Tuple def get_x() -> int: - """Get the acceleration measurement in the ``x`` axis in milli-g. + """``x`` 軸の加速度測定値をミリg単位で取得します。 - Example: ``accelerometer.get_x()`` +Example: ``accelerometer.get_x()`` - :return: A positive or negative integer depending on direction in the range +/- 2000mg. - """ +:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" ... def get_y() -> int: - """Get the acceleration measurement in the ``y`` axis in milli-g. + """``y`` 軸の加速度測定値をミリg単位で取得します。 - Example: ``accelerometer.get_y()`` +Example: ``accelerometer.get_y()`` - :return: A positive or negative integer depending on direction in the range +/- 2000mg. - """ +:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" ... def get_z() -> int: - """Get the acceleration measurement in the ``z`` axis in milli-g. + """``z`` 軸の加速度測定値をミリg単位で取得します。 - Example: ``accelerometer.get_z()`` +Example: ``accelerometer.get_z()`` - :return: A positive or negative integer depending on direction in the range +/- 2000mg. - """ +:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" ... def get_values() -> Tuple[int, int, int]: - """Get the acceleration measurements in all axes at once as a tuple. + """すべての軸の加速度測定値をタプルとして一度に取得します。 - Example: ``x, y, z = accelerometer.get_values()`` +Example: ``x, y, z = accelerometer.get_values()`` - :return: a three-element tuple of integers ordered as X, Y, Z, each value a positive or negative integer depending on direction in the range +/- 2000mg - """ +:return: a three-element tuple of integers ordered as X, Y, Z, each value a positive or negative integer depending on direction in the range +/- 2000mg""" ... def get_strength() -> int: - """Get the acceleration measurement of all axes combined, as a positive integer. This is the Pythagorean sum of the X, Y and Z axes. + """すべての軸を合成した加速度測定値を正の整数値で得ます。これは X軸、Y軸、Z軸のピタゴラス和になります。 - Example: ``accelerometer.get_strength()`` +Example: ``accelerometer.get_strength()`` - :return: The combined acceleration strength of all the axes, in milli-g. - """ +:return: The combined acceleration strength of all the axes, in milli-g.""" ... def current_gesture() -> str: - """Get the name of the current gesture. + """現在のジェスチャーの名前を取得します。 - Example: ``accelerometer.current_gesture()`` +Example: ``accelerometer.current_gesture()`` - 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. +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. - :return: The current gesture - """ +:return: The current gesture""" ... def is_gesture(name: str) -> bool: - """Check if the named gesture is currently active. + """指定した名前のジェスチャーが現在アクティブであるかどうかを確認します。 - Example: ``accelerometer.is_gesture('shake')`` +Example: ``accelerometer.is_gesture('shake')`` - 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. +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. - :param name: The gesture name. - :return: ``True`` if the gesture is active, ``False`` otherwise. - """ +:param name: ジェスチャー名。 +:return: ``True`` if the gesture is active, ``False`` otherwise.""" ... def was_gesture(name: str) -> bool: - """Check if the named gesture was active since the last call. + """直前の呼び出し以降に、指定した名前のジェスチャーがアクティブになったかどうかを確認します。 - Example: ``accelerometer.was_gesture('shake')`` +Example: ``accelerometer.was_gesture('shake')`` - 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. +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. - :param name: The gesture name. - :return: ``True`` if the gesture was active since the last call, ``False`` otherwise. - """ +:param name: ジェスチャー名。 +:return: ``True`` if the gesture was active since the last call, ``False`` otherwise.""" def get_gestures() -> Tuple[str, ...]: - """Return a tuple of the gesture history. + """ジェスチャー履歴のタプルを返します。 - Example: ``accelerometer.get_gestures()`` +Example: ``accelerometer.get_gestures()`` - Clears the gesture history before returning. +Clears the gesture history before returning. - Gestures are not updated in the background so there needs to be constant - calls to some accelerometer method to do the gesture detection. Usually - gestures can be detected using a loop with a small :func:`microbit.sleep` delay. +Gestures are not updated in the background so there needs to be constant +calls to some accelerometer method to do the gesture detection. Usually +gestures can be detected using a loop with a small :func:`microbit.sleep` delay. - :return: The history as a tuple, most recent last. - """ +:return: The history as a tuple, most recent last.""" ... def set_range(value: int) -> None: - """Set the accelerometer sensitivity range, in g (standard gravity), to the closest values supported by the hardware, so it rounds to either ``2``, ``4``, or ``8`` g. + """加速度センサーの感度範囲を g (標準重力)で設定します。設定値は、ハードウェアがサポートする最も近い値、すなわち ``2``、``4``、``8`` g のいずれかに丸められます。 - Example: ``accelerometer.set_range(8)`` +Example: ``accelerometer.set_range(8)`` - :param value: New range for the accelerometer, an integer in ``g``. - """ +:param value: 加速度センサーの新しい感度範囲。``g`` 単位の整数値で指定します。""" \ No newline at end of file diff --git a/lang/ja/typeshed/stdlib/microbit/audio.pyi b/lang/ja/typeshed/stdlib/microbit/audio.pyi index 3b1e327..309077d 100644 --- a/lang/ja/typeshed/stdlib/microbit/audio.pyi +++ b/lang/ja/typeshed/stdlib/microbit/audio.pyi @@ -1,160 +1,124 @@ -"""Play sounds using the micro:bit (import ``audio`` for V1 compatibility). -""" - +"""micro:bitでサウンドを再生します(V1との互換のために ``audio`` をインポートしてください)。""" from ..microbit import MicroBitDigitalPin, Sound, pin0 from typing import ClassVar, Iterable, Union -def play( - source: Union[Iterable[AudioFrame], Sound, SoundEffect], - wait: bool = True, - pin: MicroBitDigitalPin = pin0, - return_pin: Union[MicroBitDigitalPin, None] = None, -) -> None: - """Play a built-in sound, sound effect or custom audio frames. +def play(source: Union[Iterable[AudioFrame], Sound, SoundEffect], wait: bool=True, pin: MicroBitDigitalPin=pin0, return_pin: Union[MicroBitDigitalPin, None]=None) -> None: + """内蔵サウンド、サウンド効果、カスタム化したオーディオフレームのいずれかを再生します。 - Example: ``audio.play(Sound.GIGGLE)`` +Example: ``audio.play(Sound.GIGGLE)`` - :param source: A built-in ``Sound`` such as ``Sound.GIGGLE``, a ``SoundEffect`` or sample data as an iterable of ``AudioFrame`` objects. - :param wait: If ``wait`` is ``True``, this function will block until the sound is complete. - :param pin: An optional argument to specify the output pin can be used to override the default of ``pin0``. If we do not want any sound to play we can use ``pin=None``. - :param return_pin: Specifies a differential edge connector pin to connect to an external speaker instead of ground. This is ignored for the **V2** revision. - """ +:param source: ``Sound.GIGGLE`` などの内蔵の``Sound``、``SoundEffect``、``AudioFrame`` オブジェクトのイテラブルであるサンプルデータのいずれか。 +:param wait: ``wait`` が ``True`` の場合、サウンドの再生が終わるまでこの関数がブロックします。 +:param pin: (ピン) 出力端子をデフォルトの ``pin0`` から変えるためのオプション引数です。音を鳴らしたくない場合は ``pin=None`` を指定します。 +:param return_pin: グランドではなく外部スピーカーに接続する差動エッジコネクタの端子 +を指定します。**V2** ではこの指定を無視します。""" def is_playing() -> bool: - """Check whether a sound is playing. + """オーディオが再生中であるかどうかを確認します。 - Example: ``audio.is_playing()`` +Example: ``audio.is_playing()`` - :return: ``True`` if audio is playing, otherwise ``False``.""" +:return: ``True`` if audio is playing, otherwise ``False``.""" ... def stop() -> None: - """Stop all audio playback. + """すべてのオーディオ再生を停止します。 - Example: ``audio.stop()`` - """ +Example: ``audio.stop()``""" ... class SoundEffect: - """A sound effect, composed by a set of parameters configured via the constructor or attributes.""" - + """コンストラクタや属性で設定したパラメータのセットで構成されるサウンド効果。""" WAVEFORM_SINE: ClassVar[int] - """Sine wave option used for the ``waveform`` parameter.""" - + """``waveform`` パラメータに指定できる「サイン波」オプション。""" WAVEFORM_SAWTOOTH: ClassVar[int] - """Sawtooth wave option used for the ``waveform`` parameter.""" - + """``waveform`` パラメータに指定できる「のこぎり波」オプション。""" WAVEFORM_TRIANGLE: ClassVar[int] - """Triangle wave option used for the ``waveform`` parameter.""" - + """``waveform`` パラメータに指定できる「三角波」オプション。""" WAVEFORM_SQUARE: ClassVar[int] - """Square wave option used for the ``waveform`` parameter.""" - + """``waveform`` パラメータに指定できる「矩形波」オプション。""" WAVEFORM_NOISE: ClassVar[int] - """Noise option used for the ``waveform`` parameter.""" - + """``waveform`` パラメータに指定できる「ノイズ」オプション。""" SHAPE_LINEAR: ClassVar[int] - """Linear interpolation option used for the ``shape`` parameter.""" - + """``shape`` パラメータに指定できる「リニア補間」オプション。""" SHAPE_CURVE: ClassVar[int] - """Curve interpolation option used for the ``shape`` parameter.""" - + """``shape`` パラメータに指定できる「カーブ補間」オプション。""" SHAPE_LOG: ClassVar[int] - """Logarithmic interpolation option used for the ``shape`` parameter.""" - + """``shape`` パラメータに指定できる「対数補間」オプション。""" FX_NONE: ClassVar[int] - """No effect option used for the ``fx`` parameter.""" - + """``fx`` パラメータに指定できる「効果なし」オプション。""" FX_TREMOLO: ClassVar[int] - """Tremolo effect option used for the ``fx`` parameter.""" - + """``fx`` パラメータに指定できる「トレモロ効果」オプション。""" FX_VIBRATO: ClassVar[int] - """Vibrato effect option used for the ``fx`` parameter.""" - + """``fx`` パラメータに指定できる「ビブラート効果」オプション。""" FX_WARBLE: ClassVar[int] - """Warble effect option used for the ``fx`` parameter.""" - + """``fx`` パラメータに指定できる「ワブル効果」オプション。""" freq_start: int - """Start frequency in Hertz (Hz), a number between ``0`` and ``9999``""" - + """開始周波数。単位はヘルツ(Hz)で、``0``から``9999``の範囲の数値です。""" freq_end: int - """End frequency in Hertz (Hz), a number between ``0`` and ``9999``""" - + """終了周波数。単位はヘルツ(Hz)で、``0``から``9999``の範囲の数値です。""" duration: int - """Duration of the sound in milliseconds, a number between ``0`` and ``9999``""" - + """サウンドの長さ。``0`` から``9999``の範囲の数値です。""" vol_start: int - """Start volume value, a number between ``0`` and ``255``""" - + """開始音量。``0``から``255``の範囲の数値です。""" vol_end: int - """End volume value, a number between ``0`` and ``255``""" - + """終了音量。``0``から``255``の範囲の数値です。""" waveform: int - """Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise)""" - + """波形の種類。次の値のいずれか: ``WAVEFORM_SINE``、 ``WAVEFORM_SAWTOOTH``、``WAVEFORM_TRIANGLE``、 ``WAVEFORM_SQUARE``、``WAVEFORM_NOISE`` (ランダムに生成したノイズ)""" fx: int - """Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``""" - + """サウンドに追加する効果。次の値のいずれか: ``FX_TREMOLO``、``FX_VIBRATO``、``FX_WARBLE``、``FX_NONE``""" shape: int - """The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``""" - - def __init__( - self, - freq_start: int = 500, - freq_end: int = 2500, - duration: int = 500, - vol_start: int = 255, - vol_end: int = 0, - waveform: int = WAVEFORM_SQUARE, - fx: int = FX_NONE, - shape: int = SHAPE_LOG, - ): - """Create a new sound effect. - - Example: ``my_effect = SoundEffect(duration=1000)`` - - All the parameters are optional, with default values as shown above, and - they can all be modified via attributes of the same name. For example, we - can first create an effect ``my_effect = SoundEffect(duration=1000)``, - and then change its attributes ``my_effect.duration = 500``. - - :param freq_start: Start frequency in Hertz (Hz), a number between ``0`` and ``9999``. - :param freq_end: End frequency in Hertz (Hz), a number between ``0`` and ``9999``. - :param duration: Duration of the sound in milliseconds, a number between ``0`` and ``9999``. - :param vol_start: Start volume value, a number between ``0`` and ``255``. - :param vol_end: End volume value, a number between ``0`` and ``255``. - :param waveform: Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise). - :param fx: Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``. - :param shape: The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``. - """ + """開始周波数と終了周波数の補間曲線の種類で、波形の違いにより周波数の変化率が異なります。次の値のうちのいずれか: ``SHAPE_LINEAR``、``SHAPE_CURVE``、``SHAPE_LOG``""" + + def __init__(self, freq_start: int=500, freq_end: int=2500, duration: int=500, vol_start: int=255, vol_end: int=0, waveform: int=WAVEFORM_SQUARE, fx: int=FX_NONE, shape: int=SHAPE_LOG): + """新しいサウンド効果を作成します。 + +Example: ``my_effect = SoundEffect(duration=1000)`` + +All the parameters are optional, with default values as shown above, and +they can all be modified via attributes of the same name. For example, we +can first create an effect ``my_effect = SoundEffect(duration=1000)``, +and then change its attributes ``my_effect.duration = 500``. + +:param freq_start: 開始周波数。単位はヘルツ(Hz)で、``0``から``9999``の範囲の数値です。 +:param freq_end: 終了周波数。単位はヘルツ(Hz)で、``0``から``9999``の範囲の数値です。 +:param duration: サウンドの長さ。単位はミリ秒で、``0`` から``9999``の範囲の数値です。 +:param vol_start: 開始音量。``0``から``255``の範囲の数値です。 +:param vol_end: 終了音量。``0``から``255``の範囲の数値です。 +:param waveform: 波形の種類。次の値のいずれか: ``WAVEFORM_SINE``、 ``WAVEFORM_SAWTOOTH``、``WAVEFORM_TRIANGLE``、 ``WAVEFORM_SQUARE``、``WAVEFORM_NOISE`` (ランダムに生成したノイズ)。 +:param fx: サウンドに追加する効果。次の値のいずれか: ``FX_TREMOLO``、``FX_VIBRATO``、``FX_WARBLE``、``FX_NONE`` +:param shape: 開始周波数と終了周波数の補間曲線の種類で、波形の違いにより周波数の変化率が異なります。次の値のうちのいずれか: ``SHAPE_LINEAR``、``SHAPE_CURVE``、``SHAPE_LOG``""" + def copy(self) -> SoundEffect: - """Create a copy of this ``SoundEffect``. + """この ``SoundEffect`` のコピーを作成します。 - Example: ``sound_2 = sound_1.copy()`` +Example: ``sound_2 = sound_1.copy()`` - :return: A copy of the SoundEffect. - """ +:return: A copy of the SoundEffect.""" class AudioFrame: - """An ``AudioFrame`` object is a list of 32 samples each of which is a unsigned byte - (whole number between 0 and 255). + """``AudioFrame`` オブジェクトは32個のサンプルからなるリストです。それぞのサンプルは符号なしバイト(0〜255の整数)です。 - It takes just over 4 ms to play a single frame. +It takes just over 4 ms to play a single frame. - Example:: +Example:: - frame = AudioFrame() - for i in range(len(frame)): - frame[i] = 252 - i * 8 - """ + frame = AudioFrame() + for i in range(len(frame)): + frame[i] = 252 - i * 8""" def copyfrom(self, other: AudioFrame) -> None: - """Overwrite the data in this ``AudioFrame`` with the data from another ``AudioFrame`` instance. + """この ``AudioFrame`` のデータを、別の ``AudioFrame`` インスタンスのデータで上書きします。 + +Example: ``my_frame.copyfrom(source_frame)`` + +:param other: コピーするデータを持つ ``AudioFrame`` インスタンス。""" + + def __len__(self) -> int: + ... - Example: ``my_frame.copyfrom(source_frame)`` + def __setitem__(self, key: int, value: int) -> None: + ... - :param other: ``AudioFrame`` instance from which to copy the data. - """ - def __len__(self) -> int: ... - def __setitem__(self, key: int, value: int) -> None: ... - def __getitem__(self, key: int) -> int: ... + def __getitem__(self, key: int) -> int: + ... \ No newline at end of file diff --git a/lang/ja/typeshed/stdlib/microbit/compass.pyi b/lang/ja/typeshed/stdlib/microbit/compass.pyi index c74a47b..ccbd0f8 100644 --- a/lang/ja/typeshed/stdlib/microbit/compass.pyi +++ b/lang/ja/typeshed/stdlib/microbit/compass.pyi @@ -1,78 +1,70 @@ -"""Use the built-in compass. -""" +"""内蔵のコンパスを使います。 (方位磁針(コンパス))""" def calibrate() -> None: - """Starts the calibration process. + """調整処理を開始します。 - Example: ``compass.calibrate()`` +Example: ``compass.calibrate()`` - 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. - """ +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: - """Check is the compass is calibrated. + """コンパスが調整されているかどうかを確認します。 - Example: ``compass.is_calibrated()`` +Example: ``compass.is_calibrated()`` - :return: ``True`` if the compass has been successfully calibrated, ``False`` otherwise. - """ +:return: ``True`` if the compass has been successfully calibrated, ``False`` otherwise.""" ... def clear_calibration() -> None: - """Undoes the calibration, making the compass uncalibrated again. + """調整を取り消し、コンパスを未調整状態にします。 - Example: ``compass.clear_calibration()`` - """ +Example: ``compass.clear_calibration()``""" ... def get_x() -> int: - """Get the magnetic field strength on the ``x`` axis. + """``x`` 軸の磁場強度を取得します。 - Example: ``compass.get_x()`` +Example: ``compass.get_x()`` - Call ``calibrate`` first or the results will be inaccurate. +Call ``calibrate`` first or the results will be inaccurate. - :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. - """ +:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" ... def get_y() -> int: - """Get the magnetic field strength on the ``y`` axis. + """``y`` 軸の磁場強度を取得します。 - Example: ``compass.get_y()`` +Example: ``compass.get_y()`` - Call ``calibrate`` first or the results will be inaccurate. +Call ``calibrate`` first or the results will be inaccurate. - :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. - """ +:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" ... def get_z() -> int: - """Get the magnetic field strength on the ``z`` axis. + """``z`` 軸の磁場強度を取得します。 - Example: ``compass.get_z()`` +Example: ``compass.get_z()`` - Call ``calibrate`` first or the results will be inaccurate. +Call ``calibrate`` first or the results will be inaccurate. - :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. - """ +:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" ... def heading() -> int: - """Get the compass heading. + """コンパスの方位を取得します。 - Example: ``compass.heading()`` +Example: ``compass.heading()`` - :return: An integer in the range from 0 to 360, representing the angle in degrees, clockwise, with north as 0. - """ +:return: An integer in the range from 0 to 360, representing the angle in degrees, clockwise, with north as 0.""" ... def get_field_strength() -> int: - """Get the magnitude of the magnetic field around the device. + """デバイスのまわりの磁場の強さを取得します。 - Example: ``compass.get_field_strength()`` +Example: ``compass.get_field_strength()`` - :return: An integer indication of the magnitude of the magnetic field in nano tesla.""" - ... +:return: An integer indication of the magnitude of the magnetic field in nano tesla.""" + ... \ No newline at end of file diff --git a/lang/ja/typeshed/stdlib/microbit/display.pyi b/lang/ja/typeshed/stdlib/microbit/display.pyi index aa4013e..8cd651f 100644 --- a/lang/ja/typeshed/stdlib/microbit/display.pyi +++ b/lang/ja/typeshed/stdlib/microbit/display.pyi @@ -1,115 +1,92 @@ -"""Show text, images and animations on the 5×5 LED display. -""" - +"""5×5 LED ディスプレイ上にテキスト、イメージ、アニメーションを表示します。""" from ..microbit import Image from typing import Union, overload, Iterable def get_pixel(x: int, y: int) -> int: - """Get the brightness of the LED at column ``x`` and row ``y``. + """``x`` 列 ``y`` 行の LEDの明るさを取得します。 - Example: ``display.get_pixel(0, 0)`` +Example: ``display.get_pixel(0, 0)`` - :param x: The display column (0..4) - :param y: The display row (0..4) - :return: A number between 0 (off) and 9 (bright) - """ +:param x: ディスプレイの列 (0..4) +:param y: ディスプレイの行 (0..4) +:return: A number 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``. + """``x`` 列 ``y`` 行の LEDの明るさを設定します。 - Example: ``display.set_pixel(0, 0, 9)`` +Example: ``display.set_pixel(0, 0, 9)`` - :param x: The display column (0..4) - :param y: The display row (0..4) - :param value: The brightness between 0 (off) and 9 (bright) - """ +:param x: ディスプレイの列 (0..4) +:param y: ディスプレイの行 (0..4) +:param value: 0(オフ)から 9(明るい)までの明るさ""" ... def clear() -> None: - """Set the brightness of all LEDs to 0 (off). + """すべての LED の明るさを 0(オフ)に設定します。 - Example: ``display.clear()`` - """ +Example: ``display.clear()``""" ... -def show( - image: Union[str, float, int, Image, Iterable[Image]], - delay: int = 400, - wait: bool = True, - loop: bool = False, - clear: bool = False, -) -> None: - """Shows images, letters or digits on the LED display. +def show(image: Union[str, float, int, Image, Iterable[Image]], delay: int=400, wait: bool=True, loop: bool=False, clear: bool=False) -> None: + """イメージ、文字、数字をLEDディスプレイに表示します。 - Example: ``display.show(Image.HEART)`` +Example: ``display.show(Image.HEART)`` - When ``image`` is an image or a list of images then each image is displayed in turn. - If ``image`` is a string or number, each letter or digit is displayed in turn. +When ``image`` is an image or a list of images then each image is displayed in turn. +If ``image`` is a string or number, each letter or digit is displayed in turn. - :param image: A string, number, image or list of images to show. - :param delay: Each letter, digit or image is shown with ``delay`` milliseconds between them. - :param wait: If ``wait`` is ``True``, this function will block until the animation is finished, otherwise the animation will happen in the background. - :param loop: If ``loop`` is ``True``, the animation will repeat forever. - :param clear: If ``clear`` is ``True``, the display will be cleared after the sequence has finished. +:param image: 表示する文字列、数値、イメージ、イメージのリスト。 +:param delay: それぞれの文字、数字、イメージは ``delay`` ミリ秒間隔で表示されます。 +:param wait: ``wait`` が ``True`` である場合、アニメーションが終了するまで関数がブロックし、 そうでない場合にはバックグラウンドで実行されます。 +:param loop: ``loop`` が ``True`` である場合、アニメーションを永遠に繰り返します。 +:param clear: ``clear`` が ``True`` である場合、シーケンスの終了後にディスプレイをクリアします。 - The ``wait``, ``loop`` and ``clear`` arguments must be specified using their keyword. - """ +The ``wait``, ``loop`` and ``clear`` arguments must be specified using their keyword.""" ... -def scroll( - text: Union[str, float, int], - delay: int = 150, - wait: bool = True, - loop: bool = False, - monospace: bool = False, -) -> None: - """Scrolls a number or text on the LED display. - - Example: ``display.scroll('micro:bit')`` - - :param text: The string to scroll. If ``text`` is an integer or float it is first converted to a string using ``str()``. - :param delay: The ``delay`` parameter controls how fast the text is scrolling. - :param wait: If ``wait`` is ``True``, this function will block until the animation is finished, otherwise the animation will happen in the background. - :param loop: If ``loop`` is ``True``, the animation will repeat forever. - :param monospace: 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. - - The ``wait``, ``loop`` and ``monospace`` arguments must be specified - using their keyword. - """ +def scroll(text: Union[str, float, int], delay: int=150, wait: bool=True, loop: bool=False, monospace: bool=False) -> None: + """LEDディスプレィ上に数値やテキストをスクロール表示します。 + +Example: ``display.scroll('micro:bit')`` + +:param text: スクロールする文字列。``text`` が整数か浮動小数点数であれば、まず ``str()`` を使って文字列に変換します。 +:param delay: ``delay`` パラメータはテキストのスクロール速度を制御します。 +:param wait: ``wait`` が ``True`` である場合、アニメーションが終了するまで関数がブロックし、 そうでない場合にはバックグラウンドで実行されます。 +:param loop: ``loop`` が ``True`` である場合、アニメーションを永遠に繰り返します。 +:param monospace: ``monospace`` が ``True`` である場合、文字の幅が 5 ピクセルになり、そうでない場合にはスクロール時の文字間の幅が 1 ピクセルになります。 + +The ``wait``, ``loop`` and ``monospace`` arguments must be specified +using their keyword.""" ... def on() -> None: - """Turn on the LED display. + """ディスプレイをオンにします。 - Example: ``display.on()`` - """ +Example: ``display.on()``""" ... def off() -> None: - """Turn off the LED display (disabling the display allows you to re-use the GPIO pins for other purposes). + """LEDディスプレイをオフにします(ディスプレイを無効にすることにより、GPIO端子を他の目的に再利用できるようになります)。 - Example: ``display.off()`` - """ +Example: ``display.off()``""" ... def is_on() -> bool: - """Check whether the LED display is enabled. + """LEDディスプレイが有効であるかどうかを確認します。 - Example: ``display.is_on()`` +Example: ``display.is_on()`` - :return: ``True`` if the display is on, otherwise returns ``False``. - """ +:return: ``True`` if the display is on, otherwise returns ``False``.""" ... def read_light_level() -> int: - """Read the light level. + """ディスプレイのまわりの光量を読み取ります。 - Example: ``display.read_light_level()`` +Example: ``display.read_light_level()`` - Uses the display's LEDs in reverse-bias mode to sense the amount of light - falling on the display. +Uses the display's LEDs in reverse-bias mode to sense the amount of light +falling on the display. - :return: An integer between 0 and 255 representing the light level, with larger meaning more light. - """ - ... +:return: An integer between 0 and 255 representing the light level, with larger meaning more light.""" + ... \ No newline at end of file diff --git a/lang/ja/typeshed/stdlib/microbit/i2c.pyi b/lang/ja/typeshed/stdlib/microbit/i2c.pyi index df26efa..4d57a54 100644 --- a/lang/ja/typeshed/stdlib/microbit/i2c.pyi +++ b/lang/ja/typeshed/stdlib/microbit/i2c.pyi @@ -1,57 +1,49 @@ -"""Communicate with devices using the I²C bus protocol. -""" - +"""I²C バスプロトコルでデバイスと通信します。""" from _typeshed import ReadableBuffer from ..microbit import MicroBitDigitalPin, pin19, pin20 from typing import List -def init( - freq: int = 100000, sda: MicroBitDigitalPin = pin20, scl: MicroBitDigitalPin = pin19 -) -> None: - """Re-initialize a peripheral. +def init(freq: int=100000, sda: MicroBitDigitalPin=pin20, scl: MicroBitDigitalPin=pin19) -> None: + """ペリフェラルを再初期化します。 - Example: ``i2c.init()`` +Example: ``i2c.init()`` - :param freq: clock frequency - :param sda: ``sda`` pin (default 20) - :param scl: ``scl`` pin (default 19) +:param freq: クロック周波数 +:param sda: ``sda`` 端子(デフォルトは 20) +:param scl: ``scl`` 端子(デフォルトは 19) - On a micro:bit V1 board, changing the I²C pins from defaults will make - the accelerometer and compass stop working, as they are connected - internally to those pins. This warning does not apply to the **V2** - revision of the micro:bit as this has `separate I²C lines `_ - for the motion sensors and the edge connector. - """ +On a micro:bit V1 board, changing the I²C pins from defaults will make +the accelerometer and compass stop working, as they are connected +internally to those pins. This warning does not apply to the **V2** +revision of the micro:bit as this has `separate I²C lines `_ +for the motion sensors and the edge connector.""" ... def scan() -> List[int]: - """Scan the bus for devices. + """バスをスキャンしてデバイスを探します。 - Example: ``i2c.scan()`` +Example: ``i2c.scan()`` - :return: A list of 7-bit addresses corresponding to those devices that responded to the scan. - """ +:return: A list of 7-bit addresses corresponding to those devices that responded to the scan.""" ... -def read(addr: int, n: int, repeat: bool = False) -> bytes: - """Read bytes from a device. +def read(addr: int, n: int, repeat: bool=False) -> bytes: + """デバイスからバイト列を読み取ります。 - Example: ``i2c.read(0x50, 64)`` +Example: ``i2c.read(0x50, 64)`` - :param addr: The 7-bit address of the device - :param n: The number of bytes to read - :param repeat: If ``True``, no stop bit will be sent - :return: The bytes read - """ +:param addr: デバイスの7ビットアドレス +:param n: 読み取るバイト数 +:param repeat: ``True`` にすると、ストップビットが送られません。 +:return: The bytes read""" ... -def write(addr: int, buf: ReadableBuffer, repeat: bool = False) -> None: - """Write bytes to a device. +def write(addr: int, buf: ReadableBuffer, repeat: bool=False) -> None: + """デバイスにバイト列を書き込みます。 - Example: ``i2c.write(0x50, bytes([1, 2, 3]))`` +Example: ``i2c.write(0x50, bytes([1, 2, 3]))`` - :param addr: The 7-bit address of the device - :param buf: A buffer containing the bytes to write - :param repeat: If ``True``, no stop bit will be sent - """ - ... +:param addr: デバイスの7ビットアドレス +:param buf: 書き込むバイトを含むバッファ +:param repeat: ``True`` にすると、ストップビットが送られません。""" + ... \ No newline at end of file diff --git a/lang/ja/typeshed/stdlib/microbit/microphone.pyi b/lang/ja/typeshed/stdlib/microbit/microphone.pyi index 68e8f3a..b714ccf 100644 --- a/lang/ja/typeshed/stdlib/microbit/microphone.pyi +++ b/lang/ja/typeshed/stdlib/microbit/microphone.pyi @@ -1,70 +1,62 @@ -"""Respond to sound using the built-in microphone (V2 only). -""" - +"""内蔵マイクを使って音に応答します(V2 のみ)。""" from typing import Optional, Tuple from ..microbit import SoundEvent def current_event() -> Optional[SoundEvent]: - """Get the last recorded sound event + """記録されている最新のサウンドイベントを取得します。 - Example: ``microphone.current_event()`` +Example: ``microphone.current_event()`` - :return: The event, ``SoundEvent('loud')`` or ``SoundEvent('quiet')``. - """ +:return: The event, ``SoundEvent('loud')`` or ``SoundEvent('quiet')``.""" ... def was_event(event: SoundEvent) -> bool: - """Check if a sound was heard at least once since the last call. + """直前の呼び出しから少なくとも一度はサウンドイベントが発生したかどうかを確認します。 - Example: ``microphone.was_event(SoundEvent.LOUD)`` +Example: ``microphone.was_event(SoundEvent.LOUD)`` - This call clears the sound history before returning. +This call clears the sound history before returning. - :param event: The event to check for, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET`` - :return: ``True`` if sound was heard at least once since the last call, otherwise ``False``. - """ +:param event: ``SoundEvent.LOUD`` や ``SoundEvent.QUIET`` などのイベント +:return: ``True`` if sound was heard at least once since the last call, otherwise ``False``.""" ... def is_event(event: SoundEvent) -> bool: - """Check the most recent sound event detected. + """直近に検出されたサウンドイベントを確認します。 - Example: ``microphone.is_event(SoundEvent.LOUD)`` +Example: ``microphone.is_event(SoundEvent.LOUD)`` - This call does not clear the sound event history. +This call does not clear the sound event history. - :param event: The event to check for, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET`` - :return: ``True`` if sound was the most recent heard, ``False`` otherwise. - """ +:param event: ``SoundEvent.LOUD`` や ``SoundEvent.QUIET`` など、確認するサウンドイベント +:return: ``True`` if sound was the most recent heard, ``False`` otherwise.""" ... def get_events() -> Tuple[SoundEvent, ...]: - """Get the sound event history as a tuple. + """サウンドイベント履歴をタプルとして取得します。 - Example: ``microphone.get_events()`` +Example: ``microphone.get_events()`` - This call clears the sound history before returning. +This call clears the sound history before returning. - :return: A tuple of the event history with the most recent event last. - """ +:return: A tuple of the event history with the most recent event last.""" ... def set_threshold(event: SoundEvent, value: int) -> None: - """Set the threshold for a sound event. + """サウンドイベントのしきい値を設定します。 - Example: ``microphone.set_threshold(SoundEvent.LOUD, 250)`` +Example: ``microphone.set_threshold(SoundEvent.LOUD, 250)`` - A high threshold means the event will only trigger if the sound is very loud (>= 250 in the example). +A high threshold means the event will only trigger if the sound is very loud (>= 250 in the example). - :param event: A sound event, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET``. - :param value: The threshold level in the range 0-255. - """ +:param event: ``SoundEvent.LOUD`` や ``SoundEvent.QUIET`` などのサウンドイベント。 +:param value: 0~255の範囲で指定するしきい値レベル。""" ... def sound_level() -> int: - """Get the sound pressure level. + """音圧レベルを取得します。 - Example: ``microphone.sound_level()`` +Example: ``microphone.sound_level()`` - :return: A representation of the sound pressure level in the range 0 to 255. - """ - ... +:return: A representation of the sound pressure level in the range 0 to 255.""" + ... \ No newline at end of file diff --git a/lang/ja/typeshed/stdlib/microbit/speaker.pyi b/lang/ja/typeshed/stdlib/microbit/speaker.pyi index 5a74a4d..f0878b4 100644 --- a/lang/ja/typeshed/stdlib/microbit/speaker.pyi +++ b/lang/ja/typeshed/stdlib/microbit/speaker.pyi @@ -1,18 +1,15 @@ -"""Control the built-in speaker (V2 only). -""" +"""内蔵スピーカーを制御します(V2のみ)。""" def off() -> None: - """Turn the speaker off. + """スピーカーをオフにします。 - Example: ``speaker.off()`` +Example: ``speaker.off()`` - This does not disable sound output to an edge connector pin. - """ +This does not disable sound output to an edge connector pin.""" ... def on() -> None: - """Turn the speaker on. + """スピーカーをオンにします。 - Example: ``speaker.on()`` - """ - ... +Example: ``speaker.on()``""" + ... \ No newline at end of file diff --git a/lang/ja/typeshed/stdlib/microbit/spi.pyi b/lang/ja/typeshed/stdlib/microbit/spi.pyi index 09c4046..b4ee96e 100644 --- a/lang/ja/typeshed/stdlib/microbit/spi.pyi +++ b/lang/ja/typeshed/stdlib/microbit/spi.pyi @@ -1,60 +1,47 @@ -"""Communicate with devices using the serial peripheral interface (SPI) bus. -""" - +"""シリアルペリフェラルインターフェイス(SPI)バスを使ってデバイスと通信します。""" from _typeshed import ReadableBuffer, WriteableBuffer from ..microbit import pin13, pin14, pin15, MicroBitDigitalPin -def init( - baudrate: int = 1000000, - bits: int = 8, - mode: int = 0, - sclk: MicroBitDigitalPin = pin13, - mosi: MicroBitDigitalPin = pin15, - miso: MicroBitDigitalPin = pin14, -) -> None: - """Initialize SPI communication. - - Example: ``spi.init()`` - - For correct communication, the parameters have to be the same on both communicating devices. - - :param baudrate: The speed of communication. - :param bits: The width in bits of each transfer. Currently only ``bits=8`` is supported. However, this may change in the future. - :param mode: Determines the combination of clock polarity and phase - `see online table `_. - :param sclk: sclk pin (default 13) - :param mosi: mosi pin (default 15) - :param miso: miso pin (default 14) - """ +def init(baudrate: int=1000000, bits: int=8, mode: int=0, sclk: MicroBitDigitalPin=pin13, mosi: MicroBitDigitalPin=pin15, miso: MicroBitDigitalPin=pin14) -> None: + """SPI通信を初期化します。 + +Example: ``spi.init()`` + +For correct communication, the parameters have to be the same on both communicating devices. + +:param baudrate: 通信速度。 +:param bits: 送信時のビット幅。現在のところは ``bits=8`` だけをサポート。しかし、これは将来的に変更するかもしれません。 +:param mode: クロックの極性と位相の組み合わせを決定します - `オンラインの表を参照 `_ 。 +:param sclk: sclk 端子(デフォルトは 13) +:param mosi: mosi 端子(デフォルトは 15) +:param miso: miso 端子(デフォルトは 14)""" ... -def read(nbytes: int, out: int = 0) -> bytes: - """Read at most ``nbytes`` while continuously writing the single byte given by ``out``. +def read(nbytes: int, out: int=0) -> bytes: + """バイト列を読み取ります。 - Example: ``spi.read(64)`` +Example: ``spi.read(64)`` - :param nbytes: Maximum number of bytes to read. - :param out: The byte value to write (default 0). - :return: The bytes read. - """ +:param nbytes: 読み取る最大バイト数。 +:param out: 書き込むバイト値(初期値は'0') +:return: The bytes read.""" ... def write(buffer: ReadableBuffer) -> None: - """Write bytes to the bus. + """デバイスにバイト列を書き込みます。 - Example: ``spi.write(bytes([1, 2, 3]))`` +Example: ``spi.write(bytes([1, 2, 3]))`` - :param buffer: A buffer to read data from. - """ +:param buffer: データの読み取り元のバッファ。""" ... def write_readinto(out: WriteableBuffer, in_: ReadableBuffer) -> None: - """Write the ``out`` buffer to the bus and read any response into the ``in_`` buffer. + """``out`` バッファをバスに書き込み、任意のレスポンスを ``in_`` バッファに読み取ります。 - Example: ``spi.write_readinto(out_buffer, in_buffer)`` +Example: ``spi.write_readinto(out_buffer, in_buffer)`` - The length of the buffers should be the same. The buffers can be the same object. +The length of the buffers should be the same. The buffers can be the same object. - :param out: The buffer to write any response to. - :param in_: The buffer to read data from. - """ - ... +:param out: レスポンスの書き込みバッファ。 +:param in_: データの読み取り元のバッファ。""" + ... \ No newline at end of file diff --git a/lang/ja/typeshed/stdlib/microbit/uart.pyi b/lang/ja/typeshed/stdlib/microbit/uart.pyi index 2ab650f..f94f28a 100644 --- a/lang/ja/typeshed/stdlib/microbit/uart.pyi +++ b/lang/ja/typeshed/stdlib/microbit/uart.pyi @@ -1,96 +1,79 @@ -"""Communicate with a device using a serial interface. -""" - +"""シリアルインタフェースを使ってデバイスと通信します。""" from _typeshed import WriteableBuffer from ..microbit import MicroBitDigitalPin from typing import Optional, Union - ODD: int -"""Odd parity""" - +"""奇数パリティ""" EVEN: int -"""Even parity""" - -def init( - baudrate: int = 9600, - bits: int = 8, - parity: Optional[int] = None, - stop: int = 1, - tx: Optional[MicroBitDigitalPin] = None, - rx: Optional[MicroBitDigitalPin] = None, -) -> None: - """Initialize serial communication. - - Example: ``uart.init(115200, tx=pin0, rx=pin1)`` - - :param baudrate: The speed of communication. - :param bits: The size of bytes being transmitted. micro:bit only supports 8. - :param parity: How parity is checked, ``None``, ``uart.ODD`` or ``uart.EVEN``. - :param stop: The number of stop bits, has to be 1 for micro:bit. - :param tx: Transmitting pin. - :param rx: Receiving pin. - - 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. - - For more details see `the online documentation `_. - """ +"""偶数パリティ""" + +def init(baudrate: int=9600, bits: int=8, parity: Optional[int]=None, stop: int=1, tx: Optional[MicroBitDigitalPin]=None, rx: Optional[MicroBitDigitalPin]=None) -> None: + """シリアル通信を初期化します。 + +Example: ``uart.init(115200, tx=pin0, rx=pin1)`` + +:param baudrate: 通信速度。 +:param bits: 送信するビット幅。micro:bitは8だけをサポートしています。 +:param parity: パリティのチェック方法。``None``、``uart.ODD``、``uart.EVEN`` のいずれかを指定できます。 +:param stop: ストップビットの数はmicro:bitでは1にする必要があります。 +:param tx: 送信端子。 +:param rx: 受信端子。 + +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. + +For more details see `the online documentation `_.""" ... def any() -> bool: - """Check if any data is waiting. + """受信待ちのデータがあるかを確認します。 - Example: ``uart.any()`` +Example: ``uart.any()`` - :return: ``True`` if any data is waiting, else ``False``. - """ +:return: ``True`` if any data is waiting, else ``False``.""" ... -def read(nbytes: Optional[int] = None) -> Optional[bytes]: - """Read bytes. +def read(nbytes: Optional[int]=None) -> Optional[bytes]: + """バイト列を読み取ります。 - Example: ``uart.read()`` +Example: ``uart.read()`` - :param nbytes: If ``nbytes`` is specified then read at most that many bytes, otherwise read as many bytes as possible - :return: A bytes object or ``None`` on timeout - """ +:param nbytes: ``nbytes`` が指定されていれば、そのバイト数まで読み込みます。指定されていなければ、できるだけ多く読み取ります +:return: A bytes object or ``None`` on timeout""" ... -def readinto(buf: WriteableBuffer, nbytes: Optional[int] = None) -> Optional[int]: - """Read bytes into the ``buf``. +def readinto(buf: WriteableBuffer, nbytes: Optional[int]=None) -> Optional[int]: + """``buf`` にバイト列を読み取ります。 - Example: ``uart.readinto(input_buffer)`` +Example: ``uart.readinto(input_buffer)`` - :param buf: The buffer to write to. - :param nbytes: If ``nbytes`` is specified then read at most that many bytes, otherwise read ``len(buf)`` bytes. - :return: number of bytes read and stored into ``buf`` or ``None`` on timeout. - """ +:param buf: 書き込みバッファ。 +:param nbytes: ``nbytes`` が指定されていれば、そのバイト数まで読み込みます。指定されていなければ、``len(buf)`` を読み取ります。 +:return: number of bytes read and stored into ``buf`` or ``None`` on timeout.""" ... def readline() -> Optional[bytes]: - """Read a line, ending in a newline character. + """改行文字で終わる行を読みます。 - Example: ``uart.readline()`` +Example: ``uart.readline()`` - :return: The line read or ``None`` on timeout. The newline character is included in the returned bytes. - """ +:return: The line read or ``None`` on timeout. The newline character is included in the returned bytes.""" ... def write(buf: Union[bytes, str]) -> Optional[int]: - """Write a buffer to the bus. + """バスにバッファを書き込みます。 - Example: ``uart.write('hello world')`` +Example: ``uart.write('hello world')`` - :param buf: A bytes object or a string. - :return: The number of bytes written, or ``None`` on timeout. +:param buf: バイト列オブジェクトまたは文字列。 +:return: The number of bytes written, or ``None`` on timeout. - Examples:: +Examples:: - uart.write('hello world') - uart.write(b'hello world') - uart.write(bytes([1, 2, 3])) - """ - ... + uart.write('hello world') + uart.write(b'hello world') + uart.write(bytes([1, 2, 3]))""" + ... \ No newline at end of file diff --git a/lang/ja/typeshed/stdlib/micropython.pyi b/lang/ja/typeshed/stdlib/micropython.pyi index 7a6079f..7c013bf 100644 --- a/lang/ja/typeshed/stdlib/micropython.pyi +++ b/lang/ja/typeshed/stdlib/micropython.pyi @@ -1,144 +1,131 @@ -"""MicroPython internals.""" - +"""MicroPythonの内部。""" from typing import Any, TypeVar, overload - -_T = TypeVar("_T") +_T = TypeVar('_T') def const(expr: _T) -> _T: - """Used to declare that the expression is a constant so that the compiler can - optimise it. + """コンパイルが最適化できるように、式が定数であることを宣言するために使います。 - The use of this function should be as follows:: +The use of this function should be as follows:: - from micropython import const - CONST_X = const(123) - CONST_Y = const(2 * CONST_X + 1) + from micropython import const + CONST_X = const(123) + CONST_Y = const(2 * CONST_X + 1) - Constants declared this way are still accessible as global variables from - outside the module they are declared in. On the other hand, if a constant - begins with an underscore then it is hidden, it is not available as a - global variable, and does not take up any memory during execution. +Constants declared this way are still accessible as global variables from +outside the module they are declared in. On the other hand, if a constant +begins with an underscore then it is hidden, it is not available as a +global variable, and does not take up any memory during execution. - :param expr: A constant expression. - """ +:param expr: 定数式。""" ... @overload def opt_level() -> int: - """Get the current optimisation level for the compilation of scripts. + """スクリプトの現在のコンパイル最適化レベルを取得します。 - Example: ``micropython.opt_level()`` +Example: ``micropython.opt_level()`` - The optimisation level controls the following compilation features: +The optimisation level controls the following compilation features: - - Assertions: at level 0 assertion statements are enabled and compiled - into the bytecode; at levels 1 and higher assertions are not compiled. +- Assertions: at level 0 assertion statements are enabled and compiled + into the bytecode; at levels 1 and higher assertions are not compiled. - - Built-in ``__debug__`` variable: at level 0 this variable expands to - True; at levels 1 and higher it expands to False. +- Built-in ``__debug__`` variable: at level 0 this variable expands to + True; at levels 1 and higher it expands to False. - - Source-code line numbers: at levels 0, 1 and 2 source-code line number - are stored along with the bytecode so that exceptions can report the - line number they occurred at; at levels 3 and higher line numbers are - not stored. +- Source-code line numbers: at levels 0, 1 and 2 source-code line number + are stored along with the bytecode so that exceptions can report the + line number they occurred at; at levels 3 and higher line numbers are + not stored. - :return: An integer representing the current level. - """ +:return: An integer representing the current level.""" ... @overload def opt_level(level: int) -> None: - """Sets the optimisation level for subsequent compilation of scripts. + """スクリプトの後続のコンパイル最適化レベルを設定します。 - Example: ``micropython.opt_level(1)`` +Example: ``micropython.opt_level(1)`` - The optimisation level controls the following compilation features: +The optimisation level controls the following compilation features: - - Assertions: at level 0 assertion statements are enabled and compiled - into the bytecode; at levels 1 and higher assertions are not compiled. +- Assertions: at level 0 assertion statements are enabled and compiled + into the bytecode; at levels 1 and higher assertions are not compiled. - - Built-in ``__debug__`` variable: at level 0 this variable expands to - True; at levels 1 and higher it expands to False. +- Built-in ``__debug__`` variable: at level 0 this variable expands to + True; at levels 1 and higher it expands to False. - - Source-code line numbers: at levels 0, 1 and 2 source-code line number - are stored along with the bytecode so that exceptions can report the - line number they occurred at; at levels 3 and higher line numbers are - not stored. +- Source-code line numbers: at levels 0, 1 and 2 source-code line number + are stored along with the bytecode so that exceptions can report the + line number they occurred at; at levels 3 and higher line numbers are + not stored. - The default optimisation level is usually level 0. +The default optimisation level is usually level 0. - :param level: An integer optimisation level. - """ +:param level: 最適化レベルを示す整数値。""" ... -def mem_info(verbose: Any = None) -> None: - """Print information about currently used memory. +def mem_info(verbose: Any=None) -> None: + """現在使っているメモリに関する情報を表示します。 - Example: ``micropython.mem_info()`` +Example: ``micropython.mem_info()`` - :param verbose: If the ``verbose`` argument is given then extra information is printed. - """ +:param verbose: ``verbose`` 引数を指定すると、詳しい情報を表示します。""" ... -def qstr_info(verbose: Any = None) -> None: - """Print information about currently interned strings. +def qstr_info(verbose: Any=None) -> None: + """現在インターンされている文字列に関する情報を表示します。 - Example: ``micropython.qstr_info()`` +Example: ``micropython.qstr_info()`` - :param verbose: If the ``verbose`` argument is given then extra information is printed. +:param verbose: ``verbose`` 引数を指定すると、詳しい情報を表示します。 - The information that is printed is implementation dependent, but currently - includes the number of interned strings and the amount of RAM they use. In - verbose mode it prints out the names of all RAM-interned strings. - """ +The information that is printed is implementation dependent, but currently +includes the number of interned strings and the amount of RAM they use. In +verbose mode it prints out the names of all RAM-interned strings.""" ... def stack_use() -> int: - """Return an integer representing the current amount of stack that is being - used. + """現在使われているスタックのサイズを表す整数を返します。 - Example: ``micropython.stack_use()`` +Example: ``micropython.stack_use()`` - The absolute value of this is not particularly useful, rather it - should be used to compute differences in stack usage at different points. +The absolute value of this is not particularly useful, rather it +should be used to compute differences in stack usage at different points. - :return: An integer representing current stack use. - """ +:return: An integer representing current stack use.""" ... def heap_lock() -> None: - """Lock the heap. + """ヒープをロックします。 - Example: ``micropython.heap_lock()`` +Example: ``micropython.heap_lock()`` - When locked no memory allocation can occur and a ``MemoryError`` will be - raised if any heap allocation is attempted. - """ +When locked no memory allocation can occur and a ``MemoryError`` will be +raised if any heap allocation is attempted.""" ... def heap_unlock() -> None: - """Unlock the heap. + """ヒープのロックを解除します。 - Example: ``micropython.heap_unlock()`` +Example: ``micropython.heap_unlock()`` - When locked no memory allocation can occur and a ``MemoryError`` will be - raised if any heap allocation is attempted. - """ +When locked no memory allocation can occur and a ``MemoryError`` will be +raised if any heap allocation is attempted.""" ... def kbd_intr(chr: int) -> None: - """Set the character that will raise a ``KeyboardInterrupt`` exception. + """``KeyboardInterrupt`` 例外を発生させる文字を設定します。 - Example: ``micropython.kbd_intr(-1)`` +Example: ``micropython.kbd_intr(-1)`` - :param chr: Character code to raise the interrupt or -1 to disable capture of Ctrl-C. +:param chr: 割り込みを発生させる文字コード。あるいは、Ctrl-Cのキャプチャを無効にするには-1を指定します。 - By default this is set to 3 during script execution, corresponding to Ctrl-C. - Passing -1 to this function will disable capture of Ctrl-C, and passing 3 - will restore it. +By default this is set to 3 during script execution, corresponding to Ctrl-C. +Passing -1 to this function will disable capture of Ctrl-C, and passing 3 +will restore it. - This function can be used to prevent the capturing of Ctrl-C on the - incoming stream of characters that is usually used for the REPL, in case - that stream is used for other purposes. - """ - ... +This function can be used to prevent the capturing of Ctrl-C on the +incoming stream of characters that is usually used for the REPL, in case +that stream is used for other purposes.""" + ... \ No newline at end of file diff --git a/lang/ja/typeshed/stdlib/music.pyi b/lang/ja/typeshed/stdlib/music.pyi index 5f4778b..7a84637 100644 --- a/lang/ja/typeshed/stdlib/music.pyi +++ b/lang/ja/typeshed/stdlib/music.pyi @@ -1,167 +1,128 @@ -"""Create and play melodies. -""" +"""メロディーの作成と再生。""" from typing import Optional, Tuple, Union, List - from .microbit import MicroBitDigitalPin, pin0 - DADADADUM: Tuple[str, ...] -"""Melody: the opening to Beethoven’s 5th Symphony in C minor.""" - +"""メロディ: ベートーヴェンの交響曲第5番ハ短調の冒頭。""" ENTERTAINER: Tuple[str, ...] -"""Melody: the opening fragment of Scott Joplin’s Ragtime classic “The Entertainer”.""" - +"""メロディ: スコット・ジョプリンのラグタイム・クラシック『ジ・エンターテイナー 』の冒頭。""" PRELUDE: Tuple[str, ...] -"""Melody: the opening of the first Prelude in C Major of J.S.Bach’s 48 Preludes and Fugues.""" - +"""メロディ: J・S・バッハの前奏曲とフーガ計48曲の前奏曲第1番ハ長調の冒頭。""" ODE: Tuple[str, ...] -"""Melody: the “Ode to Joy” theme from Beethoven’s 9th Symphony in D minor.""" - +"""メロディ: ベートーヴェンの交響曲第9番ニ短調より『歓喜の歌』のテーマ。""" NYAN: Tuple[str, ...] -"""Melody: the Nyan Cat theme (http://www.nyan.cat/). +"""メロディ: Nyan Cat テーマ (http://www.nyan.cat/)。 The composer is unknown. This is fair use for educational porpoises (as they say in New York).""" - RINGTONE: Tuple[str, ...] -"""Melody: something that sounds like a mobile phone ringtone. +"""メロディ: 携帯電話の着信音のようなもの。 To be used to indicate an incoming message. """ - FUNK: Tuple[str, ...] -"""Melody: a funky bass line for secret agents and criminal masterminds.""" - +"""メロディ: スパイと犯罪の黒幕用のファンキーなベースライン。""" BLUES: Tuple[str, ...] -"""Melody: a boogie-woogie 12-bar blues walking bass.""" - +"""メロディ: ブギー・ウーギーの 12 小節のブルース・ウォーキング・ベース。""" BIRTHDAY: Tuple[str, ...] -"""Melody: “Happy Birthday to You…” +"""メロディ:『ハッピーバースディトゥユー ...』 For copyright status see: http://www.bbc.co.uk/news/world-us-canada-34332853 """ - WEDDING: Tuple[str, ...] -"""Melody: the bridal chorus from Wagner’s opera “Lohengrin”.""" - +"""メロディ: ワグナーのオペラ『ローエングリン』より婚礼の合唱。""" FUNERAL: Tuple[str, ...] -"""Melody: the “funeral march” otherwise known as Frédéric Chopin’s Piano Sonata No. 2 in B♭ minor, Op. 35.""" - +"""メロディ: フレデリック・ショパンのピアノソナタ第2番変ロ短調 作品35(別名『葬送』)。""" PUNCHLINE: Tuple[str, ...] -"""Melody: a fun fragment that signifies a joke has been made.""" - +"""メロディ: ジョークが言われたことを意味する楽しい音楽。""" PYTHON: Tuple[str, ...] -"""Melody: John Philip Sousa’s march “Liberty Bell” aka, the theme for “Monty Python’s Flying Circus” (after which the Python programming language is named).""" - +"""メロディ: ジョン・フィリップ・スーザの『自由の鐘』(『空飛ぶモンティ・パイソン』のテーマともいう)(プログラミング言語Pythonの名前の由来となった)。""" BADDY: Tuple[str, ...] -"""Melody: silent movie era entrance of a baddy.""" - +"""メロディ: 無声映画時代の悪役の登場。""" CHASE: Tuple[str, ...] -"""Melody: silent movie era chase scene.""" - +"""メロディ: 無声映画時代のチェイスシーン。""" BA_DING: Tuple[str, ...] -"""Melody: a short signal to indicate something has happened.""" - +"""メロディ: 何かが起こったことを示す短い信号。""" WAWAWAWAA: Tuple[str, ...] -"""Melody: a very sad trombone.""" - +"""メロディ: 非常に悲しいトロンボーン。""" JUMP_UP: Tuple[str, ...] -"""Melody: for use in a game, indicating upward movement.""" - +"""メロディ: ゲームでの使用で、上方向の動きを示します。""" JUMP_DOWN: Tuple[str, ...] -"""Melody: for use in a game, indicating downward movement.""" - +"""メロディ: ゲームでの使用で、下向きの動きを示します。""" POWER_UP: Tuple[str, ...] -"""Melody: a fanfare to indicate an achievement unlocked.""" - +"""メロディ: アチーブメントを達成したことを示すファンファーレ。""" POWER_DOWN: Tuple[str, ...] -"""Melody: a sad fanfare to indicate an achievement lost.""" +"""メロディ: アチーブメントを達成しなかったことを示すファンファーレ。""" -def set_tempo(ticks: int = 4, bpm: int = 120) -> None: - """Sets the approximate tempo for playback. +def set_tempo(ticks: int=4, bpm: int=120) -> None: + """再生するためのおおよそのテンポを設定します。 - Example: ``music.set_tempo(bpm=120)`` +Example: ``music.set_tempo(bpm=120)`` - :param ticks: The number of ticks constituting a beat. - :param bpm: An integer determining how many beats per minute. +:param ticks: 1ビートを構成するティック数。 +:param bpm: 毎分のビート数を決定する整数。 - Suggested default values allow the following useful behaviour: +Suggested default values allow the following useful behaviour: - - music.set_tempo() – reset the tempo to default of ticks = 4, bpm = 120 - - music.set_tempo(ticks=8) – change the “definition” of a beat - - music.set_tempo(bpm=180) – just change the tempo +- music.set_tempo() – reset the tempo to default of ticks = 4, bpm = 120 +- music.set_tempo(ticks=8) – change the “definition” of a beat +- music.set_tempo(bpm=180) – just change the tempo - To work out the length of a tick in milliseconds is very simple arithmetic: - 60000/bpm/ticks_per_beat. For the default values that’s - 60000/120/4 = 125 milliseconds or 1 beat = 500 milliseconds. - """ +To work out the length of a tick in milliseconds is very simple arithmetic: +60000/bpm/ticks_per_beat. For the default values that’s +60000/120/4 = 125 milliseconds or 1 beat = 500 milliseconds.""" ... def get_tempo() -> Tuple[int, int]: - """Gets the current tempo as a tuple of integers: ``(ticks, bpm)``. + """現在のテンポを整数のタプル ``(ticks, bpm)`` として取得します。 - Example: ``ticks, beats = music.get_tempo()`` +Example: ``ticks, beats = music.get_tempo()`` - :return: The temp as a tuple with two integer values, the ticks then the beats per minute. - """ +:return: The temp as a tuple with two integer values, the ticks then the beats per minute.""" ... -def play( - music: Union[str, List[str], Tuple[str, ...]], - pin: Optional[MicroBitDigitalPin] = pin0, - wait: bool = True, - loop: bool = False, -) -> None: - """Plays music. +def play(music: Union[str, List[str], Tuple[str, ...]], pin: Optional[MicroBitDigitalPin]=pin0, wait: bool=True, loop: bool=False) -> None: + """ミュージックを再生します。 - Example: ``music.play(music.NYAN)`` +Example: ``music.play(music.NYAN)`` - :param music: music specified in `a special notation `_ - :param pin: the output pin for use with an external speaker (default ``pin0``), ``None`` for no sound. - :param wait: If ``wait`` is set to ``True``, this function is blocking. - :param loop: If ``loop`` is set to ``True``, the tune repeats until ``stop`` is called or the blocking call is interrupted. +:param music: `特別な表記 `_ で指定されたミュージック +:param pin: (ピン) 外部スピーカー用出力端子(デフォルトは ``pin0``)。音を鳴らしたくない場合は ``None`` を指定します。 +:param wait: ``wait`` を ``True`` に設定した場合、この関数がブロックします。 +:param loop: ``loop`` が ``True`` の場合、曲は ``stop`` が呼び出されるか、ブロックコールが中断されるまで繰り返し再生されます。 - Many built-in melodies are defined in this module. - """ +Many built-in melodies are defined in this module.""" ... -def pitch( - frequency: int, - duration: int = -1, - pin: Optional[MicroBitDigitalPin] = pin0, - wait: bool = True, -) -> None: - """Play a note. +def pitch(frequency: int, duration: int=-1, pin: Optional[MicroBitDigitalPin]=pin0, wait: bool=True) -> None: + """音符を再生します。 - Example: ``music.pitch(185, 1000)`` +Example: ``music.pitch(185, 1000)`` - :param frequency: An integer frequency - :param duration: A millisecond duration. If negative then sound is continuous until the next call or a call to ``stop``. - :param pin: Optional output pin (default ``pin0``). - :param wait: If ``wait`` is set to ``True``, this function is blocking. +:param frequency: 周波数を示す整数値 +:param duration: 持続時間をミリ秒単位で指定します。負の場合、次の呼び出しか ``stop`` の呼び出しまで再生が続きます。 +:param pin: オプションの出力端子(デフォルトは ``pin0``)。 +:param wait: ``wait`` を ``True`` に設定した場合、この関数がブロックします。 - For example, if the frequency is set to 440 and the length to - 1000 then we hear a standard concert A for one second. +For example, if the frequency is set to 440 and the length to +1000 then we hear a standard concert A for one second. - You can only play one pitch on one pin at any one time. - """ +You can only play one pitch on one pin at any one time.""" ... -def stop(pin: Optional[MicroBitDigitalPin] = pin0) -> None: - """Stops all music playback on the built-in speaker and any pin outputting sound. +def stop(pin: Optional[MicroBitDigitalPin]=pin0) -> None: + """内蔵スピーカーやサウンドを出力する端子から鳴らしているすべてのミュージック再生を停止します。 - Example: ``music.stop()`` +Example: ``music.stop()`` - :param pin: An optional argument can be provided to specify a pin, e.g. ``music.stop(pin1)``. - """ +:param pin: オプションの引数には、たとえば ``music.stop(pin1)`` などの端子を指定できます。""" def reset() -> None: - """Resets ticks, bpm, duration and octave to their default values. + """ティック、bpm、持続時間、オクターブをデフォルト値にリセットします。 - Example: ``music.reset()`` +Example: ``music.reset()`` - Values: - - ``ticks = 4`` - - ``bpm = 120`` - - ``duration = 4`` - - ``octave = 4`` - """ - ... +Values: +- ``ticks = 4`` +- ``bpm = 120`` +- ``duration = 4`` +- ``octave = 4``""" + ... \ No newline at end of file diff --git a/lang/ja/typeshed/stdlib/neopixel.pyi b/lang/ja/typeshed/stdlib/neopixel.pyi index 2d5a749..8dadfad 100644 --- a/lang/ja/typeshed/stdlib/neopixel.pyi +++ b/lang/ja/typeshed/stdlib/neopixel.pyi @@ -1,82 +1,81 @@ -"""Individually addressable RGB and RGBW LED strips. -""" +"""個別にアドレス可能な RGB/RGBW LED ストリップ。""" from .microbit import MicroBitDigitalPin from typing import Tuple class NeoPixel: - def __init__(self, pin: MicroBitDigitalPin, n: int, bpp: int = 3) -> None: - """Initialise a new strip of neopixel LEDs controlled via a pin. - Example: ``np = neopixel.NeoPixel(pin0, 8)`` + def __init__(self, pin: MicroBitDigitalPin, n: int, bpp: int=3) -> None: + """端子を介して制御するネオピクセルLEDの新しいストリップを初期化します。 - To support RGBW neopixels, a third argument can be passed to - ``NeoPixel`` to indicate the number of bytes per pixel (``bpp``). - For RGBW, this is is 4 rather than the default of 3 for RGB and GRB. +Example: ``np = neopixel.NeoPixel(pin0, 8)`` - Each pixel is addressed by a position (starting from 0). Neopixels are - given RGB (red, green, blue) / RGBW (red, green, blue, white) values - between 0-255 as a tuple. For example, in RGB, ``(255,255,255)`` is - white. In RGBW, ``(255,255,255,0)`` or ``(0,0,0,255)`` is white. +To support RGBW neopixels, a third argument can be passed to +``NeoPixel`` to indicate the number of bytes per pixel (``bpp``). +For RGBW, this is is 4 rather than the default of 3 for RGB and GRB. - See `the online docs `_ for warnings and other advice. +Each pixel is addressed by a position (starting from 0). Neopixels are +given RGB (red, green, blue) / RGBW (red, green, blue, white) values +between 0-255 as a tuple. For example, in RGB, ``(255,255,255)`` is +white. In RGBW, ``(255,255,255,0)`` or ``(0,0,0,255)`` is white. - :param pin: The pin controlling the neopixel strip. - :param n: The number of neopixels in the strip. - :param bpp: Bytes per pixel. For RGBW neopixel support, pass 4 rather than the default of 3 for RGB and GRB. - """ +See `the online docs `_ for warnings and other advice. + +:param pin: ネオピクセルストリップを制御する端子。 +:param n: ストリップ内のネオピクセルの数。 +:param bpp: ピクセルあたりのバイト数。RGBW ネオピクセルに対応するには、RGBやGRBのデフォルト値の3ではなく、4 を指定します。""" ... + def clear(self) -> None: - """Clear all the pixels. + """すべてのピクセルをクリアします。 - Example: ``np.clear()`` - """ +Example: ``np.clear()``""" ... + def show(self) -> None: - """Show the pixels. + """ピクセルを表示します。 - Example: ``np.show()`` +Example: ``np.show()`` - Must be called for any updates to become visible. - """ +Must be called for any updates to become visible.""" ... + def write(self) -> None: - """Show the pixels (micro:bit V2 only). + """ピクセルを表示します(micro:bit V2 のみ)。 - Example: ``np.write()`` +Example: ``np.write()`` - Must be called for any updates to become visible. +Must be called for any updates to become visible. - Equivalent to ``show``. - """ +Equivalent to ``show``.""" ... + def fill(self, colour: Tuple[int, ...]) -> None: - """Colour all pixels a given RGB/RGBW value (micro:bit V2 only). + """指定した RGB/RGBW 値をすべてのピクセルに設定します(micro:bit V2 のみ)。 - Example: ``np.fill((0, 0, 255))`` +Example: ``np.fill((0, 0, 255))`` - :param colour: A tuple of the same length as the number of bytes per pixel (bpp). +:param colour: ピクセルあたりのバイト数(bpp)と同じ長さのタプル。 - Use in conjunction with ``show()`` to update the neopixels. - """ +Use in conjunction with ``show()`` to update the neopixels.""" ... + def __setitem__(self, key: int, value: Tuple[int, ...]) -> None: - """Set a pixel colour. + """ピクセルの色を設定します。 - Example: ``np[0] = (255, 0, 0)`` +Example: ``np[0] = (255, 0, 0)`` + +:param key: ピクセル番号。 +:param value: 色。""" - :param key: The pixel number. - :param value: The colour. - """ def __getitem__(self, key: int) -> Tuple[int, ...]: - """Get a pixel colour. + """ピクセルの色を取得します。 + +Example: ``r, g, b = np[0]`` - Example: ``r, g, b = np[0]`` +:param key: ピクセル番号。 +:return: The colour tuple.""" - :param key: The pixel number. - :return: The colour tuple. - """ def __len__(self) -> int: - """Get length of this pixel strip. + """このピクセルストリップの長さを取得します。 - Example: ``len(np)`` - """ +Example: ``len(np)``""" \ No newline at end of file diff --git a/lang/ja/typeshed/stdlib/os.pyi b/lang/ja/typeshed/stdlib/os.pyi index 2f2db77..a9f2217 100644 --- a/lang/ja/typeshed/stdlib/os.pyi +++ b/lang/ja/typeshed/stdlib/os.pyi @@ -1,73 +1,63 @@ -"""Access the file system. -""" - +"""ファイルシステムにアクセスします。""" from typing import Tuple from typing import List def listdir() -> List[str]: - """List files. + """ファイルすべての名前のリストを取得します。 - Example: ``os.listdir()`` +Example: ``os.listdir()`` - :return: A list of the names of all the files contained within the local - persistent on-device file system. - """ +:return: A list of the names of all the files contained within the local +persistent on-device file system.""" ... def remove(filename: str) -> None: - """Remove (delete) a file. + """ファイルを削除します。 - Example: ``os.remove('data.txt')`` +Example: ``os.remove('data.txt')`` - :param filename: The file to delete. +:param filename: 削除するファイルの名前。 - If the file does not exist an ``OSError`` exception will occur. - """ +If the file does not exist an ``OSError`` exception will occur.""" ... def size(filename: str) -> int: - """Returns the size of a file. + """ファイルのサイズを返します。 - Example: ``os.size('data.txt')`` +Example: ``os.size('data.txt')`` - :param filename: The file - :return: The size in bytes. +:param filename: ファイル +:return: The size in bytes. - If the file does not exist an ``OSError`` exception will occur. - """ +If the file does not exist an ``OSError`` exception will occur.""" class uname_result(Tuple[str, str, str, str, str]): - """Result of ``os.uname()``""" + """``os.uname()`` の結果""" sysname: str - """Operating system name.""" - + """オペレーティングシステム名。""" nodename: str - """Name of machine on network (implementation-defined).""" - + """ネットワーク上のマシンの名前(実装定義)。""" release: str - """Operating system release.""" - + """オペレーティングシステムのリリース。""" version: str - """Operating system version.""" - + """オペレーティングシステムのバージョン。""" machine: str - """Hardware identifier.""" + """ハードウェア識別子。""" def uname() -> uname_result: - """Returns information identifying the current operating system. + """現在のオペレーティングシステムを識別する情報を返します。 - Example: ``os.uname()`` +Example: ``os.uname()`` - The return value is an object with five attributes: +The return value is an object with five attributes: - - ``sysname`` - operating system name - - ``nodename`` - name of machine on network (implementation-defined) - - ``release`` - operating system release - - ``version`` - operating system version - - ``machine`` - hardware identifier +- ``sysname`` - operating system name +- ``nodename`` - name of machine on network (implementation-defined) +- ``release`` - operating system release +- ``version`` - operating system version +- ``machine`` - hardware identifier - There is no underlying operating system in MicroPython. As a result the - information returned by the ``uname`` function is mostly useful for - versioning details. - """ - ... +There is no underlying operating system in MicroPython. As a result the +information returned by the ``uname`` function is mostly useful for +versioning details.""" + ... \ No newline at end of file diff --git a/lang/ja/typeshed/stdlib/radio.pyi b/lang/ja/typeshed/stdlib/radio.pyi index 8dd0267..83ee371 100644 --- a/lang/ja/typeshed/stdlib/radio.pyi +++ b/lang/ja/typeshed/stdlib/radio.pyi @@ -1,152 +1,129 @@ -"""Communicate between micro:bits with the built-in radio. -""" - +"""内蔵の無線通信を使ったmicro:bit間の通信。""" from _typeshed import WriteableBuffer from typing import Optional, Tuple - RATE_1MBIT: int -"""Constant used to indicate a throughput of 1 MBit a second.""" - +"""1 MBit/秒のスループットを示すために使われる定数。""" RATE_2MBIT: int -"""Constant used to indicate a throughput of 2 MBit a second.""" +"""2 MBit/秒のスループットを示すために使われる定数。""" def on() -> None: - """Turns the radio on. + """無線通信をオンにします。 - Example: ``radio.on()`` +Example: ``radio.on()`` - This needs to be explicitly called since the radio draws power and takes - up memory that you may otherwise need. - """ +This needs to be explicitly called since the radio draws power and takes +up memory that you may otherwise need.""" ... def off() -> None: - """Turns off the radio, saving power and memory. + """無線通信をオフにして、電力とメモリを節約します。 - Example: ``radio.off()`` - """ +Example: ``radio.off()``""" ... -def config( - length: int = 32, - queue: int = 3, - channel: int = 7, - power: int = 6, - address: int = 0x75626974, - group: int = 0, - data_rate: int = RATE_1MBIT, -) -> None: - """Configures the radio. - - Example: ``radio.config(group=42)`` - - The default configuration is suitable for most use. - - :param length: (default=32) defines the maximum length, in bytes, of a message sent via the radio. - It can be up to 251 bytes long (254 - 3 bytes for S0, LENGTH and S1 preamble). - :param queue: (default=3) specifies the number of messages that can be stored on the incoming message queue. - If there are no spaces left on the queue for incoming messages, then the incoming message is dropped. - :param channel: (default=7) an integer value from 0 to 83 (inclusive) that defines an arbitrary "channel" to which the radio is tuned. - Messages will be sent via this channel and only messages received via this channel will be put onto the incoming message queue. Each step is 1MHz wide, based at 2400MHz. - :param power: (default=6) is an integer value from 0 to 7 (inclusive) to indicate the strength of signal used when broadcasting a message. - The higher the value the stronger the signal, but the more power is consumed by the device. The numbering translates to positions in the following list of dBm (decibel milliwatt) values: -30, -20, -16, -12, -8, -4, 0, 4. - :param address: (default=0x75626974) an arbitrary name, expressed as a 32-bit address, that's used to filter incoming packets at the hardware level, keeping only those that match the address you set. - The default used by other micro:bit related platforms is the default setting used here. - :param group: (default=0) an 8-bit value (0-255) used with the ``address`` when filtering messages. - Conceptually, "address" is like a house/office address and "group" is like the person at that address to which you want to send your message. - :param data_rate: (default=``radio.RATE_1MBIT``) indicates the speed at which data throughput takes place. - Can be one of the following constants defined in the ``radio`` module: ``RATE_250KBIT``, ``RATE_1MBIT`` or ``RATE_2MBIT``. - - If ``config`` is not called then the defaults described above are assumed. - """ +def config(length: int=32, queue: int=3, channel: int=7, power: int=6, address: int=1969383796, group: int=0, data_rate: int=RATE_1MBIT) -> None: + """無線通信を設定します。 + +Example: ``radio.config(group=42)`` + +The default configuration is suitable for most use. + +:param length: (デフォルト=32)\u3000無線を介して送信されるメッセージのバイト単位の最大長を設定します。 +最大で 251 バイト(S0、長さ、S1 プリアンブルは254 から 3 を引いたバイト数)に設定できます。 +:param queue: (デフォルト=3)\u3000受信メッセージキューに格納できるメッセージの数を指定します。 +着信メッセージのキューに空きがない場合、着信メッセージは捨てられます。 +:param channel: (デフォルト=7)\u3000無線が同調されている任意の「チャネル」を定義するもので、0 から 83 までの整数値を設定できます。メッセージはこのチャネル経由で送信され、このチャネル経由で受信したメッセージだけが受信メッセージキューに入れられます。各ステップは 1MHz 幅で、2400MHz を基準にしています。 +:param power: (デフォルト=6)\u3000メッセージをブロードキャストするときに使用される信号の強度を示すもので、0 から 7 までの整数値(指定の値を含む。)を設定できです。 +値が高いほど信号は強くなりますが、デバイスが消費する電力が大きくなります。指定の番号は次のリストの dBm(デシベルミリワット)値の位置に変換されます: -30, -20, -16, -12, -8, -4, 0, 4 。 +:param address: (デフォルト=0x75626974)\u300032 ビットのアドレスとして表される任意の名前であり、ハードウェアレベルで着信パケットをフィルタリングするために使用されます。フィルタリングはユーザーが設定したアドレスと一致するもののみを維持します。 +他のmicro:bit関連のプラットフォームで使われるデフォルトは、ここで使われるデフォルト設定となっています。 +:param group: (デフォルト=0)\u30008ビットの値(0〜255)であり、 ``address`` フィルタしたメッセージで使います。 +概念的に「address」は自宅/事務所の住所のようなものであり、「group」はその住所のメッセージを受け取人のようなものです。 +:param data_rate: (デフォルト=``radio.RATE_1MBIT``)\u3000データスループットが起こる速度を示しています。 +``radio`` モジュールに定義されている定数 ``RATE_250KBIT``、``RATE_1MBIT``、``RATE_2MBIT`` のいずれかを指定します。 + +If ``config`` is not called then the defaults described above are assumed.""" ... def reset() -> None: - """Reset the settings to their default values. + """設定をデフォルト値にリセットします。 - Example: ``radio.reset()`` +Example: ``radio.reset()`` - The defaults as as per the ``config`` function above. - """ +The defaults as as per the ``config`` function above.""" ... def send_bytes(message: bytes) -> None: - """Sends a message containing bytes. + """バイト列を含んだメッセージを送信します。 - Example: ``radio.send_bytes(b'hello')`` +Example: ``radio.send_bytes(b'hello')`` - :param message: The bytes to send. - """ +:param message: 送信するバイト列。""" ... def receive_bytes() -> Optional[bytes]: - """Receive the next incoming message on the message queue. + """メッセージキューにある次の着信メッセージを受信します。 - Example: ``radio.receive_bytes()`` +Example: ``radio.receive_bytes()`` - :return: The message bytes if any, otherwise ``None``. - """ +:return: The message bytes if any, otherwise ``None``.""" ... def receive_bytes_into(buffer: WriteableBuffer) -> Optional[int]: - """Copy the next incoming message on the message queue into a buffer. + """メッセージキューにある次の着信メッセージをバッファにコピーします。 - Example: ``radio.receive_bytes_info(buffer)`` +Example: ``radio.receive_bytes_info(buffer)`` - :param buffer: The target buffer. The message is truncated if larger than the buffer. - :return: ``None`` if there are no pending messages, otherwise it returns the length of the message (which might be more than the length of the buffer). - """ +:param buffer: メッセージを格納するバッファ。メッセージがバッファより大きい場合、メッセージの収まらない部分が切り捨てられます。 +:return: ``None`` if there are no pending messages, otherwise it returns the length of the message (which might be more than the length of the buffer).""" ... def send(message: str) -> None: - """Sends a message string. + """メッセージ文字列を送信します。 - Example: ``radio.send('hello')`` +Example: ``radio.send('hello')`` - This is the equivalent of ``radio.send_bytes(bytes(message, 'utf8'))`` but with ``b'\x01\x00\x01'`` - prepended to the front (to make it compatible with other platforms that target the micro:bit). +This is the equivalent of ``radio.send_bytes(bytes(message, 'utf8'))`` but with ``b'\x01\x00\x01'`` +prepended to the front (to make it compatible with other platforms that target the micro:bit). - :param message: The string to send. - """ +:param message: 送信する文字列。""" ... def receive() -> Optional[str]: - """Works in exactly the same way as ``receive_bytes`` but returns whatever was sent. + """``receive_bytes`` と同じように動作しますが、送信されてきたものはすべて返します。 - Example: ``radio.receive()`` +Example: ``radio.receive()`` - Equivalent to ``str(receive_bytes(), 'utf8')`` but with a check that the the first - three bytes are ``b'\x01\x00\x01'`` (to make it compatible with other platforms that - may target the micro:bit). +Equivalent to ``str(receive_bytes(), 'utf8')`` but with a check that the the first +three bytes are ``b'\x01\x00\x01'`` (to make it compatible with other platforms that +may target the micro:bit). - :return: The message with the prepended bytes stripped and converted to a string. +:return: The message with the prepended bytes stripped and converted to a string. - A ``ValueError`` exception is raised if conversion to string fails. - """ +A ``ValueError`` exception is raised if conversion to string fails.""" ... def receive_full() -> Optional[Tuple[bytes, int, int]]: - """Returns a tuple containing three values representing the next incoming message on the message queue. + """メッセージキューにある次の受信メッセージを表す3つの値をタプルで返します。 - Example: ``radio.receive_full()`` +Example: ``radio.receive_full()`` - If there are no pending messages then ``None`` is returned. +If there are no pending messages then ``None`` is returned. - The three values in the tuple represent: +The three values in the tuple represent: - - the next incoming message on the message queue as bytes. - - the RSSI (signal strength): a value between 0 (strongest) and -255 (weakest) as measured in dBm. - - a microsecond timestamp: the value returned by ``time.ticks_us()`` when the message was received. +- the next incoming message on the message queue as bytes. +- the RSSI (signal strength): a value between 0 (strongest) and -255 (weakest) as measured in dBm. +- a microsecond timestamp: the value returned by ``time.ticks_us()`` when the message was received. - For example:: +For example:: - details = radio.receive_full() - if details: - msg, rssi, timestamp = details + details = radio.receive_full() + if details: + msg, rssi, timestamp = details - This function is useful for providing information needed for triangulation - and/or trilateration with other micro:bit devices. +This function is useful for providing information needed for triangulation +and/or trilateration with other micro:bit devices. - :return: ``None`` if there is no message, otherwise a tuple of length three with the bytes, strength and timestamp values. - """ - ... +:return: ``None`` if there is no message, otherwise a tuple of length three with the bytes, strength and timestamp values.""" + ... \ No newline at end of file diff --git a/lang/ja/typeshed/stdlib/random.pyi b/lang/ja/typeshed/stdlib/random.pyi index a2c2ef3..50560b1 100644 --- a/lang/ja/typeshed/stdlib/random.pyi +++ b/lang/ja/typeshed/stdlib/random.pyi @@ -1,93 +1,80 @@ -"""Generate random numbers. -""" +"""乱数を生成します。""" from typing import TypeVar, Sequence, Union, overload def getrandbits(n: int) -> int: - """Generate an integer with ``n`` random bits. + """``n`` 乱数ビット数を持つ整数を生成します。 - Example: ``random.getrandbits(1)`` +Example: ``random.getrandbits(1)`` - :param n: A value between 1-30 (inclusive). - """ +:param n: 1~30の値(指定の値を含みます)。""" ... def seed(n: int) -> None: - """Initialize the random number generator. + """乱数ジェネレータを初期化します。 - Example: ``random.seed(0)`` +Example: ``random.seed(0)`` - :param n: The integer seed +:param n: 整数シード - This will give you reproducibly deterministic randomness from a given starting - state (``n``). - """ +This will give you reproducibly deterministic randomness from a given starting +state (``n``).""" ... def randint(a: int, b: int) -> int: - """Choose a random integer between ``a`` and ``b`` inclusive. + """``a`` から ``b`` の区間内のランダムな整数値を返します(指定の値を含みます)。 - Example: ``random.randint(0, 9)`` +Example: ``random.randint(0, 9)`` - :param a: Start value for the range (inclusive) - :param b: End value for the range (inclusive) +:param a: (A) 乱数区間の開始値(指定の値を含みます) +:param b: 乱数区間の終了値(指定の値を含みます) - Alias for ``randrange(a, b + 1)``. - """ +Alias for ``randrange(a, b + 1)``.""" ... @overload def randrange(stop: int) -> int: - """Choose a randomly selected integer between zero and up to (but not - including) ``stop``. + """0 から ``stop`` 未満までの間で無作為に選択された整数を返します。 - Example: ``random.randrange(10)`` +Example: ``random.randrange(10)`` - :param stop: End value for the range (exclusive) - """ +:param stop: 乱数区間の終了値(指定の値を含みません)""" ... @overload -def randrange(start: int, stop: int, step: int = 1) -> int: - """ - Choose a randomly selected element from ``range(start, stop, step)``. +def randrange(start: int, stop: int, step: int=1) -> int: + """``range(start, stop, step)`` から無作為に選択された整数を返します。 - Example: ``random.randrange(0, 10)`` +Example: ``random.randrange(0, 10)`` - :param start: The start of the range (inclusive) - :param stop: The end of the range (exclusive) - :param step: The step. - """ +:param start: 乱数区間の開始値(指定の値を含みます) +:param stop: 乱数区間の終了値(指定の値を含みません) +:param step: ステップ値。""" ... - -_T = TypeVar("_T") +_T = TypeVar('_T') def choice(seq: Sequence[_T]) -> _T: - """Choose a random element from the non-empty sequence ``seq``. + """空でないシーケンス ``seq`` からランダムな要素を返します。 - Example: ``random.choice([Image.HAPPY, Image.SAD])`` +Example: ``random.choice([Image.HAPPY, Image.SAD])`` - :param seq: A sequence. +:param seq: シーケンス。 - If ``seq`` is empty, raises ``IndexError``. - """ +If ``seq`` is empty, raises ``IndexError``.""" ... def random() -> float: - """Generate a random floating point number in the range [0.0, 1.0). + """0.0 以上、1.0 未満の区間から無作為に選択された浮動小数点数を生成します。 - Example: ``random.random()`` +Example: ``random.random()`` - :return: The random floating point number - """ +:return: The random floating point number""" ... def uniform(a: float, b: float) -> float: - """ - Return a random floating point number between ``a`` and ``b`` inclusive. + """``a`` から ``b`` の区間内のランダムな浮動小数点数を返します(指定の値を含みます)。 - Example: ``random.uniform(0, 9)`` +Example: ``random.uniform(0, 9)`` - :param a: Start value for the range (inclusive) - :param b: End value for the range (inclusive) - """ - ... +:param a: (A) 乱数区間の開始値(指定の値を含みます) +:param b: 乱数区間の終了値(指定の値を含みます)""" + ... \ No newline at end of file diff --git a/lang/ja/typeshed/stdlib/speech.pyi b/lang/ja/typeshed/stdlib/speech.pyi index 349d188..25b5f53 100644 --- a/lang/ja/typeshed/stdlib/speech.pyi +++ b/lang/ja/typeshed/stdlib/speech.pyi @@ -1,106 +1,79 @@ -"""Make the micro:bit talk, sing and make other speech like sounds. -""" - +"""micro:bit に話させたり、歌わせたり、その他の音声のようなサウンドを作らせたりします。""" from typing import Optional from .microbit import MicroBitDigitalPin, pin0 def translate(words: str) -> str: - """Translate English words to phonemes. + """英単語の並びを音素に変換します。 - Example: ``speech.translate('hello world')`` +Example: ``speech.translate('hello world')`` - :param words: A string of English words. - :return: A string containing a best guess at the appropriate phonemes to pronounce. - The output is generated from this `text to phoneme translation table `_. +:param words: 英単語の並びの文字列。 +:return: A string containing a best guess at the appropriate phonemes to pronounce. +The output is generated from this `text to phoneme translation table `_. - This function should be used to generate a first approximation of phonemes - that can be further hand-edited to improve accuracy, inflection and - emphasis. +This function should be used to generate a first approximation of phonemes +that can be further hand-edited to improve accuracy, inflection and +emphasis. - See `the online documentation `_ for detailed information. - """ +See `the online documentation `_ for detailed information.""" ... -def pronounce( - phonemes: str, - pitch: int = 64, - speed: int = 72, - mouth: int = 128, - throat: int = 128, - pin: Optional[MicroBitDigitalPin] = pin0, -) -> None: - """Pronounce phonemes. - - Example: ``speech.pronounce(' /HEHLOW WERLD')`` - - :param phonemes: The string of phonemes to pronounce - :param pitch: A number representing the pitch of the voice - :param speed: A number representing the speed of the voice - :param mouth: A number representing the mouth of the voice - :param throat: A number representing the throat of the voice - :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. - If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. - - Override the optional pitch, speed, mouth and throat settings to change the - timbre (quality) of the voice. - - See `the online documentation `_ for detailed information. - """ - ... +def pronounce(phonemes: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: Optional[MicroBitDigitalPin]=pin0) -> None: + """音素を発声します。 + +Example: ``speech.pronounce(' /HEHLOW WERLD')`` + +:param phonemes: 発音する音素の文字列 +:param pitch: 音声の音高を表す数値 +:param speed: 音声の速度を表す数値 +:param mouth: 音声の口の動きを表す数値 +:param throat: 音声の喉の動きを表す数値 +:param pin: (ピン) 出力端子をデフォルトの ``pin0`` から変えるためのオプション引数。 +音を鳴らしたくない場合は ``pin=None`` を指定します。micro:bit V2 のみで使えます。 -def say( - words: str, - pitch: int = 64, - speed: int = 72, - mouth: int = 128, - throat: int = 128, - pin: MicroBitDigitalPin = pin0, -) -> None: - """Say English words. - - Example: ``speech.say('hello world')`` - - :param words: The string of words to say. - :param pitch: A number representing the pitch of the voice - :param speed: A number representing the speed of the voice - :param mouth: A number representing the mouth of the voice - :param throat: A number representing the throat of the voice - :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. - If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. - - The result is semi-accurate for English. Override the optional pitch, speed, - mouth and throat settings to change the timbre (quality) of the voice. - - This is a short-hand equivalent of: - ``speech.pronounce(speech.translate(words))`` - - See `the online documentation `_ for detailed information. - """ +Override the optional pitch, speed, mouth and throat settings to change the +timbre (quality) of the voice. + +See `the online documentation `_ for detailed information.""" ... -def sing( - phonemes: str, - pitch: int = 64, - speed: int = 72, - mouth: int = 128, - throat: int = 128, - pin: MicroBitDigitalPin = pin0, -) -> None: - """Sing phonemes. - - Example: ``speech.sing(' /HEHLOW WERLD')`` - - :param phonemes: The string of words to sing. - :param pitch: A number representing the pitch of the voice - :param speed: A number representing the speed of the voice - :param mouth: A number representing the mouth of the voice - :param throat: A number representing the throat of the voice - :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. - If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. - - Override the optional pitch, speed, mouth and throat settings to change - the timbre (quality) of the voice. - - See `the online documentation `_ for detailed information. - """ +def say(words: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: MicroBitDigitalPin=pin0) -> None: + """英単語の並びを発声します。 + +Example: ``speech.say('hello world')`` + +:param words: 発声する言葉の文字列。 +:param pitch: 音声の音高を表す数値 +:param speed: 音声の速度を表す数値 +:param mouth: 音声の口の動きを表す数値 +:param throat: 音声の喉の動きを表す数値 +:param pin: (ピン) 出力端子をデフォルトの ``pin0`` から変えるためのオプション引数。 +音を鳴らしたくない場合は ``pin=None`` を指定します。micro:bit V2 のみで使えます。 + +The result is semi-accurate for English. Override the optional pitch, speed, +mouth and throat settings to change the timbre (quality) of the voice. + +This is a short-hand equivalent of: +``speech.pronounce(speech.translate(words))`` + +See `the online documentation `_ for detailed information.""" ... + +def sing(phonemes: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: MicroBitDigitalPin=pin0) -> None: + """音素を歌います。 + +Example: ``speech.sing(' /HEHLOW WERLD')`` + +:param phonemes: 歌う言葉の文字列。 +:param pitch: 音声の音高を表す数値 +:param speed: 音声の速度を表す数値 +:param mouth: 音声の口の動きを表す数値 +:param throat: 音声の喉の動きを表す数値 +:param pin: (ピン) 出力端子をデフォルトの ``pin0`` から変えるためのオプション引数。 +音を鳴らしたくない場合は ``pin=None`` を指定します。micro:bit V2 のみで使えます。 + +Override the optional pitch, speed, mouth and throat settings to change +the timbre (quality) of the voice. + +See `the online documentation `_ for detailed information.""" + ... \ No newline at end of file diff --git a/lang/ja/typeshed/stdlib/struct.pyi b/lang/ja/typeshed/stdlib/struct.pyi index 53b3e0b..987f964 100644 --- a/lang/ja/typeshed/stdlib/struct.pyi +++ b/lang/ja/typeshed/stdlib/struct.pyi @@ -1,65 +1,56 @@ -"""Pack and unpack primitive data types. -""" - +"""プリミティブデータ型のパックとアンパック。""" from _typeshed import ReadableBuffer, WriteableBuffer from typing import Any, Tuple, Union def calcsize(fmt: str) -> int: - """Get the number of bytes needed to store the given ``fmt``. + """指定した ``fmt`` で格納するために必要なバイト数を取得します。 - Example: ``struct.calcsize('hf')`` +Example: ``struct.calcsize('hf')`` - :param fmt: A format string. - :return The number of bytes needed to store such a value. - """ +:param fmt: フォーマット文字列。 +:return The number of bytes needed to store such a value.""" ... def pack(fmt: str, v1: Any, *vn: Any) -> bytes: - """Pack values according to a format string. + """フォーマット文字列にしたがって複数の値をパックします。 - Example: ``struct.pack('hf', 1, 3.1415)`` +Example: ``struct.pack('hf', 1, 3.1415)`` - :param fmt: The format string. - :param v1: The first value. - :param *vn: The remaining values. - :return A bytes object encoding the values. - """ +:param fmt: フォーマット文字列。 +:param v1: 先頭の値。 +:param *vn: 残りの値。 +:return A bytes object encoding the values.""" ... -def pack_into( - fmt: str, buffer: WriteableBuffer, offset: int, v1: Any, *vn: Any -) -> None: - """Pack values according to a format string. +def pack_into(fmt: str, buffer: WriteableBuffer, offset: int, v1: Any, *vn: Any) -> None: + """フォーマット文字列にしたがって複数の値をパックします。 - Example: ``struct.pack_info('hf', buffer, 1, 3.1415)`` +Example: ``struct.pack_info('hf', buffer, 1, 3.1415)`` - :param fmt: The format string. - :param buffer: The target buffer to write into. - :param offset: The offset into the buffer. May be negative to count from the end of the buffer. - :param v1: The first value. - :param *vn: The remaining values. - """ +:param fmt: フォーマット文字列。 +:param buffer: 書き込み先のバッファ。 +:param offset: バッファのオフセット。負の場合はバッファの最後からのオフセットになります。 +:param v1: 先頭の値。 +:param *vn: 残りの値。""" ... def unpack(fmt: str, data: ReadableBuffer) -> Tuple[Any, ...]: - """Unpack data according to a format string. + """フォーマット文字列にしたがってデータをアンパックします。 - Example: ``v1, v2 = struct.unpack('hf', buffer)`` +Example: ``v1, v2 = struct.unpack('hf', buffer)`` - :param fmt: The format string. - :param data: The data. - :return: A tuple of the unpacked values. - """ +:param fmt: フォーマット文字列。 +:param data: データ。 +:return: A tuple of the unpacked values.""" ... -def unpack_from(fmt: str, buffer: ReadableBuffer, offset: int = 0) -> Tuple: - """Unpack data from a buffer according to a format string. +def unpack_from(fmt: str, buffer: ReadableBuffer, offset: int=0) -> Tuple: + """フォーマット文字列にしたがってバッファからデータをアンパックします。 - Example: ``v1, v2 = struct.unpack_from('hf', buffer)`` +Example: ``v1, v2 = struct.unpack_from('hf', buffer)`` - :param fmt: The format string. - :param buffer: The source buffer to read from. - :param offset: The offset into the buffer. May be negative to count from the end of the buffer. - :return: A tuple of the unpacked values. - """ - ... +:param fmt: フォーマット文字列。 +:param buffer: 読み込み元のバッファ。 +:param offset: バッファのオフセット。負の場合はバッファの最後からのオフセットになります。 +:return: A tuple of the unpacked values.""" + ... \ No newline at end of file diff --git a/lang/ja/typeshed/stdlib/sys.pyi b/lang/ja/typeshed/stdlib/sys.pyi index 320bac9..136e7d3 100644 --- a/lang/ja/typeshed/stdlib/sys.pyi +++ b/lang/ja/typeshed/stdlib/sys.pyi @@ -1,43 +1,36 @@ -"""System specific functions""" - +"""システム固有関数。""" from typing import Any, Dict, List, NoReturn, TextIO, Tuple -def exit(retval: object = ...) -> NoReturn: - """Terminate current program with a given exit code. +def exit(retval: object=...) -> NoReturn: + """与えた終了コードで現在のプログラムを終了します。 - Example: ``sys.exit(1)`` +Example: ``sys.exit(1)`` - This function raises a ``SystemExit`` exception. If an argument is given, its - value given as an argument to ``SystemExit``. +This function raises a ``SystemExit`` exception. If an argument is given, its +value given as an argument to ``SystemExit``. - :param retval: The exit code or message. - """ +:param retval: 終了コードまたはメッセージ。""" ... def print_exception(exc: Exception) -> None: - """ - Print an exception with a traceback. - - Example: ``sys.print_exception(e)`` + """例外をトレースバック付きで出力します。 - :param exc: The exception to print +Example: ``sys.print_exception(e)`` - This is simplified version of a function which appears in the - ``traceback`` module in CPython. - """ +:param exc: 表示する例外 +This is simplified version of a function which appears in the +``traceback`` module in CPython.""" argv: List[str] -"""A mutable list of arguments the current program was started with.""" - +"""現在のプログラム開始時の引数の変更可能なリスト。""" byteorder: str -"""The byte order of the system (``"little"`` or ``"big"``).""" +"""システムのバイト順(``"little"`` または ``"big"``)。""" class _implementation: name: str version: Tuple[int, int, int] - implementation: _implementation -"""Object with information about the current Python implementation. +"""現在の Python 処理系に関する情報を持つオブジェクト。 For MicroPython, it has following attributes: @@ -51,13 +44,9 @@ minimal ports). CPython mandates more attributes for this object, but the actual useful bare minimum is implemented in MicroPython. """ - maxsize: int """ -Maximum value which a native integer type can hold on the current platform, -or maximum value representable by MicroPython integer type, if it's smaller -than platform max value (that is the case for MicroPython ports without -long int support). +現在のプラットフォームでネイティブ整数型が保持できる最大値、またはプラットフォームの最大値より小さい場合は MicroPython 整数型で表現可能な最大値(MicroPython ポートで 長整数をサポートしないとした場合)。 This attribute is useful for detecting "bitness" of a platform (32-bit vs 64-bit, etc.). It's recommended to not compare this attribute to some @@ -77,17 +66,14 @@ value directly, but instead count number of bits in it:: # (e.g. 31) due to peculiarities described above, so use "> 16", # "> 32", "> 64" style of comparisons. """ - modules: Dict[str, Any] -"""Dictionary of loaded modules. +"""読み込まれたモジュールの辞書。 On some ports, it may not include builtin modules.""" - path: List[str] -"""A mutable list of directories to search for imported modules.""" - +"""インポートするモジュールを検索するディレクトリの変更可能なリスト。""" platform: str -"""The platform that MicroPython is running on. +"""MicroPython が実行されているプラ\u200b\u200bットフォーム。 For OS/RTOS ports, this is usually an identifier of the OS, e.g. ``"linux"``. For baremetal ports it is an identifier of a board, e.g. ``"pyboard"`` for @@ -97,13 +83,11 @@ distinguish one board from another. If you need to check whether your program runs on MicroPython (vs other Python implementation), use ``sys.implementation`` instead. """ - version: str -"""Python language version that this implementation conforms to, as a string.""" - +"""この処理系が準拠するPython言語バージョンを表す文字列。""" version_info: Tuple[int, int, int] -"""Python language version that this implementation conforms to, as a tuple of ints. +"""この実装が準拠しているPython言語バージョンを表すintのタプル。 Only the first three version numbers (major, minor, micro) are supported and they can be referenced only by index, not by name. -""" +""" \ No newline at end of file diff --git a/lang/ja/typeshed/stdlib/time.pyi b/lang/ja/typeshed/stdlib/time.pyi index 598c483..9e894e8 100644 --- a/lang/ja/typeshed/stdlib/time.pyi +++ b/lang/ja/typeshed/stdlib/time.pyi @@ -1,132 +1,111 @@ -"""Measure time and add delays to programs. -""" - +"""時間の測定とプログラムの遅延。""" from typing import Union def sleep(seconds: Union[int, float]) -> None: - """ - Delay a number of seconds. + """指定した秒数だけ遅延します。 - Example: ``time.sleep(1)`` +Example: ``time.sleep(1)`` - :param seconds: The number of seconds to sleep for. - Use a floating-point number to sleep for a fractional number of seconds. - """ +:param seconds: スリープする秒数。 +秒より細かい精度で指定したい場合は浮動小数点数を使ってください。""" ... def sleep_ms(ms: int) -> None: - """ - Delay for given number of milliseconds. + """指定したミリ秒だけ遅延します。 - Example: ``time.sleep_ms(1_000_000)`` +Example: ``time.sleep_ms(1_000_000)`` - :param ms: The number of milliseconds delay (>= 0). - """ +:param ms: 遅延するミリ秒数(>= 0)。""" ... def sleep_us(us: int) -> None: - """ - Delay for given number of microseconds. + """指定したマイクロ秒だけ遅延します。 - Example: ``time.sleep_us(1000)`` +Example: ``time.sleep_us(1000)`` - :param us: The number of microseconds delay (>= 0). - """ +:param us: 遅延するマイクロ秒数(>= 0)。""" ... def ticks_ms() -> int: - """ - Get an increasing, millisecond counter with an arbitrary reference point, - that wraps around after some value. + """呼出し時点での稼働時間をミリ秒単位で取得します。稼働時間は最大値に達するとラップアラウンドします。 - Example: ``time.ticks_ms()`` +Example: ``time.ticks_ms()`` - :return: The counter value in milliseconds. - """ +:return: The counter value in milliseconds.""" ... def ticks_us() -> int: - """ - Get an increasing, microsecond counter with an arbitrary reference point, - that wraps around after some value. + """呼出し時点での稼働時間をマイクロ秒単位で取得します。稼働時間は最大値に達するとラップアラウンドします。 - Example: ``time.ticks_us()`` +Example: ``time.ticks_us()`` - :return: The counter value in microseconds. - """ +:return: The counter value in microseconds.""" ... def ticks_add(ticks: int, delta: int) -> int: - """ - Offset ticks value by a given number, which can be either positive or - negative. + """与えた数をティック値からのオフセットとして加算した値を返します。引数の値は正でも負でもかまいません。 - Example: ``time.ticks_add(time.ticks_ms(), 200)`` +Example: ``time.ticks_add(time.ticks_ms(), 200)`` - Given a ticks value, this function allows to calculate ticks - value delta ticks before or after it, following modular-arithmetic - definition of tick values. +Given a ticks value, this function allows to calculate ticks +value delta ticks before or after it, following modular-arithmetic +definition of tick values. - :param ticks: A ticks value - :param delta: An integer offset +:param ticks: ティック値 +:param delta: 整数オフセット - Example:: +Example:: - # Find out what ticks value there was 100ms ago - print(ticks_add(time.ticks_ms(), -100)) + # Find out what ticks value there was 100ms ago + print(ticks_add(time.ticks_ms(), -100)) - # Calculate deadline for operation and test for it - deadline = ticks_add(time.ticks_ms(), 200) - while ticks_diff(deadline, time.ticks_ms()) > 0: - do_a_little_of_something() + # Calculate deadline for operation and test for it + deadline = ticks_add(time.ticks_ms(), 200) + while ticks_diff(deadline, time.ticks_ms()) > 0: + do_a_little_of_something() - # Find out TICKS_MAX used by this port - print(ticks_add(0, -1)) - """ + # Find out TICKS_MAX used by this port + print(ticks_add(0, -1))""" ... def ticks_diff(ticks1: int, ticks2: int) -> int: - """ - Measure ticks difference between values returned from - ``time.ticks_ms()`` or ``ticks_us()``, as a signed value - which may wrap around. - - Example: ``time.ticks_diff(scheduled_time, now)`` - - :param ticks1: The value to subtract from - :param ticks2: The value to subtract - - The argument order is the same as for subtraction operator, - ``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. - - ``ticks_diff()`` is designed to accommodate various usage - patterns, among them: - - Polling with timeout. In this case, the order of events is known, and you - will deal only with positive results of :func:`time.ticks_diff()`:: - - # Wait for GPIO pin to be asserted, but at most 500us - start = time.ticks_us() - while pin.value() == 0: - if time.ticks_diff(time.ticks_us(), start) > 500: - raise TimeoutError - - - Scheduling events. In this case, :func:`time.ticks_diff()` result may be - negative if an event is overdue:: - - # This code snippet is not optimized - now = time.ticks_ms() - scheduled_time = task.scheduled_time() - if ticks_diff(scheduled_time, now) > 0: - print("Too early, let's nap") - sleep_ms(ticks_diff(scheduled_time, now)) - task.run() - elif ticks_diff(scheduled_time, now) == 0: - print("Right at time!") - task.run() - elif ticks_diff(scheduled_time, now) < 0: - print("Oops, running late, tell task to run faster!") - task.run(run_faster=True) - """ - ... + """``time.ticks_ms()`` や ``ticks_us()`` 関数の戻り値(ラップアラウンドする可能性のある符号付きの値)の間のティック値の差を計算します。 + +Example: ``time.ticks_diff(scheduled_time, now)`` + +:param ticks1: 引かられる方の値 +:param ticks2: 引く方の値 + +The argument order is the same as for subtraction operator, +``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. + +``ticks_diff()`` is designed to accommodate various usage +patterns, among them: + +Polling with timeout. In this case, the order of events is known, and you +will deal only with positive results of :func:`time.ticks_diff()`:: + + # Wait for GPIO pin to be asserted, but at most 500us + start = time.ticks_us() + while pin.value() == 0: + if time.ticks_diff(time.ticks_us(), start) > 500: + raise TimeoutError + + +Scheduling events. In this case, :func:`time.ticks_diff()` result may be +negative if an event is overdue:: + + # This code snippet is not optimized + now = time.ticks_ms() + scheduled_time = task.scheduled_time() + if ticks_diff(scheduled_time, now) > 0: + print("Too early, let's nap") + sleep_ms(ticks_diff(scheduled_time, now)) + task.run() + elif ticks_diff(scheduled_time, now) == 0: + print("Right at time!") + task.run() + elif ticks_diff(scheduled_time, now) < 0: + print("Oops, running late, tell task to run faster!") + task.run(run_faster=True)""" + ... \ No newline at end of file diff --git a/lang/ko/typeshed/stdlib/gc.pyi b/lang/ko/typeshed/stdlib/gc.pyi index 1370abf..0efcfde 100644 --- a/lang/ko/typeshed/stdlib/gc.pyi +++ b/lang/ko/typeshed/stdlib/gc.pyi @@ -1,73 +1,68 @@ -"""Control the garbage collector""" - +"""가비지 컬렉터 제어""" from typing import overload def enable() -> None: - """Enable automatic garbage collection.""" + """자동 가비지 컬렉션을 활성화합니다.""" ... def disable() -> None: - """Disable automatic garbage collection. + """자동 가비지 컬렉션을 비활성화합니다. - Heap memory can still be allocated, - and garbage collection can still be initiated manually using ``gc.collect``.""" +Heap memory can still be allocated, +and garbage collection can still be initiated manually using ``gc.collect``.""" def collect() -> None: - """Run a garbage collection.""" + """가비지 컬렉션을 실행합니다.""" ... def mem_alloc() -> int: - """Get the number of bytes of heap RAM that are allocated. + """할당된 힙 RAM의 바이트 수를 불러옵니다. - :return: The number of bytes allocated. +:return: The number of bytes allocated. - This function is MicroPython extension. - """ +This function is MicroPython extension.""" ... def mem_free() -> int: - """Get the number of bytes of available heap RAM, or -1 if this amount is not known. + """이용 가능한 힙 RAM의 바이트 수를 불러옵니다. 값을 알 수 없는 경우 -1을 반환합니다. - :return: The number of bytes free. +:return: The number of bytes free. - This function is MicroPython extension. - """ +This function is MicroPython extension.""" ... @overload def threshold() -> int: - """Query the additional GC allocation threshold. + """추가 GC 할당 임계값을 요청합니다. - :return: The GC allocation threshold. +:return: The GC allocation threshold. - This function is a MicroPython extension. CPython has a similar - function - ``set_threshold()``, but due to different GC - implementations, its signature and semantics are different. - """ +This function is a MicroPython extension. CPython has a similar +function - ``set_threshold()``, but due to different GC +implementations, its signature and semantics are different.""" ... @overload def threshold(amount: int) -> None: - """Set the additional GC allocation threshold. - - Normally, a collection is triggered only when a new allocation - cannot be satisfied, i.e. on an out-of-memory (OOM) condition. - If this function is called, in addition to OOM, a collection - will be triggered each time after ``amount`` bytes have been - allocated (in total, since the previous time such an amount of bytes - have been allocated). ``amount`` is usually specified as less than the - full heap size, with the intention to trigger a collection earlier than when the - heap becomes exhausted, and in the hope that an early collection will prevent - excessive memory fragmentation. This is a heuristic measure, the effect - of which will vary from application to application, as well as - the optimal value of the ``amount`` parameter. - - A value of -1 means a disabled allocation threshold. - - This function is a MicroPython extension. CPython has a similar - function - ``set_threshold()``, but due to different GC - implementations, its signature and semantics are different. - - :param amount: The number of bytes after which a garbage collection should be triggered. - """ - ... + """추가 GC 할당 임계값을 설정합니다. + +Normally, a collection is triggered only when a new allocation +cannot be satisfied, i.e. on an out-of-memory (OOM) condition. +If this function is called, in addition to OOM, a collection +will be triggered each time after ``amount`` bytes have been +allocated (in total, since the previous time such an amount of bytes +have been allocated). ``amount`` is usually specified as less than the +full heap size, with the intention to trigger a collection earlier than when the +heap becomes exhausted, and in the hope that an early collection will prevent +excessive memory fragmentation. This is a heuristic measure, the effect +of which will vary from application to application, as well as +the optimal value of the ``amount`` parameter. + +A value of -1 means a disabled allocation threshold. + +This function is a MicroPython extension. CPython has a similar +function - ``set_threshold()``, but due to different GC +implementations, its signature and semantics are different. + +:param amount: 가비지 컬렉션이 트리거되는 바이트 수입니다.""" + ... \ No newline at end of file diff --git a/lang/ko/typeshed/stdlib/log.pyi b/lang/ko/typeshed/stdlib/log.pyi index c9870fa..3da3957 100644 --- a/lang/ko/typeshed/stdlib/log.pyi +++ b/lang/ko/typeshed/stdlib/log.pyi @@ -1,104 +1,89 @@ -"""Log data to your micro:bit V2.""" - +"""micro:bit V2에 데이터를 기록합니다.""" from typing import Literal, Mapping, Optional, Union, overload - MILLISECONDS = 1 -"""Milliseconds timestamp format.""" - +"""밀리초 타임스탬프 형식입니다.""" SECONDS = 10 -"""Seconds timestamp format.""" - +"""초 타임스탬프 형식입니다.""" MINUTES = 600 -"""Minutes timestamp format.""" - +"""분 타임스탬프 형식입니다.""" HOURS = 36000 -"""Hours timestamp format.""" - +"""시간 타임스탬프 형식입니다.""" DAYS = 864000 -"""Days timestamp format.""" +"""일 타임스탬프 형식입니다.""" -def set_labels( - *labels: str, timestamp: Optional[Literal[1, 10, 36000, 864000]] = SECONDS -) -> None: - """Set up the log file header. +def set_labels(*labels: str, timestamp: Optional[Literal[1, 10, 36000, 864000]]=SECONDS) -> None: + """로그 파일 헤더를 설정합니다. - Example: ``log.set_labels('X', 'Y', 'Z', timestamp=log.MINUTES)`` +Example: ``log.set_labels('X', 'Y', 'Z', timestamp=log.MINUTES)`` - Ideally this function should be called a single time, before any data is - logged, to configure the data table header once. +Ideally this function should be called a single time, before any data is +logged, to configure the data table header once. - If a log file already exists when the program starts, or if this function - is called multiple times, it will check the labels already defined in the - log file. If this function call contains any new labels not already - present, it will generate a new header row with the additional columns. +If a log file already exists when the program starts, or if this function +is called multiple times, it will check the labels already defined in the +log file. If this function call contains any new labels not already +present, it will generate a new header row with the additional columns. - By default the first column contains a timestamp for each row. The time - unit can be selected via the timestamp argument. +By default the first column contains a timestamp for each row. The time +unit can be selected via the timestamp argument. - :param *labels: Any number of positional arguments, each corresponding to an entry in the log header. - :param timestamp: Select the timestamp unit that will be automatically added as the first column in every row. Timestamp values can be one of ``log.MILLISECONDS``, ``log.SECONDS``, ``log.MINUTES``, ``log.HOURS``, ``log.DAYS`` or ``None`` to disable the timestamp. The default value is ``log.SECONDS``. - """ +:param *labels: (*레이블) 각각 로그 헤더의 항목에 해당하는 임의의 위치 인수 수입니다. +:param timestamp: (타임스탬프) 모든 행의 첫 번째에 자동으로 삽입될 타임스탬프 단위를 선택하십시오. 타임스탬프의 값은 ``log.MILLISECONDS``, ``log.SECONDS``, ``log.MINUTES``, ``log.HOURS``, ``log.DAYS``가 될 수 있고 비활성화하려면 ``None``값으로 설정하십시오. 타임스탬프의 기본값은 ``log.SECONDS``입니다.""" ... @overload -def add( - data_dictionary: Optional[Mapping[str, Union[str, int, float]]], -) -> None: - """Add a data row to the log by passing a dictionary of headers and values. +def add(data_dictionary: Optional[Mapping[str, Union[str, int, float]]]) -> None: + """헤더 및 값의 딕셔너리를 패스해 로그에 데이터 행을 추가합니다. - Example: ``log.add({ 'temp': temperature() })`` +Example: ``log.add({ 'temp': temperature() })`` - Each call to this function adds a row to the log. +Each call to this function adds a row to the log. - New labels not previously specified via the set_labels function, or by a - previous call to this function, will trigger a new header entry to be added - to the log with the extra labels. +New labels not previously specified via the set_labels function, or by a +previous call to this function, will trigger a new header entry to be added +to the log with the extra labels. - Labels previously specified and not present in a call to this function will - be skipped with an empty value in the log row. +Labels previously specified and not present in a call to this function will +be skipped with an empty value in the log row. - :param data_dictionary: The data to log as a dictionary with a key for each header. - """ +:param data_dictionary: (데이터 사전) 각 헤더에 대한 키가 있는 사전으로 기록할 데이터입니다.""" ... @overload def add(**kwargs: Union[str, int, float]) -> None: - """Add a data row to the log using keyword arguments. + """키워드 인자를 사용해 로그에 데이터 행을 추가합니다. - Example: ``log.add(temp=temperature())`` +Example: ``log.add(temp=temperature())`` - Each call to this function adds a row to the log. +Each call to this function adds a row to the log. - New labels not previously specified via the set_labels function, or by a - previous call to this function, will trigger a new header entry to be added - to the log with the extra labels. +New labels not previously specified via the set_labels function, or by a +previous call to this function, will trigger a new header entry to be added +to the log with the extra labels. - Labels previously specified and not present in a call to this function will - be skipped with an empty value in the log row. - """ +Labels previously specified and not present in a call to this function will +be skipped with an empty value in the log row.""" ... def delete(full=False): - """Deletes the contents of the log, including headers. + """헤더를 포함한 로그의 내용을 삭제합니다. - Example: ``log.delete()`` +Example: ``log.delete()`` - To add the log headers again the ``set_labels`` function should to be called after this function. +To add the log headers again the ``set_labels`` function should to be called after this function. - There are two erase modes; “full” completely removes the data from the physical storage, - and “fast” invalidates the data without removing it. +There are two erase modes; “full” completely removes the data from the physical storage, +and “fast” invalidates the data without removing it. - :param full: ``True`` selects a “full” erase and ``False`` selects the “fast” erase method. - """ +:param full: ``True``는 "전체" 지우기를 선택하고 ``False``는 "빠른" 지우기 방법을 선택합니다.""" ... def set_mirroring(serial: bool): - """Configure mirroring of the data logging activity to the serial output. + """직렬 출력에 대한 데이터 로깅 작업 미러링을 구성합니다. - Example: ``log.set_mirroring(True)`` +Example: ``log.set_mirroring(True)`` - Serial mirroring is disabled by default. When enabled, it will print to serial each row logged into the log file. +Serial mirroring is disabled by default. When enabled, it will print to serial each row logged into the log file. - :param serial: ``True`` enables mirroring data to the serial output. - """ - ... +:param serial: ``True``로 설정할 경우 시리얼 출력 인터페이스에 데이터를 미러링하는 것이 허용됩니다.""" + ... \ No newline at end of file diff --git a/lang/ko/typeshed/stdlib/machine.pyi b/lang/ko/typeshed/stdlib/machine.pyi index 2e82f5b..97f92aa 100644 --- a/lang/ko/typeshed/stdlib/machine.pyi +++ b/lang/ko/typeshed/stdlib/machine.pyi @@ -1,97 +1,84 @@ -"""Low-level utilities. -""" +"""로우 레벨 유틸리티입니다.""" from typing import Any from .microbit import MicroBitDigitalPin def unique_id() -> bytes: - """Get a byte string with a unique identifier of a board. + """보드의 고유 식별자가 있는 바이트 문자열을 불러옵니다. - Example: ``machine.unique_id()`` +Example: ``machine.unique_id()`` - :return: An identifier that varies from one board instance to another. - """ +:return: An identifier that varies from one board instance to another.""" ... def reset() -> None: - """Reset the device in a manner similar to pushing the external RESET button. + """외부 초기화 버튼을 누른 것과 유사한 방식으로 기기를 초기화합니다. - Example: ``machine.reset()`` - """ +Example: ``machine.reset()``""" ... def freq() -> int: - """Get the CPU frequency in hertz. + """헤르츠로 표시된 CPU 진동수를 불러옵니다. - Example: ``machine.freq()`` +Example: ``machine.freq()`` - :return: The CPU frequency. - """ +:return: The CPU frequency.""" ... def disable_irq() -> Any: - """Disable interrupt requests. + """인터럽트 요청을 비활성화합니다. - Example: ``interrupt_state = machine.disable_irq()`` +Example: ``interrupt_state = machine.disable_irq()`` - :return: the previous IRQ state which should be considered an opaque value +:return: the previous IRQ state which should be considered an opaque value - The return value should be passed to the ``enable_irq`` function to restore - interrupts to their original state. - """ +The return value should be passed to the ``enable_irq`` function to restore +interrupts to their original state.""" ... def enable_irq(state: Any) -> None: - """Re-enable interrupt requests. + """인터럽트 요청을 재활성화합니다. - Example: ``machine.enable_irq(interrupt_state)`` +Example: ``machine.enable_irq(interrupt_state)`` - :param state: The value that was returned from the most recent call to the ``disable_irq`` function. - """ +:param state: ``disable_irq`` 함수에서 가장 최근에 호출된 값을 반환합니다.""" ... -def time_pulse_us( - pin: MicroBitDigitalPin, pulse_level: int, timeout_us: int = 1000000 -) -> int: - """Time a pulse on a pin. +def time_pulse_us(pin: MicroBitDigitalPin, pulse_level: int, timeout_us: int=1000000) -> int: + """핀 펄스 시간을 측정합니다. - Example: ``time_pulse_us(pin0, 1)`` +Example: ``time_pulse_us(pin0, 1)`` - If the current input value of the pin is different to ``pulse_level``, the - function first waits until the pin input becomes equal to - ``pulse_level``, then times the duration that the pin is equal to - ``pulse_level``. If the pin is already equal to ``pulse_level`` then timing - starts straight away. +If the current input value of the pin is different to ``pulse_level``, the +function first waits until the pin input becomes equal to +``pulse_level``, then times the duration that the pin is equal to +``pulse_level``. If the pin is already equal to ``pulse_level`` then timing +starts straight away. - :param pin: The pin to use - :param pulse_level: 0 to time a low pulse or 1 to time a high pulse - :param timeout_us: A microsecond timeout - :return: The duration of the pulse in microseconds, or -1 for a timeout waiting for the level to match ``pulse_level``, or -2 on timeout waiting for the pulse to end - """ +:param pin: (핀) 사용할 핀 +:param pulse_level: (펄스 레벨) 로우 펄스의 시간을 측정하려면 0, 하이 펄스는 1 +:param timeout_us: 마이크로초 시간 초과 +:return: The duration of the pulse in microseconds, or -1 for a timeout waiting for the level to match ``pulse_level``, or -2 on timeout waiting for the pulse to end""" ... class mem: - """The class for the ``mem8``, ``mem16`` and ``mem32`` memory views.""" + """``mem8``, ``mem16``, ``mem32`` 메모리 뷰 클래스""" def __getitem__(self, address: int) -> int: - """Access a value from memory. + """메모리 값에 액세스합니다. - :param address: The memory address. - :return: The value at that address as an integer. - """ +:param address: 메모리 주소입니다. +:return: The value at that address as an integer.""" ... + def __setitem__(self, address: int, value: int) -> None: - """Set a value at the given address. + """제공된 주소에 값을 설정합니다. - :param address: The memory address. - :param value: The integer value to set. - """ +:param address: 메모리 주소입니다. +:param value: 설정할 정수값입니다.""" ... - mem8: mem -"""8-bit (byte) view of memory.""" - +"""8비트(바이트) 메모리 뷰입니다.""" mem16: mem -"""16-bit view of memory.""" - +"""16비트 메모리 뷰입니다.""" mem32: mem -"""32-bit view of memory.""" +"""32비트 메모리 뷰입니다.""" \ No newline at end of file diff --git a/lang/ko/typeshed/stdlib/math.pyi b/lang/ko/typeshed/stdlib/math.pyi index f82d4de..bb2dc94 100644 --- a/lang/ko/typeshed/stdlib/math.pyi +++ b/lang/ko/typeshed/stdlib/math.pyi @@ -1,273 +1,246 @@ -"""Mathematical functions. -""" - +"""수학 함수입니다.""" from typing import Tuple def acos(x: float) -> float: - """Calculate the inverse cosine. + """코사인의 역을 계산합니다. - Example: ``math.acos(1)`` +Example: ``math.acos(1)`` - :param x: A number - :return: The inverse cosine of ``x`` - """ +:param x: 숫자 +:return: The inverse cosine of ``x``""" ... def asin(x: float) -> float: - """Calculate the inverse sine. + """사인의 역을 계산합니다. - Example: ``math.asin(0)`` +Example: ``math.asin(0)`` - :param x: A number - :return: The inverse sine of ``x`` - """ +:param x: 숫자 +:return: The inverse sine of ``x``""" ... def atan(x: float) -> float: - """Calculate the inverse tangent. + """탄젠트의 역을 계산합니다. - Example: ``math.atan(0)`` +Example: ``math.atan(0)`` - :param x: A number - :return: The inverse tangent of ``x`` - """ +:param x: 숫자 +:return: The inverse tangent of ``x``""" ... def atan2(y: float, x: float) -> float: - """Calculate the principal value of the inverse tangent of ``y/x``. + """``y/x``의 역 탄젠트의 주 값을 계산합니다. - Example: ``math.atan2(0, -1)`` +Example: ``math.atan2(0, -1)`` - :param y: A number - :param x: A number - :return: The principal value of the inverse tangent of ``y/x`` - """ +:param y: 숫자 +:param x: 숫자 +:return: The principal value of the inverse tangent of ``y/x``""" ... def ceil(x: float) -> float: - """Round a number towards positive infinity. + """양의 무한대로 숫자를 반올림합니다. - Example: ``math.ceil(0.1)`` +Example: ``math.ceil(0.1)`` - :param x: A number - :return: ``x`` rounded towards positive infinity. - """ +:param x: 숫자 +:return: ``x`` rounded towards positive infinity.""" ... def copysign(x: float, y: float) -> float: - """Calculate ``x`` with the sign of ``y``. + """``y``의 사인 값으로 ``x``를 계산합니다. - Example: ``math.copysign(1, -1)`` +Example: ``math.copysign(1, -1)`` - :param x: A number - :param y: The source of the sign for the return value - :return: ``x`` with the sign of ``y`` - """ +:param x: 숫자 +:param y: 반환값의 사인의 출처 +:return: ``x`` with the sign of ``y``""" ... def cos(x: float) -> float: - """Calculate the cosine of ``x``. + """``x``의 코사인을 계산합니다. - Example: ``math.cos(0)`` +Example: ``math.cos(0)`` - :param x: A number - :return: The cosine of ``x`` - """ +:param x: 숫자 +:return: The cosine of ``x``""" ... def degrees(x: float) -> float: - """Convert radians to degrees. + """호도법을 각도법으로 변환합니다. (도) - Example: ``math.degrees(2 * math.pi)`` +Example: ``math.degrees(2 * math.pi)`` - :param x: A value in radians - :return: The value converted to degrees""" +:param x: 호도법 값 +:return: The value converted to degrees""" ... def exp(x: float) -> float: - """Calculate the exponential of ``x``. + """``x``의 지수를 계산합니다. - Example: ``math.exp(1)`` +Example: ``math.exp(1)`` - :param x: A number - :return: The exponential of ``x``. - """ +:param x: 숫자 +:return: The exponential of ``x``.""" ... def fabs(x: float) -> float: - """Return the absolute value of ``x``. + """``x``의 절댓값을 반환합니다. - Example: ``math.fabs(-0.1)`` +Example: ``math.fabs(-0.1)`` - :param x: A number - :return: The absolute value of ``x`` - """ +:param x: 숫자 +:return: The absolute value of ``x``""" ... def floor(x: float) -> int: - """Round a number towards negative infinity. + """음의 무한대로 숫자를 반올림합니다. - Example: ``math.floor(0.9)`` +Example: ``math.floor(0.9)`` - :param x: A number - :return: ``x`` rounded towards negative infinity. - """ +:param x: 숫자 +:return: ``x`` rounded towards negative infinity.""" ... def fmod(x: float, y: float) -> float: - """Calculate the remainder of ``x/y``. + """``x/y``의 나머지를 계산합니다. - Example: ``math.fmod(10, 3)`` +Example: ``math.fmod(10, 3)`` - :param x: The numerator - :param y: The denominator - """ +:param x: 분자 +:param y: 분모""" ... def frexp(x: float) -> Tuple[float, int]: - """Decomposes a floating-point number into its mantissa and exponent. + """부동 소수점 수를 가수와 지수로 분해합니다. - Example: ``mantissa, exponent = math.frexp(2)`` +Example: ``mantissa, exponent = math.frexp(2)`` - The returned value is the tuple ``(m, e)`` such that ``x == m * 2**e`` - exactly. If ``x == 0`` then the function returns ``(0.0, 0)``, otherwise - the relation ``0.5 <= abs(m) < 1`` holds. +The returned value is the tuple ``(m, e)`` such that ``x == m * 2**e`` +exactly. If ``x == 0`` then the function returns ``(0.0, 0)``, otherwise +the relation ``0.5 <= abs(m) < 1`` holds. - :param x: A floating-point number - :return: A tuple of length two containing its mantissa then exponent - """ +:param x: 부동 소수점 수 +:return: A tuple of length two containing its mantissa then exponent""" ... def isfinite(x: float) -> bool: - """Check if a value is finite. + """값이 유한값인지 확인합니다. - Example: ``math.isfinite(float('inf'))`` +Example: ``math.isfinite(float('inf'))`` - :param x: A number. - :return: ``True`` if ``x`` is finite, ``False`` otherwise. - """ +:param x: 숫자입니다. +:return: ``True`` if ``x`` is finite, ``False`` otherwise.""" ... def isinf(x: float) -> bool: - """Check if a value is infinite. + """값이 무한인지 확인합니다. - Example: ``math.isinf(float('-inf'))`` +Example: ``math.isinf(float('-inf'))`` - :param x: A number. - :return: ``True`` if ``x`` is infinite, ``False`` otherwise. - """ +:param x: 숫자입니다. +:return: ``True`` if ``x`` is infinite, ``False`` otherwise.""" ... def isnan(x: float) -> bool: - """Check if a value is not-a-number (NaN). + """값이 숫자가 아닌 값(NaN)인지 확인합니다. - Example: ``math.isnan(float('nan'))`` +Example: ``math.isnan(float('nan'))`` - :param x: A number - :return: ``True`` if ``x`` is not-a-number (NaN), ``False`` otherwise.""" +:param x: 숫자 +:return: ``True`` if ``x`` is not-a-number (NaN), ``False`` otherwise.""" ... def ldexp(x: float, exp: int) -> float: - """Calculate ``x * (2**exp)``. + """``x * (2**exp)``를 계산합니다. - Example: ``math.ldexp(0.5, 2)`` +Example: ``math.ldexp(0.5, 2)`` - :param x: A number - :param exp: Integer exponent - :return: ``x * (2**exp)`` - """ +:param x: 숫자 +:param exp: 정수 지수 +:return: ``x * (2**exp)``""" ... -def log(x: float, base: float = e) -> float: - """Calculate the logarithm of ``x`` to the given base (defaults to natural logorithm). +def log(x: float, base: float=e) -> float: + """``x``의 로그를 주어진 베이스에 따라 계산합니다(기본값은 자연로그). - Example: ``math.log(math.e)`` +Example: ``math.log(math.e)`` - With one argument, return the natural logarithm of x (to base e). +With one argument, return the natural logarithm of x (to base e). - With two arguments, return the logarithm of x to the given base, calculated as ``log(x)/log(base)``. +With two arguments, return the logarithm of x to the given base, calculated as ``log(x)/log(base)``. - :param x: A number - :param base: The base to use - :return: The natural logarithm of ``x`` - """ +:param x: 숫자 +:param base: 사용할 베이스 +:return: The natural logarithm of ``x``""" ... def modf(x: float) -> Tuple[float, float]: - """Calculate the fractional and integral parts of ``x``. + """``x``의 분수 및 정수 부분을 계산합니다. - Example: ``fractional, integral = math.modf(1.5)`` +Example: ``fractional, integral = math.modf(1.5)`` - :param x: A number - :return: A tuple of two floats representing the fractional then integral parts of ``x``. +:param x: 숫자 +:return: A tuple of two floats representing the fractional then integral parts of ``x``. - Both the fractional and integral values have the same sign as ``x``. - """ +Both the fractional and integral values have the same sign as ``x``.""" ... def pow(x: float, y: float) -> float: - """Returns ``x`` to the power of ``y``. + """``y``의 제곱을 ``x``(으)로 반환합니다. - Example: ``math.pow(4, 0.5)`` +Example: ``math.pow(4, 0.5)`` - :param x: A number - :param y: The exponent - :return: ``x`` to the power of ``y`` - """ +:param x: 숫자 +:param y: 지수 +:return: ``x`` to the power of ``y``""" ... def radians(x: float) -> float: - """Convert a degrees to radians. + """각도법을 호도법으로 변환합니다. - Example: ``math.radians(360)`` +Example: ``math.radians(360)`` - :param x: A value in degrees - :return: The value converted to radians - """ +:param x: 각도법 값 +:return: The value converted to radians""" ... def sin(x: float) -> float: - """Calculate the sine of ``x``. + """``x``의 사인을 계산합니다. - Example: ``math.sin(math.pi/2)`` +Example: ``math.sin(math.pi/2)`` - :param x: A number - :return: The sine of ``x`` - """ +:param x: 숫자 +:return: The sine of ``x``""" ... def sqrt(x: float) -> float: - """Calculate the square root of ``x``. + """``x``의 제곱근을 계산합니다. - Example: ``math.sqrt(4)`` +Example: ``math.sqrt(4)`` - :param x: A number - :return: The square root of ``x`` - """ +:param x: 숫자 +:return: The square root of ``x``""" ... def tan(x: float) -> float: - """Calculate the tangent of ``x``. + """``x``의 탄젠트를 계산합니다. - Example: ``math.tan(0)`` +Example: ``math.tan(0)`` - :param x: A number - :return: The tangent of ``x``. - """ +:param x: 숫자 +:return: The tangent of ``x``.""" ... def trunc(x: float) -> int: - """Round a number towards 0. + """숫자를 0으로 반올림합니다. - Example: ``math.trunc(-0.9)`` +Example: ``math.trunc(-0.9)`` - :param x: A number - :return: ``x`` rounded towards zero. - """ +:param x: 숫자 +:return: ``x`` rounded towards zero.""" ... - e: float -"""Base of the natural logarithm""" - +"""자연 알고리즘 베이스""" pi: float -"""The ratio of a circle's circumference to its diameter""" +"""원의 원주와 지름의 비율""" \ No newline at end of file diff --git a/lang/ko/typeshed/stdlib/microbit/__init__.pyi b/lang/ko/typeshed/stdlib/microbit/__init__.pyi index f12158f..1c64b85 100644 --- a/lang/ko/typeshed/stdlib/microbit/__init__.pyi +++ b/lang/ko/typeshed/stdlib/microbit/__init__.pyi @@ -1,11 +1,6 @@ -"""Pins, images, sounds, temperature and volume. -""" - +"""핀, 이미지, 소리, 온도 및 음량입니다.""" from typing import Any, Callable, List, Optional, Tuple, Union, overload - from _typeshed import ReadableBuffer - -# V2 only from . import accelerometer as accelerometer from . import audio as audio from . import compass as compass @@ -16,831 +11,696 @@ from . import speaker as speaker from . import spi as spi from . import uart as uart -def run_every( - callback: Optional[Callable[[], None]] = None, - days: int = 0, - h: int = 0, - min: int = 0, - s: int = 0, - ms: int = 0, -) -> Callable[[Callable[[], None]], Callable[[], None]]: - """Schedule to run a function at the interval specified by the time arguments **V2 only**. +def run_every(callback: Optional[Callable[[], None]]=None, days: int=0, h: int=0, min: int=0, s: int=0, ms: int=0) -> Callable[[Callable[[], None]], Callable[[], None]]: + """매개 변수로 주어진 일정한 시간(밀리초, ms)마다 특정 함수를 호출합니다. **micro:bit V2 전용** - Example: ``run_every(my_logging, min=5)`` +Example: ``run_every(my_logging, min=5)`` - ``run_every`` can be used in two ways: +``run_every`` can be used in two ways: - As a Decorator - placed on top of the function to schedule. For example:: +As a Decorator - placed on top of the function to schedule. For example:: - @run_every(h=1, min=20, s=30, ms=50) - def my_function(): - # Do something here + @run_every(h=1, min=20, s=30, ms=50) + def my_function(): + # Do something here - As a Function - passing the callback as a positional argument. For example:: +As a Function - passing the callback as a positional argument. For example:: - def my_function(): - # Do something here - run_every(my_function, s=30) + def my_function(): + # Do something here + run_every(my_function, s=30) - Each argument corresponds to a different time unit and they are additive. - So ``run_every(min=1, s=30)`` schedules the callback every minute and a half. +Each argument corresponds to a different time unit and they are additive. +So ``run_every(min=1, s=30)`` schedules the callback every minute and a half. - When an exception is thrown inside the callback function it deschedules the - function. To avoid this you can catch exceptions with ``try/except``. +When an exception is thrown inside the callback function it deschedules the +function. To avoid this you can catch exceptions with ``try/except``. - :param callback: Function to call at the provided interval. Omit when using as a decorator. - :param days: Sets the day mark for the scheduling. - :param h: Sets the hour mark for the scheduling. - :param min: Sets the minute mark for the scheduling. - :param s: Sets the second mark for the scheduling. - :param ms: Sets the millisecond mark for the scheduling. - """ +:param callback: 주어진 시간이 되었을 때 호출할 함수. 데코레이터(장식자)로 사용할 때 호출. +:param days: 함수 호출 반복 시간의 날 단위를 정합니다. +:param h: 함수 호출 반복 시간의 시간 단위를 정합니다. +:param min: 함수 호출 반복 시간의 분 단위를 정합니다. +:param s: 함수 호출 반복 시간의 초 단위를 정합니다. +:param ms: 함수 호출 반복 시간의 밀리초 단위를 정합니다.""" def panic(n: int) -> None: - """Enter a panic mode. + """패닉 모드를 활성화합니다. - Example: ``panic(127)`` +Example: ``panic(127)`` - :param n: An arbitrary integer <= 255 to indicate a status. +:param n: <= 255의 임의 정수로 상태를 표시합니다. - Requires restart. - """ +Requires restart.""" def reset() -> None: - """Restart the board.""" - + """보드를 재시작합니다.""" @overload def scale(value: float, from_: Tuple[float, float], to: Tuple[int, int]) -> int: """Converts a value from a range to an integer range. - Example: ``volume = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255))`` +Example: ``volume = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255))`` - For example, to convert an accelerometer X value to a speaker volume. +For example, to convert an accelerometer X value to a speaker volume. - If one of the numbers in the ``to`` parameter is a floating point - (i.e a decimal number like ``10.0``), this function will return a - floating point number. +If one of the numbers in the ``to`` parameter is a floating point +(i.e a decimal number like ``10.0``), this function will return a +floating point number. - temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0)) + temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0)) - :param value: A number to convert. - :param from_: A tuple to define the range to convert from. - :param to: A tuple to define the range to convert to. - :return: The ``value`` converted to the ``to`` range. - """ +:param value: A number to convert. +:param from_: 변환할 범위를 정의할 튜플 값 +:param to: A tuple to define the range to convert to. +:return: The ``value`` converted to the ``to`` range.""" @overload def scale(value: float, from_: Tuple[float, float], to: Tuple[float, float]) -> float: """Converts a value from a range to a floating point range. - Example: ``temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0))`` +Example: ``temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0))`` - For example, to convert temperature from a Celsius scale to Fahrenheit. +For example, to convert temperature from a Celsius scale to Fahrenheit. - If one of the numbers in the ``to`` parameter is a floating point - (i.e a decimal number like ``10.0``), this function will return a - floating point number. - If they are both integers (i.e ``10``), it will return an integer:: +If one of the numbers in the ``to`` parameter is a floating point +(i.e a decimal number like ``10.0``), this function will return a +floating point number. +If they are both integers (i.e ``10``), it will return an integer:: - returns_int = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255)) + returns_int = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255)) - :param value: A number to convert. - :param from_: A tuple to define the range to convert from. - :param to: A tuple to define the range to convert to. - :return: The ``value`` converted to the ``to`` range. - """ +:param value: A number to convert. +:param from_: 변환할 범위를 정의할 튜플 값 +:param to: A tuple to define the range to convert to. +:return: The ``value`` converted to the ``to`` range.""" def sleep(n: float) -> None: - """Wait for ``n`` milliseconds. + """``n``밀리초 동안 대기합니다. - Example: ``sleep(1000)`` +Example: ``sleep(1000)`` - :param n: The number of milliseconds to wait +:param n: 대기할 밀리초 수 - One second is 1000 milliseconds, so:: +One second is 1000 milliseconds, so:: - microbit.sleep(1000) + microbit.sleep(1000) - will pause the execution for one second. - """ +will pause the execution for one second.""" def running_time() -> int: - """Get the running time of the board. + """보드의 실행 시간을 불러옵니다. - :return: The number of milliseconds since the board was switched on or restarted. - """ +:return: The number of milliseconds since the board was switched on or restarted.""" def temperature() -> int: - """Get the temperature of the micro:bit in degrees Celsius.""" + """섭씨로 micro:bit의 온도를 불러옵니다. (온도)""" def set_volume(v: int) -> None: - """Sets the volume. + """음량을 설정합니다. - Example: ``set_volume(127)`` +Example: ``set_volume(127)`` - :param v: a value between 0 (low) and 255 (high). +:param v: 0(낮음) 및 255(높음) 사이의 값입니다. - Out of range values will be clamped to 0 or 255. +Out of range values will be clamped to 0 or 255. - **V2** only. - """ +**V2** only.""" ... class Button: - """The class for the buttons ``button_a`` and ``button_b``.""" + """``button_a`` 및 ``button_b`` 버튼 클래스입니다.""" def is_pressed(self) -> bool: - """Check if the button is pressed. + """해당 버튼이 눌렸는지 확인합니다. - :return: ``True`` if the specified button ``button`` is pressed, and ``False`` otherwise. - """ +:return: ``True`` if the specified button ``button`` is pressed, and ``False`` otherwise.""" ... + def was_pressed(self) -> bool: - """Check if the button was pressed since the device started or the last time this method was called. + """장치가 시작한 후 또는 이 메서드가 호출된 후 해당 버튼이 눌렸는지 확인합니다. - Calling this method will clear the press state so - that the button must be pressed again before this method will return - ``True`` again. +Calling this method will clear the press state so +that the button must be pressed again before this method will return +``True`` again. - :return: ``True`` if the specified button ``button`` was pressed, and ``False`` otherwise - """ +:return: ``True`` if the specified button ``button`` was pressed, and ``False`` otherwise""" ... + def get_presses(self) -> int: - """Get the running total of button presses, and resets this total - to zero before returning. + """버튼이 눌린 총 횟수를 불러오고, 총값을 반환하기 전 초기화합니다. - :return: The number of presses since the device started or the last time this method was called - """ +:return: The number of presses since the device started or the last time this method was called""" ... - button_a: Button -"""The left button ``Button`` object.""" - +"""왼쪽 버튼 ``Button`` 개체입니다.""" button_b: Button -"""The right button ``Button`` object.""" +"""오른쪽 버튼 ``Button`` 개체입니다.""" class MicroBitDigitalPin: - """A digital pin. - - Some pins support analog and touch features using the ``MicroBitAnalogDigitalPin`` and ``MicroBitTouchPin`` subclasses. - """ + """디지털 핀입니다. +Some pins support analog and touch features using the ``MicroBitAnalogDigitalPin`` and ``MicroBitTouchPin`` subclasses.""" NO_PULL: int PULL_UP: int PULL_DOWN: int + def read_digital(self) -> int: - """Get the digital value of the pin. + """핀의 디지털 값을 불러옵니다. - Example: ``value = pin0.read_digital()`` +Example: ``value = pin0.read_digital()`` - :return: 1 if the pin is high, and 0 if it's low. - """ +:return: 1 if the pin is high, and 0 if it's low.""" ... + def write_digital(self, value: int) -> None: - """Set the digital value of the pin. + """핀의 디지털 값을 설정합니다. - Example: ``pin0.write_digital(1)`` +Example: ``pin0.write_digital(1)`` - :param value: 1 to set the pin high or 0 to set the pin low""" +:param value: 핀을 하이로 설정하려면 1, 로우로 설정하려면 0""" ... + def set_pull(self, value: int) -> None: - """Set the pull state to one of three possible values: ``PULL_UP``, ``PULL_DOWN`` or ``NO_PULL``. + """다음 중 하나의 값으로 풀 상태를 설정: ``PULL_UP``, ``PULL_DOWN`` 또는 ``NO_PULL`` - Example: ``pin0.set_pull(pin0.PULL_UP)`` +Example: ``pin0.set_pull(pin0.PULL_UP)`` - :param value: The pull state from the relevant pin, e.g. ``pin0.PULL_UP``. - """ +:param value: 관련 핀의 풀 상태입니다. (예: ``pin0.PULL_UP``)""" ... + def get_pull(self) -> int: - """Get the pull state on a pin. + """핀의 풀 상태를 불러옵니다. - Example: ``pin0.get_pull()`` +Example: ``pin0.get_pull()`` - :return: ``NO_PULL``, ``PULL_DOWN``, or ``PULL_UP`` +:return: ``NO_PULL``, ``PULL_DOWN``, or ``PULL_UP`` - These are set using the ``set_pull()`` method or automatically configured - when a pin mode requires it. - """ +These are set using the ``set_pull()`` method or automatically configured +when a pin mode requires it.""" ... + def get_mode(self) -> str: - """Returns the pin mode. + """핀 모드를 반환합니다. - Example: ``pin0.get_mode()`` +Example: ``pin0.get_mode()`` - When a pin is used for a specific function, like - writing a digital value, or reading an analog value, the pin mode - changes. +When a pin is used for a specific function, like +writing a digital value, or reading an analog value, the pin mode +changes. - :return: ``"unused"``, ``"analog"``, ``"read_digital"``, ``"write_digital"``, ``"display"``, ``"button"``, ``"music"``, ``"audio"``, ``"touch"``, ``"i2c"``, or ``"spi"`` - """ +:return: ``"unused"``, ``"analog"``, ``"read_digital"``, ``"write_digital"``, ``"display"``, ``"button"``, ``"music"``, ``"audio"``, ``"touch"``, ``"i2c"``, or ``"spi"``""" ... + def write_analog(self, value: int) -> None: - """Output a PWM signal on the pin, with the duty cycle proportional to ``value``. + """핀의 PWM 신호를 출력하고 ``value``와(과) 비례해 듀티 사이클을 설정합니다. + +Example: ``pin0.write_analog(254)`` - Example: ``pin0.write_analog(254)`` +:param value: 0(0% 듀티 사이클) 및 1023(100% 듀티) 사이의 정수 또는 부동 소수점 수입니다.""" - :param value: 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. + """PWM 신호가 출력되는 주기를 ``period``밀리초로 설정합니다. - Example: ``pin0.set_analog_period(10)`` +Example: ``pin0.set_analog_period(10)`` + +:param period: 유효한 최소값이 1ms인 밀리초 주기입니다.""" - :param period: The period in milliseconds with a minimum valid value of 1ms. - """ def set_analog_period_microseconds(self, period: int) -> None: - """Set the period of the PWM signal being output to ``period`` in microseconds. + """PWM 신호가 출력되는 주기를 ``period``마이크로초로 설정합니다. - Example: ``pin0.set_analog_period_microseconds(512)`` +Example: ``pin0.set_analog_period_microseconds(512)`` - :param period: The period in microseconds with a minimum valid value of 256µs. - """ +:param period: 유효한 최소값이 256µs인 마이크로초 주기입니다.""" class MicroBitAnalogDigitalPin(MicroBitDigitalPin): - """A pin with analog and digital features.""" + """아날로그 및 디지털 기능이 있는 핀입니다.""" def read_analog(self) -> int: - """Read the voltage applied to the pin. + """핀에 적용된 전압을 읽습니다. - Example: ``pin0.read_analog()`` +Example: ``pin0.read_analog()`` - :return: An integer between 0 (meaning 0V) and 1023 (meaning 3.3V). - """ +:return: An integer between 0 (meaning 0V) and 1023 (meaning 3.3V).""" class MicroBitTouchPin(MicroBitAnalogDigitalPin): - """A pin with analog, digital and touch features.""" - + """아날로그, 디지털, 터치 기능이 있는 핀입니다.""" CAPACITIVE: int RESISTIVE: int + def is_touched(self) -> bool: - """Check if the pin is being touched. + """핀이 접촉 상태인지 확인합니다. - Example: ``pin0.is_touched()`` +Example: ``pin0.is_touched()`` - The default touch mode for the pins on the edge connector is ``resistive``. - The default for the logo pin **V2** is ``capacitive``. +The default touch mode for the pins on the edge connector is ``resistive``. +The default for the logo pin **V2** is ``capacitive``. - **Resistive touch** - This test is done by measuring how much resistance there is between the - pin and ground. A low resistance gives a reading of ``True``. To get - a reliable reading using a finger you may need to touch the ground pin - with another part of your body, for example your other hand. +**Resistive touch** +This test is done by measuring how much resistance there is between the +pin and ground. A low resistance gives a reading of ``True``. To get +a reliable reading using a finger you may need to touch the ground pin +with another part of your body, for example your other hand. - **Capacitive touch** - This test is done by interacting with the electric field of a capacitor - using a finger as a conductor. `Capacitive touch - `_ - does not require you to make a ground connection as part of a circuit. +**Capacitive touch** +This test is done by interacting with the electric field of a capacitor +using a finger as a conductor. `Capacitive touch +`_ +does not require you to make a ground connection as part of a circuit. - :return: ``True`` if the pin is being touched with a finger, otherwise return ``False``. - """ +:return: ``True`` if the pin is being touched with a finger, otherwise return ``False``.""" ... + def set_touch_mode(self, value: int) -> None: - """Set the touch mode for the pin. + """핀의 터치 모드를 설정합니다. - Example: ``pin0.set_touch_mode(pin0.CAPACITIVE)`` +Example: ``pin0.set_touch_mode(pin0.CAPACITIVE)`` - The default touch mode for the pins on the edge connector is - ``resistive``. The default for the logo pin **V2** is ``capacitive``. +The default touch mode for the pins on the edge connector is +``resistive``. The default for the logo pin **V2** is ``capacitive``. - :param value: ``CAPACITIVE`` or ``RESISTIVE`` from the relevant pin. - """ +:param value: 관련 핀의 ``CAPACITIVE`` 또는 ``RESISTIVE``입니다.""" ... - pin0: MicroBitTouchPin -"""Pin with digital, analog and touch features.""" - +"""디지털 및 아날로그, 터치 기능이 있는 핀입니다.""" pin1: MicroBitTouchPin -"""Pin with digital, analog and touch features.""" - +"""디지털 및 아날로그, 터치 기능이 있는 핀입니다.""" pin2: MicroBitTouchPin -"""Pin with digital, analog and touch features.""" - +"""디지털 및 아날로그, 터치 기능이 있는 핀입니다.""" pin3: MicroBitAnalogDigitalPin -"""Pin with digital and analog features.""" - +"""디지털 및 아날로그 기능이 있는 핀입니다.""" pin4: MicroBitAnalogDigitalPin -"""Pin with digital and analog features.""" - +"""디지털 및 아날로그 기능이 있는 핀입니다.""" pin5: MicroBitDigitalPin -"""Pin with digital features.""" - +"""디지털 기능이 있는 핀입니다. (pin speaker)""" pin6: MicroBitDigitalPin -"""Pin with digital features.""" - +"""디지털 기능이 있는 핀입니다.""" pin7: MicroBitDigitalPin -"""Pin with digital features.""" - +"""디지털 기능이 있는 핀입니다.""" pin8: MicroBitDigitalPin -"""Pin with digital features.""" - +"""디지털 기능이 있는 핀입니다.""" pin9: MicroBitDigitalPin -"""Pin with digital features.""" - +"""디지털 기능이 있는 핀입니다.""" pin10: MicroBitAnalogDigitalPin -"""Pin with digital and analog features.""" - +"""디지털 및 아날로그 기능이 있는 핀입니다.""" pin11: MicroBitDigitalPin -"""Pin with digital features.""" - +"""디지털 기능이 있는 핀입니다.""" pin12: MicroBitDigitalPin -"""Pin with digital features.""" - +"""디지털 기능이 있는 핀입니다.""" pin13: MicroBitDigitalPin -"""Pin with digital features.""" - +"""디지털 기능이 있는 핀입니다.""" pin14: MicroBitDigitalPin -"""Pin with digital features.""" - +"""디지털 기능이 있는 핀입니다.""" pin15: MicroBitDigitalPin -"""Pin with digital features.""" - +"""디지털 기능이 있는 핀입니다.""" pin16: MicroBitDigitalPin -"""Pin with digital features.""" - +"""디지털 기능이 있는 핀입니다.""" pin19: MicroBitDigitalPin -"""Pin with digital features.""" - +"""디지털 기능이 있는 핀입니다.""" pin20: MicroBitDigitalPin -"""Pin with digital features.""" - +"""디지털 기능이 있는 핀입니다.""" pin_logo: MicroBitTouchPin -"""A touch sensitive logo pin on the front of the micro:bit, which by default is set to capacitive touch mode.""" - +"""micro:bit 전면의 터치 감지 로고 핀으로, 기본값은 정전식 터치 모드입니다. (핀 로고)""" pin_speaker: MicroBitAnalogDigitalPin -"""A pin to address the micro:bit speaker. +"""micro:bit 스피커를 처리하는 핀입니다. (핀 스피커) This API is intended only for use in Pulse-Width Modulation pin operations e.g. pin_speaker.write_analog(128). """ class Image: - """An image to show on the micro:bit LED display. + """micro:bit LED 디스플레이에 표시할 이미지입니다. - Given an image object it's possible to display it via the ``display`` API:: - - display.show(Image.HAPPY) - """ +Given an image object it's possible to display it via the ``display`` API:: + display.show(Image.HAPPY)""" HEART: Image - """Heart image.""" - + """하트 이미지입니다.""" HEART_SMALL: Image - """Small heart image.""" - + """작은 하트 이미지입니다.""" HAPPY: Image - """Happy face image.""" - + """행복한 얼굴 이미지입니다.""" SMILE: Image - """Smiling mouth image.""" - + """미소 짓는 얼굴 이미지입니다.""" SAD: Image - """Sad face image.""" - + """슬픈 얼굴 이미지입니다.""" CONFUSED: Image - """Confused face image.""" - + """혼란스러운 얼굴 이미지입니다.""" ANGRY: Image - """Angry face image.""" - + """화난 얼굴 이미지입니다.""" ASLEEP: Image - """Sleeping face image.""" - + """자는 얼굴 이미지입니다.""" SURPRISED: Image - """Surprised face image.""" - + """놀란 얼굴 이미지입니다.""" SILLY: Image - """Silly face image.""" - + """우스꽝스러운 얼굴 이미지입니다.""" FABULOUS: Image - """Sunglasses face image.""" - + """선글라스를 쓴 얼굴 이미지입니다.""" MEH: Image - """Unimpressed face image.""" - + """지루한 얼굴 이미지입니다.""" YES: Image - """Tick image.""" - + """체크 표시 이미지입니다.""" NO: Image - """Cross image.""" - + """엑스 표시 이미지입니다.""" CLOCK12: Image - """Image with line pointing to 12 o'clock.""" - + """12시 정각을 가리키는 이미지입니다.""" CLOCK11: Image - """Image with line pointing to 11 o'clock.""" - + """11시 정각을 가리키는 이미지입니다.""" CLOCK10: Image - """Image with line pointing to 10 o'clock.""" - + """10시 정각을 가리키는 이미지입니다.""" CLOCK9: Image - """Image with line pointing to 9 o'clock.""" - + """9시 정각을 가리키는 이미지입니다.""" CLOCK8: Image - """Image with line pointing to 8 o'clock.""" - + """8시 정각을 가리키는 이미지입니다.""" CLOCK7: Image - """Image with line pointing to 7 o'clock.""" - + """7시 정각을 가리키는 이미지입니다.""" CLOCK6: Image - """Image with line pointing to 6 o'clock.""" - + """6시 정각을 가리키는 이미지입니다.""" CLOCK5: Image - """Image with line pointing to 5 o'clock.""" - + """5시 정각을 가리키는 이미지입니다.""" CLOCK4: Image - """Image with line pointing to 4 o'clock.""" - + """4시 정각을 가리키는 이미지입니다.""" CLOCK3: Image - """Image with line pointing to 3 o'clock.""" - + """3시 정각을 가리키는 이미지입니다.""" CLOCK2: Image - """Image with line pointing to 2 o'clock.""" - + """2시 정각을 가리키는 이미지입니다.""" CLOCK1: Image - """Image with line pointing to 1 o'clock.""" - + """1시 정각을 가리키는 이미지입니다.""" ARROW_N: Image - """Image of arrow pointing north.""" - + """북쪽을 가리키는 화살표 이미지입니다.""" ARROW_NE: Image - """Image of arrow pointing north east.""" - + """북동쪽을 가리키는 화살표 이미지입니다.""" ARROW_E: Image - """Image of arrow pointing east.""" - + """동쪽을 가리키는 화살표 이미지입니다.""" ARROW_SE: Image - """Image of arrow pointing south east.""" - + """남동쪽을 가리키는 화살표 이미지입니다.""" ARROW_S: Image - """Image of arrow pointing south.""" - + """남쪽을 가리키는 화살표 이미지입니다.""" ARROW_SW: Image - """Image of arrow pointing south west.""" - + """남서쪽을 가리키는 화살표 이미지입니다.""" ARROW_W: Image - """Image of arrow pointing west.""" - + """서쪽을 가리키는 화살표 이미지입니다.""" ARROW_NW: Image - """Image of arrow pointing north west.""" - + """북서쪽을 가리키는 화살표 이미지입니다.""" TRIANGLE: Image - """Image of a triangle pointing up.""" - + """위쪽을 가리키는 삼각형 이미지입니다.""" TRIANGLE_LEFT: Image - """Image of a triangle in the left corner.""" - + """왼쪽 구석의 삼각형 이미지입니다.""" CHESSBOARD: Image - """Alternate LEDs lit in a chessboard pattern.""" - + """체스판 패턴으로 깜빡이는 LED 불빛입니다.""" DIAMOND: Image - """Diamond image.""" - + """다이아몬드 이미지입니다.""" DIAMOND_SMALL: Image - """Small diamond image.""" - + """작은 다이아몬드 이미지입니다.""" SQUARE: Image - """Square image.""" - + """사각형 이미지입니다.""" SQUARE_SMALL: Image - """Small square image.""" - + """작은 사각형 이미지입니다.""" RABBIT: Image - """Rabbit image.""" - + """토끼 이미지입니다.""" COW: Image - """Cow image.""" - + """소 이미지입니다.""" MUSIC_CROTCHET: Image - """Crotchet note image.""" - + """사분음표 이미지입니다.""" MUSIC_QUAVER: Image - """Quaver note image.""" - + """팔분음표 이미지입니다.""" MUSIC_QUAVERS: Image - """Pair of quavers note image.""" - + """두 개의 팔분음표 이미지입니다.""" PITCHFORK: Image - """Pitchfork image.""" - + """쇠스랑 이미지입니다.""" XMAS: Image - """Christmas tree image.""" - + """크리스마스 나무 이미지입니다.""" PACMAN: Image - """Pac-Man arcade character image.""" - + """오락실 캐릭터 Pac-Man 이미지입니다.""" TARGET: Image - """Target image.""" - + """표적 이미지입니다.""" TSHIRT: Image - """T-shirt image.""" - + """티셔츠 이미지입니다.""" ROLLERSKATE: Image - """Rollerskate image.""" - + """롤러스케이트 이미지입니다.""" DUCK: Image - """Duck image.""" - + """오리 이미지입니다.""" HOUSE: Image - """House image.""" - + """집 이미지입니다.""" TORTOISE: Image - """Tortoise image.""" - + """거북이 이미지입니다.""" BUTTERFLY: Image - """Butterfly image.""" - + """나비 이미지입니다.""" STICKFIGURE: Image - """Stick figure image.""" - + """막대인간 이미지입니다.""" GHOST: Image - """Ghost image.""" - + """유령 이미지입니다.""" SWORD: Image - """Sword image.""" - + """칼 이미지입니다.""" GIRAFFE: Image - """Giraffe image.""" - + """기린 이미지입니다.""" SKULL: Image - """Skull image.""" - + """해골 이미지입니다.""" UMBRELLA: Image - """Umbrella image.""" - + """우산 이미지입니다.""" SNAKE: Image - """Snake image.""" - + """뱀 이미지입니다.""" SCISSORS: Image """Scissors image.""" - ALL_CLOCKS: List[Image] - """A list containing all the CLOCK_ images in sequence.""" - + """모든 CLOCK_ 이미지를 순서대로 나열한 리스트입니다.""" ALL_ARROWS: List[Image] - """A list containing all the ARROW_ images in sequence.""" + """모든 ARROW_ 이미지를 순서대로 나열한 리스트입니다.""" + @overload def __init__(self, string: str) -> None: - """Create an image from a string describing which LEDs are lit. + """어떤 LED가 켜져있는지 설명하는 문자열로부터 이미지를 생성합니다. (string) - ``string`` has to consist of digits 0-9 arranged into lines, - describing the image, for example:: +``string`` has to consist of digits 0-9 arranged into lines, +describing the image, for example:: - image = Image("90009:" - "09090:" - "00900:" - "09090:" - "90009") + 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 newlines (\\n) insead of the colons. +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 newlines (\\n) insead of the colons. - :param string: The string describing the image. - """ +:param string: 이미지를 설명하는 문자열입니다.""" ... + @overload - def __init__( - self, width: int = 5, height: int = 5, buffer: ReadableBuffer = None - ) -> None: - """Create an empty image with ``width`` columns and ``height`` rows. + def __init__(self, width: int=5, height: int=5, buffer: ReadableBuffer=None) -> None: + """``width`` 열과 ``height`` 행의 비어있는 이미지를 생성합니다. - :param width: Optional width of the image - :param height: Optional height of the image - :param buffer: Optional array or bytes of ``width``×``height`` integers in range 0-9 to initialize the image +:param width: 이미지 너비(선택 사항) +:param height: 이미지 높이(선택 사항) +:param buffer: 0~9의 범위에 속하는 정수로 구성된 ``width``x``height`` 배열 또는 바이트(선택 사항) - Examples:: +Examples:: - Image(2, 2, b'\x08\x08\x08\x08') - Image(2, 2, bytearray([9,9,9,9])) + Image(2, 2, b'\x08\x08\x08\x08') + Image(2, 2, bytearray([9,9,9,9])) - These create 2 x 2 pixel images at full brightness. - """ +These create 2 x 2 pixel images at full brightness.""" ... + def width(self) -> int: - """Get the number of columns. + """열의 수를 불러옵니다. - :return: The number of columns in the image - """ +:return: The number of columns in the image""" ... + def height(self) -> int: - """Get the number of rows. + """행의 수를 불러옵니다. - :return: The number of rows in the image - """ +:return: The number of rows in the image""" ... + def set_pixel(self, x: int, y: int, value: int) -> None: - """Set the brightness of a pixel. + """픽셀의 밝기를 설정합니다. - Example: ``my_image.set_pixel(0, 0, 9)`` +Example: ``my_image.set_pixel(0, 0, 9)`` - :param x: The column number - :param y: The row number - :param value: The brightness as an integer between 0 (dark) and 9 (bright) +:param x: 열 번호 +:param y: 행 번호 +:param value: 0(어두움)과 9(밝음) 사이의 정수로 밝기를 설정합니다. - This method will raise an exception when called on any of the built-in - read-only images, like ``Image.HEART``. - """ +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: - """Get the brightness of a pixel. + """픽셀의 밝기를 불러옵니다. - Example: ``my_image.get_pixel(0, 0)`` +Example: ``my_image.get_pixel(0, 0)`` - :param x: The column number - :param y: The row number - :return: The brightness as an integer between 0 and 9. - """ +:param x: 열 번호 +:param y: 행 번호 +:return: The brightness as an integer between 0 and 9.""" ... + def shift_left(self, n: int) -> Image: - """Create a new image by shifting the picture left. + """사진을 왼쪽으로 옮겨 새로운 이미지를 생성합니다. - Example: ``Image.HEART_SMALL.shift_left(1)`` +Example: ``Image.HEART_SMALL.shift_left(1)`` - :param n: The number of columns to shift by - :return: The shifted image - """ +:param n: 옮길 열의 수 +:return: The shifted image""" ... + def shift_right(self, n: int) -> Image: - """Create a new image by shifting the picture right. + """사진을 오른쪽으로 옮겨 새로운 이미지를 생성합니다. - Example: ``Image.HEART_SMALL.shift_right(1)`` +Example: ``Image.HEART_SMALL.shift_right(1)`` - :param n: The number of columns to shift by - :return: The shifted image - """ +:param n: 옮길 열의 수 +:return: The shifted image""" ... + def shift_up(self, n: int) -> Image: - """Create a new image by shifting the picture up. + """사진을 위로 옮겨 새로운 이미지를 생성합니다. - Example: ``Image.HEART_SMALL.shift_up(1)`` +Example: ``Image.HEART_SMALL.shift_up(1)`` - :param n: The number of rows to shift by - :return: The shifted image - """ +:param n: 옮길 행의 수 +:return: The shifted image""" ... + def shift_down(self, n: int) -> Image: - """Create a new image by shifting the picture down. + """사진을 아래로 옮겨 새로운 이미지를 생성합니다. - Example: ``Image.HEART_SMALL.shift_down(1)`` +Example: ``Image.HEART_SMALL.shift_down(1)`` - :param n: The number of rows to shift by - :return: The shifted image - """ +:param n: 옮길 행의 수 +:return: The shifted image""" ... + def crop(self, x: int, y: int, w: int, h: int) -> Image: - """Create a new image by cropping the picture. + """사진을 잘라 내 새로운 이미지를 생성합니다. - Example: ``Image.HEART.crop(1, 1, 3, 3)`` +Example: ``Image.HEART.crop(1, 1, 3, 3)`` - :param x: The crop offset column - :param y: The crop offset row - :param w: The crop width - :param h: The crop height - :return: The new image - """ +:param x: 자르기 오프셋 열 +:param y: 자르기 오프셋 행 +:param w: 자르기 너비 +:param h: 자르기 높이 +:return: The new image""" ... + def copy(self) -> Image: - """Create an exact copy of the image. + """이미지와 동일한 사본을 생성합니다. - Example: ``Image.HEART.copy()`` +Example: ``Image.HEART.copy()`` - :return: The new image - """ +:return: The new image""" ... + def invert(self) -> Image: - """Create a new image by inverting the brightness of the pixels in the - source image. + """소스 이미지에 있는 픽셀을 밝기를 반전해 새로운 이미지를 생성합니다. - Example: ``Image.SMALL_HEART.invert()`` +Example: ``Image.SMALL_HEART.invert()`` - :return: The new image. - """ +:return: The new image.""" ... + def fill(self, value: int) -> None: - """Set the brightness of all the pixels in the image. + """이미지의 모든 픽셀의 밝기를 설정합니다. - Example: ``my_image.fill(5)`` +Example: ``my_image.fill(5)`` - :param value: The new brightness as a number between 0 (dark) and 9 (bright). +:param value: 새로운 밝기를 0(어두움)과 9(밝기) 사이로 설정합니다. - This method will raise an exception when called on any of the built-in - read-only images, like ``Image.HEART``. - """ +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 an area from another image into this image. - - Example: ``my_image.blit(Image.HEART, 1, 1, 3, 3, 1, 1)`` - - :param src: The source image - :param x: The starting column offset in the source image - :param y: The starting row offset in the source image - :param w: The number of columns to copy - :param h: The number of rows to copy - :param xdest: The column offset to modify in this image - :param ydest: The row offset to modify in this image - - Pixels outside the source image are treated as having a brightness 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 blit(self, src: Image, x: int, y: int, w: int, h: int, xdest: int=0, ydest: int=0) -> None: + """다른 이미지로부터 영역을 복사해 이 이미지로 가져옵니다. + +Example: ``my_image.blit(Image.HEART, 1, 1, 3, 3, 1, 1)`` + +:param src: 소스 이미지 +:param x: 소스 이미지 내 시작 열 오프셋 +:param y: 소스 이미지 내 시작 행 오프셋 +:param w: 복사할 열의 수 +:param h: 복사할 행 번호 +:param xdest: 이 이미지에서 수정할 열의 오프셋 +:param ydest: 이 이미지에서 수정할 행의 오프셋 + +Pixels outside the source image are treated as having a brightness 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. + """두 이미지의 각 픽셀의 밝기 값을 더해 새로운 이미지를 생성합니다. - Example: ``Image.HEART + Image.HAPPY`` +Example: ``Image.HEART + Image.HAPPY`` - :param other: The image to add. - """ +:param other: 더할 이미지입니다.""" ... + def __sub__(self, other: Image) -> Image: - """Create a new image by subtracting the brightness values of the - other image from this image. + """두 이미지의 각 픽셀의 밝기 값을 빼 새로운 이미지를 생성합니다. - Example: ``Image.HEART - Image.HEART_SMALL`` +Example: ``Image.HEART - Image.HEART_SMALL`` - :param other: The image to subtract. - """ +:param other: 뺄 이미지입니다.""" ... + def __mul__(self, n: float) -> Image: - """Create a new image by multiplying the brightness of each pixel by - ``n``. + """각 픽셀의 밝기 값을 ``n``만큼 곱해 새로운 이미지를 생성합니다. - Example: ``Image.HEART * 0.5`` +Example: ``Image.HEART * 0.5`` - :param n: The value to multiply by. - """ +:param n: 곱할 값입니다.""" ... + def __truediv__(self, n: float) -> Image: - """Create a new image by dividing the brightness of each pixel by - ``n``. + """각 픽셀의 밝기 값을 ``n``만큼 나누어 새로운 이미지를 생성합니다. - Example: ``Image.HEART / 2`` +Example: ``Image.HEART / 2`` - :param n: The value to divide by. - """ +:param n: 나눌 값입니다.""" ... class SoundEvent: LOUD: SoundEvent - """Represents the transition of sound events, from ``quiet`` to ``loud`` like clapping or shouting.""" - + """``quiet``에서 박수 또는 함성 등 ``loud``로 소리 이벤트의 변화를 나타냅니다.""" QUIET: SoundEvent - """Represents the transition of sound events, from ``loud`` to ``quiet`` like speaking or background music.""" + """``loud``에서 말소리 또는 배경 음악 등 ``quiet``로 소리 이벤트의 변화를 나타냅니다.""" class Sound: - """The built-in sounds can be called using ``audio.play(Sound.NAME)``.""" - + """``audio.play(Sound.NAME)``을 사용해 내장된 소리를 호출합니다.""" GIGGLE: Sound - """Giggling sound.""" - + """웃는 소리입니다.""" HAPPY: Sound - """Happy sound.""" - + """행복해하는 소리입니다.""" HELLO: Sound - """Greeting sound.""" - + """인사 소리입니다.""" MYSTERIOUS: Sound - """Mysterious sound.""" - + """신비한 소리입니다.""" SAD: Sound - """Sad sound.""" - + """슬퍼하는 소리입니다.""" SLIDE: Sound - """Sliding sound.""" - + """슬라이드 소리입니다.""" SOARING: Sound - """Soaring sound.""" - + """솟아오르는 소리입니다.""" SPRING: Sound - """Spring sound.""" - + """스프링 소리입니다.""" TWINKLE: Sound - """Twinkling sound.""" - + """반짝이는 소리입니다.""" YAWN: Sound - """Yawning sound.""" + """하품 소리입니다.""" \ No newline at end of file diff --git a/lang/ko/typeshed/stdlib/microbit/accelerometer.pyi b/lang/ko/typeshed/stdlib/microbit/accelerometer.pyi index bac82c0..c57cd04 100644 --- a/lang/ko/typeshed/stdlib/microbit/accelerometer.pyi +++ b/lang/ko/typeshed/stdlib/microbit/accelerometer.pyi @@ -1,115 +1,103 @@ -"""Measure the acceleration of the micro:bit and recognise gestures. -""" - +"""micro:bit의 가속도를 측정하고 제스쳐를 인식합니다.""" from typing import Tuple def get_x() -> int: - """Get the acceleration measurement in the ``x`` axis in milli-g. + """``x`` 축의 가속도 측정값을 milli-g로 불러옵니다. - Example: ``accelerometer.get_x()`` +Example: ``accelerometer.get_x()`` - :return: A positive or negative integer depending on direction in the range +/- 2000mg. - """ +:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" ... def get_y() -> int: - """Get the acceleration measurement in the ``y`` axis in milli-g. + """``y`` 축의 가속도 측정값을 milli-g로 불러옵니다. - Example: ``accelerometer.get_y()`` +Example: ``accelerometer.get_y()`` - :return: A positive or negative integer depending on direction in the range +/- 2000mg. - """ +:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" ... def get_z() -> int: - """Get the acceleration measurement in the ``z`` axis in milli-g. + """``z`` 축의 가속도 측정값을 milli-g로 불러옵니다. - Example: ``accelerometer.get_z()`` +Example: ``accelerometer.get_z()`` - :return: A positive or negative integer depending on direction in the range +/- 2000mg. - """ +:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" ... def get_values() -> Tuple[int, int, int]: - """Get the acceleration measurements in all axes at once as a tuple. + """한 번에 모든 축의 가속도 측정값을 튜플로 불러옵니다. - Example: ``x, y, z = accelerometer.get_values()`` +Example: ``x, y, z = accelerometer.get_values()`` - :return: a three-element tuple of integers ordered as X, Y, Z, each value a positive or negative integer depending on direction in the range +/- 2000mg - """ +:return: a three-element tuple of integers ordered as X, Y, Z, each value a positive or negative integer depending on direction in the range +/- 2000mg""" ... def get_strength() -> int: """Get the acceleration measurement of all axes combined, as a positive integer. This is the Pythagorean sum of the X, Y and Z axes. - Example: ``accelerometer.get_strength()`` +Example: ``accelerometer.get_strength()`` - :return: The combined acceleration strength of all the axes, in milli-g. - """ +:return: The combined acceleration strength of all the axes, in milli-g.""" ... def current_gesture() -> str: - """Get the name of the current gesture. + """현재 제스처의 이름을 불러옵니다. - Example: ``accelerometer.current_gesture()`` +Example: ``accelerometer.current_gesture()`` - 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. +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. - :return: The current gesture - """ +:return: The current gesture""" ... def is_gesture(name: str) -> bool: - """Check if the named gesture is currently active. + """해당 이름의 제스처가 현재 활성화 상태인지 확인합니다. - Example: ``accelerometer.is_gesture('shake')`` +Example: ``accelerometer.is_gesture('shake')`` - 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. +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. - :param name: The gesture name. - :return: ``True`` if the gesture is active, ``False`` otherwise. - """ +:param name: 제스쳐 이름. +:return: ``True`` if the gesture is active, ``False`` otherwise.""" ... def was_gesture(name: str) -> bool: - """Check if the named gesture was active since the last call. + """해당 이름의 제스처가 마지막 호출 이후로 활성화된 적이 있는지 확인합니다. - Example: ``accelerometer.was_gesture('shake')`` +Example: ``accelerometer.was_gesture('shake')`` - 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. +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. - :param name: The gesture name. - :return: ``True`` if the gesture was active since the last call, ``False`` otherwise. - """ +:param name: 제스처 이름입니다. +:return: ``True`` if the gesture was active since the last call, ``False`` otherwise.""" def get_gestures() -> Tuple[str, ...]: - """Return a tuple of the gesture history. + """제스처 기록의 튜플을 반환합니다. - Example: ``accelerometer.get_gestures()`` +Example: ``accelerometer.get_gestures()`` - Clears the gesture history before returning. +Clears the gesture history before returning. - Gestures are not updated in the background so there needs to be constant - calls to some accelerometer method to do the gesture detection. Usually - gestures can be detected using a loop with a small :func:`microbit.sleep` delay. +Gestures are not updated in the background so there needs to be constant +calls to some accelerometer method to do the gesture detection. Usually +gestures can be detected using a loop with a small :func:`microbit.sleep` delay. - :return: The history as a tuple, most recent last. - """ +:return: The history as a tuple, most recent last.""" ... def set_range(value: int) -> None: """Set the accelerometer sensitivity range, in g (standard gravity), to the closest values supported by the hardware, so it rounds to either ``2``, ``4``, or ``8`` g. - Example: ``accelerometer.set_range(8)`` +Example: ``accelerometer.set_range(8)`` - :param value: New range for the accelerometer, an integer in ``g``. - """ +:param value: New range for the accelerometer, an integer in ``g``.""" \ No newline at end of file diff --git a/lang/ko/typeshed/stdlib/microbit/audio.pyi b/lang/ko/typeshed/stdlib/microbit/audio.pyi index 3b1e327..e14bf7e 100644 --- a/lang/ko/typeshed/stdlib/microbit/audio.pyi +++ b/lang/ko/typeshed/stdlib/microbit/audio.pyi @@ -1,160 +1,123 @@ -"""Play sounds using the micro:bit (import ``audio`` for V1 compatibility). -""" - +"""micro:bit을 활용해 소리를 재생합니다(V1 호환을 위해서는 ``audio``를 가져오세요).""" from ..microbit import MicroBitDigitalPin, Sound, pin0 from typing import ClassVar, Iterable, Union -def play( - source: Union[Iterable[AudioFrame], Sound, SoundEffect], - wait: bool = True, - pin: MicroBitDigitalPin = pin0, - return_pin: Union[MicroBitDigitalPin, None] = None, -) -> None: +def play(source: Union[Iterable[AudioFrame], Sound, SoundEffect], wait: bool=True, pin: MicroBitDigitalPin=pin0, return_pin: Union[MicroBitDigitalPin, None]=None) -> None: """Play a built-in sound, sound effect or custom audio frames. - Example: ``audio.play(Sound.GIGGLE)`` +Example: ``audio.play(Sound.GIGGLE)`` - :param source: A built-in ``Sound`` such as ``Sound.GIGGLE``, a ``SoundEffect`` or sample data as an iterable of ``AudioFrame`` objects. - :param wait: If ``wait`` is ``True``, this function will block until the sound is complete. - :param pin: An optional argument to specify the output pin can be used to override the default of ``pin0``. If we do not want any sound to play we can use ``pin=None``. - :param return_pin: Specifies a differential edge connector pin to connect to an external speaker instead of ground. This is ignored for the **V2** revision. - """ +:param source: A built-in ``Sound`` such as ``Sound.GIGGLE``, a ``SoundEffect`` or sample data as an iterable of ``AudioFrame`` objects. +:param wait: ``wait``이 ``True``인 경우 사운드 재생이 완료될 때까지 이 함수가 차단됩니다. +:param pin: (핀) ``pin0``의 기본값을 덮어쓰는 데 사용할 출력 핀을 특정하는 인자입니다(선택 사항). 사운드를 재생하고 싶지 않다면 ``pin=None``을 사용할 수 있습니다. +:param return_pin: 접지 대신 외부 스피커에 연결할 차동 엣지 커넥터 핀을 특정합니다. **V2** 수정 버전에서는 무시합니다.""" def is_playing() -> bool: - """Check whether a sound is playing. + """소리가 재생 중인지 체크합니다. - Example: ``audio.is_playing()`` +Example: ``audio.is_playing()`` - :return: ``True`` if audio is playing, otherwise ``False``.""" +:return: ``True`` if audio is playing, otherwise ``False``.""" ... def stop() -> None: - """Stop all audio playback. + """모든 오디오 플레이백을 중지합니다. - Example: ``audio.stop()`` - """ +Example: ``audio.stop()``""" ... class SoundEffect: """A sound effect, composed by a set of parameters configured via the constructor or attributes.""" - WAVEFORM_SINE: ClassVar[int] """Sine wave option used for the ``waveform`` parameter.""" - WAVEFORM_SAWTOOTH: ClassVar[int] """Sawtooth wave option used for the ``waveform`` parameter.""" - WAVEFORM_TRIANGLE: ClassVar[int] """Triangle wave option used for the ``waveform`` parameter.""" - WAVEFORM_SQUARE: ClassVar[int] """Square wave option used for the ``waveform`` parameter.""" - WAVEFORM_NOISE: ClassVar[int] """Noise option used for the ``waveform`` parameter.""" - SHAPE_LINEAR: ClassVar[int] """Linear interpolation option used for the ``shape`` parameter.""" - SHAPE_CURVE: ClassVar[int] """Curve interpolation option used for the ``shape`` parameter.""" - SHAPE_LOG: ClassVar[int] """Logarithmic interpolation option used for the ``shape`` parameter.""" - FX_NONE: ClassVar[int] """No effect option used for the ``fx`` parameter.""" - FX_TREMOLO: ClassVar[int] """Tremolo effect option used for the ``fx`` parameter.""" - FX_VIBRATO: ClassVar[int] """Vibrato effect option used for the ``fx`` parameter.""" - FX_WARBLE: ClassVar[int] """Warble effect option used for the ``fx`` parameter.""" - freq_start: int """Start frequency in Hertz (Hz), a number between ``0`` and ``9999``""" - freq_end: int """End frequency in Hertz (Hz), a number between ``0`` and ``9999``""" - duration: int """Duration of the sound in milliseconds, a number between ``0`` and ``9999``""" - vol_start: int """Start volume value, a number between ``0`` and ``255``""" - vol_end: int """End volume value, a number between ``0`` and ``255``""" - waveform: int """Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise)""" - fx: int """Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``""" - shape: int """The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``""" - def __init__( - self, - freq_start: int = 500, - freq_end: int = 2500, - duration: int = 500, - vol_start: int = 255, - vol_end: int = 0, - waveform: int = WAVEFORM_SQUARE, - fx: int = FX_NONE, - shape: int = SHAPE_LOG, - ): - """Create a new sound effect. - - Example: ``my_effect = SoundEffect(duration=1000)`` - - All the parameters are optional, with default values as shown above, and - they can all be modified via attributes of the same name. For example, we - can first create an effect ``my_effect = SoundEffect(duration=1000)``, - and then change its attributes ``my_effect.duration = 500``. - - :param freq_start: Start frequency in Hertz (Hz), a number between ``0`` and ``9999``. - :param freq_end: End frequency in Hertz (Hz), a number between ``0`` and ``9999``. - :param duration: Duration of the sound in milliseconds, a number between ``0`` and ``9999``. - :param vol_start: Start volume value, a number between ``0`` and ``255``. - :param vol_end: End volume value, a number between ``0`` and ``255``. - :param waveform: Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise). - :param fx: Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``. - :param shape: The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``. - """ + def __init__(self, freq_start: int=500, freq_end: int=2500, duration: int=500, vol_start: int=255, vol_end: int=0, waveform: int=WAVEFORM_SQUARE, fx: int=FX_NONE, shape: int=SHAPE_LOG): + """Create a new sound effect. (string) + +Example: ``my_effect = SoundEffect(duration=1000)`` + +All the parameters are optional, with default values as shown above, and +they can all be modified via attributes of the same name. For example, we +can first create an effect ``my_effect = SoundEffect(duration=1000)``, +and then change its attributes ``my_effect.duration = 500``. + +:param freq_start: Start frequency in Hertz (Hz), a number between ``0`` and ``9999``. +:param freq_end: End frequency in Hertz (Hz), a number between ``0`` and ``9999``. +:param duration: Duration of the sound in milliseconds, a number between ``0`` and ``9999``. +:param vol_start: Start volume value, a number between ``0`` and ``255``. +:param vol_end: End volume value, a number between ``0`` and ``255``. +:param waveform: Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise). +:param fx: Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``. +:param shape: The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``.""" + def copy(self) -> SoundEffect: """Create a copy of this ``SoundEffect``. - Example: ``sound_2 = sound_1.copy()`` +Example: ``sound_2 = sound_1.copy()`` - :return: A copy of the SoundEffect. - """ +:return: A copy of the SoundEffect.""" class AudioFrame: - """An ``AudioFrame`` object is a list of 32 samples each of which is a unsigned byte - (whole number between 0 and 255). + """``AudioFrame`` 오브젝트는 부호 없는 바이트 샘플 32개의 리스트입니다(0에서 255 사이의 모든 숫자). - It takes just over 4 ms to play a single frame. +It takes just over 4 ms to play a single frame. - Example:: +Example:: - frame = AudioFrame() - for i in range(len(frame)): - frame[i] = 252 - i * 8 - """ + frame = AudioFrame() + for i in range(len(frame)): + frame[i] = 252 - i * 8""" def copyfrom(self, other: AudioFrame) -> None: """Overwrite the data in this ``AudioFrame`` with the data from another ``AudioFrame`` instance. - Example: ``my_frame.copyfrom(source_frame)`` +Example: ``my_frame.copyfrom(source_frame)`` + +:param other: ``AudioFrame`` instance from which to copy the data.""" + + def __len__(self) -> int: + ... + + def __setitem__(self, key: int, value: int) -> None: + ... - :param other: ``AudioFrame`` instance from which to copy the data. - """ - def __len__(self) -> int: ... - def __setitem__(self, key: int, value: int) -> None: ... - def __getitem__(self, key: int) -> int: ... + def __getitem__(self, key: int) -> int: + ... \ No newline at end of file diff --git a/lang/ko/typeshed/stdlib/microbit/compass.pyi b/lang/ko/typeshed/stdlib/microbit/compass.pyi index c74a47b..1c2f8eb 100644 --- a/lang/ko/typeshed/stdlib/microbit/compass.pyi +++ b/lang/ko/typeshed/stdlib/microbit/compass.pyi @@ -1,78 +1,70 @@ -"""Use the built-in compass. -""" +"""내장된 나침반을 사용합니다. (나침반)""" def calibrate() -> None: - """Starts the calibration process. + """보정 프로세스를 시작합니다. - Example: ``compass.calibrate()`` +Example: ``compass.calibrate()`` - 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. - """ +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: - """Check is the compass is calibrated. + """나침반이 보정되었는지 확인합니다. - Example: ``compass.is_calibrated()`` +Example: ``compass.is_calibrated()`` - :return: ``True`` if the compass has been successfully calibrated, ``False`` otherwise. - """ +:return: ``True`` if the compass has been successfully calibrated, ``False`` otherwise.""" ... def clear_calibration() -> None: - """Undoes the calibration, making the compass uncalibrated again. + """보정을 해제해 나침반을 보정하지 않은 상태로 설정합니다. - Example: ``compass.clear_calibration()`` - """ +Example: ``compass.clear_calibration()``""" ... def get_x() -> int: - """Get the magnetic field strength on the ``x`` axis. + """``x`` 축의 자기장 강도를 불러옵니다. - Example: ``compass.get_x()`` +Example: ``compass.get_x()`` - Call ``calibrate`` first or the results will be inaccurate. +Call ``calibrate`` first or the results will be inaccurate. - :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. - """ +:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" ... def get_y() -> int: - """Get the magnetic field strength on the ``y`` axis. + """``y`` 축의 자기장 강도를 불러옵니다. - Example: ``compass.get_y()`` +Example: ``compass.get_y()`` - Call ``calibrate`` first or the results will be inaccurate. +Call ``calibrate`` first or the results will be inaccurate. - :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. - """ +:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" ... def get_z() -> int: - """Get the magnetic field strength on the ``z`` axis. + """``z`` 축의 자기장 강도를 불러옵니다. - Example: ``compass.get_z()`` +Example: ``compass.get_z()`` - Call ``calibrate`` first or the results will be inaccurate. +Call ``calibrate`` first or the results will be inaccurate. - :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. - """ +:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" ... def heading() -> int: - """Get the compass heading. + """나침반의 방향을 불러옵니다. - Example: ``compass.heading()`` +Example: ``compass.heading()`` - :return: An integer in the range from 0 to 360, representing the angle in degrees, clockwise, with north as 0. - """ +:return: An integer in the range from 0 to 360, representing the angle in degrees, clockwise, with north as 0.""" ... def get_field_strength() -> int: - """Get the magnitude of the magnetic field around the device. + """장치 주변의 자기장 규모를 불러옵니다. - Example: ``compass.get_field_strength()`` +Example: ``compass.get_field_strength()`` - :return: An integer indication of the magnitude of the magnetic field in nano tesla.""" - ... +:return: An integer indication of the magnitude of the magnetic field in nano tesla.""" + ... \ No newline at end of file diff --git a/lang/ko/typeshed/stdlib/microbit/display.pyi b/lang/ko/typeshed/stdlib/microbit/display.pyi index aa4013e..af0c5de 100644 --- a/lang/ko/typeshed/stdlib/microbit/display.pyi +++ b/lang/ko/typeshed/stdlib/microbit/display.pyi @@ -1,115 +1,92 @@ -"""Show text, images and animations on the 5×5 LED display. -""" - +"""5×5 LED 디스플레이에 텍스트, 이미지, 애니메이션을 표시합니다.""" from ..microbit import Image from typing import Union, overload, Iterable def get_pixel(x: int, y: int) -> int: - """Get the brightness of the LED at column ``x`` and row ``y``. + """열 ``x``와 행 ``y``의 LED의 밝기를 불러옵니다. - Example: ``display.get_pixel(0, 0)`` +Example: ``display.get_pixel(0, 0)`` - :param x: The display column (0..4) - :param y: The display row (0..4) - :return: A number between 0 (off) and 9 (bright) - """ +:param x: 디스플레이 열(0..4) +:param y: 디스플레이 행(0..4) +:return: A number 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``. + """열 ``x``와 행 ``y``의 LED의 밝기를 설정합니다. - Example: ``display.set_pixel(0, 0, 9)`` +Example: ``display.set_pixel(0, 0, 9)`` - :param x: The display column (0..4) - :param y: The display row (0..4) - :param value: The brightness between 0 (off) and 9 (bright) - """ +:param x: 디스플레이 열(0..4) +:param y: 디스플레이 행(0..4) +:param value: 0(꺼짐)과 9(밝음) 사이의 밝기""" ... def clear() -> None: - """Set the brightness of all LEDs to 0 (off). + """모든 LED의 밝기를 0(꺼짐)으로 설정합니다. - Example: ``display.clear()`` - """ +Example: ``display.clear()``""" ... -def show( - image: Union[str, float, int, Image, Iterable[Image]], - delay: int = 400, - wait: bool = True, - loop: bool = False, - clear: bool = False, -) -> None: - """Shows images, letters or digits on the LED display. +def show(image: Union[str, float, int, Image, Iterable[Image]], delay: int=400, wait: bool=True, loop: bool=False, clear: bool=False) -> None: + """LED 디스플레이에 이미지, 글자 또는 숫자를 표시합니다. - Example: ``display.show(Image.HEART)`` +Example: ``display.show(Image.HEART)`` - When ``image`` is an image or a list of images then each image is displayed in turn. - If ``image`` is a string or number, each letter or digit is displayed in turn. +When ``image`` is an image or a list of images then each image is displayed in turn. +If ``image`` is a string or number, each letter or digit is displayed in turn. - :param image: A string, number, image or list of images to show. - :param delay: Each letter, digit or image is shown with ``delay`` milliseconds between them. - :param wait: If ``wait`` is ``True``, this function will block until the animation is finished, otherwise the animation will happen in the background. - :param loop: If ``loop`` is ``True``, the animation will repeat forever. - :param clear: If ``clear`` is ``True``, the display will be cleared after the sequence has finished. +:param image: 표시할 문자열, 숫자, 이미지 또는 이미지 목록입니다. +:param delay: ``delay``밀리초의 지연 시간을 두고 각 글자, 숫자 또는 이미지가 표시됩니다. +:param wait: ``wait``가 ``True``인 경우 이 기능은 애니메이션이 종료될 때까지 차단됩니다. 그렇지 않은 경우 애니메이션이 백그라운드에서 재생됩니다. +:param loop: ``loop``가 ``True``인 경우 애니메이션이 무한 반복됩니다. +:param clear: ``clear``가 ``True``인 경우 디스플레이는 시퀀스가 종료된 후 내용을 지웁니다. - The ``wait``, ``loop`` and ``clear`` arguments must be specified using their keyword. - """ +The ``wait``, ``loop`` and ``clear`` arguments must be specified using their keyword.""" ... -def scroll( - text: Union[str, float, int], - delay: int = 150, - wait: bool = True, - loop: bool = False, - monospace: bool = False, -) -> None: - """Scrolls a number or text on the LED display. - - Example: ``display.scroll('micro:bit')`` - - :param text: The string to scroll. If ``text`` is an integer or float it is first converted to a string using ``str()``. - :param delay: The ``delay`` parameter controls how fast the text is scrolling. - :param wait: If ``wait`` is ``True``, this function will block until the animation is finished, otherwise the animation will happen in the background. - :param loop: If ``loop`` is ``True``, the animation will repeat forever. - :param monospace: 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. - - The ``wait``, ``loop`` and ``monospace`` arguments must be specified - using their keyword. - """ +def scroll(text: Union[str, float, int], delay: int=150, wait: bool=True, loop: bool=False, monospace: bool=False) -> None: + """LED 디스플레이의 숫자 또는 텍스트를 스크롤합니다. + +Example: ``display.scroll('micro:bit')`` + +:param text: 스크롤할 문자열. 만약 ``text``가 정수 또는 부동수인 경우 먼저 ``str()``을 사용해 변환됩니다. +:param delay: ``delay`` 매개변수는 텍스트 스크롤링 속도를 조절합니다. +:param wait: ``wait``가 ``True``인 경우 이 기능은 애니메이션이 종료될 때까지 차단됩니다. 그렇지 않은 경우 애니메이션이 백그라운드에서 재생됩니다. +:param loop: ``loop``가 ``True``인 경우 애니메이션이 무한 반복됩니다. +:param monospace: ``monospace``가 ``True``인 경우 스크롤 중에 모든 글자는 5열의 픽셀만큼의 너비를 소모하며, 그렇지 않은 경우 글자 사이에 정확히 1열의 픽셀의 공백이 존재합니다. + +The ``wait``, ``loop`` and ``monospace`` arguments must be specified +using their keyword.""" ... def on() -> None: - """Turn on the LED display. + """LED 디스플레이를 켭니다. - Example: ``display.on()`` - """ +Example: ``display.on()``""" ... def off() -> None: - """Turn off the LED display (disabling the display allows you to re-use the GPIO pins for other purposes). + """LED 디스플레이를 끕니다(디스플레이를 비활성화하면 GPIO 핀을 다른 목적으로 재사용할 수 있습니다). - Example: ``display.off()`` - """ +Example: ``display.off()``""" ... def is_on() -> bool: - """Check whether the LED display is enabled. + """LED 디스플레이가 활성화되어있는지 확인합니다. - Example: ``display.is_on()`` +Example: ``display.is_on()`` - :return: ``True`` if the display is on, otherwise returns ``False``. - """ +:return: ``True`` if the display is on, otherwise returns ``False``.""" ... def read_light_level() -> int: - """Read the light level. + """밝기 레벨을 읽습니다. - Example: ``display.read_light_level()`` +Example: ``display.read_light_level()`` - Uses the display's LEDs in reverse-bias mode to sense the amount of light - falling on the display. +Uses the display's LEDs in reverse-bias mode to sense the amount of light +falling on the display. - :return: An integer between 0 and 255 representing the light level, with larger meaning more light. - """ - ... +:return: An integer between 0 and 255 representing the light level, with larger meaning more light.""" + ... \ No newline at end of file diff --git a/lang/ko/typeshed/stdlib/microbit/i2c.pyi b/lang/ko/typeshed/stdlib/microbit/i2c.pyi index df26efa..4fa2d4c 100644 --- a/lang/ko/typeshed/stdlib/microbit/i2c.pyi +++ b/lang/ko/typeshed/stdlib/microbit/i2c.pyi @@ -1,57 +1,49 @@ -"""Communicate with devices using the I²C bus protocol. -""" - +"""I²C 버스 프로토콜을 사용해 기기와 통신합니다.""" from _typeshed import ReadableBuffer from ..microbit import MicroBitDigitalPin, pin19, pin20 from typing import List -def init( - freq: int = 100000, sda: MicroBitDigitalPin = pin20, scl: MicroBitDigitalPin = pin19 -) -> None: - """Re-initialize a peripheral. +def init(freq: int=100000, sda: MicroBitDigitalPin=pin20, scl: MicroBitDigitalPin=pin19) -> None: + """주변 장치를 다시 초기화합니다. - Example: ``i2c.init()`` +Example: ``i2c.init()`` - :param freq: clock frequency - :param sda: ``sda`` pin (default 20) - :param scl: ``scl`` pin (default 19) +:param freq: 클럭 진동수 +:param sda: ``scl`` 핀(기본값 20) +:param scl: ``scl`` 핀(기본값 19) - On a micro:bit V1 board, changing the I²C pins from defaults will make - the accelerometer and compass stop working, as they are connected - internally to those pins. This warning does not apply to the **V2** - revision of the micro:bit as this has `separate I²C lines `_ - for the motion sensors and the edge connector. - """ +On a micro:bit V1 board, changing the I²C pins from defaults will make +the accelerometer and compass stop working, as they are connected +internally to those pins. This warning does not apply to the **V2** +revision of the micro:bit as this has `separate I²C lines `_ +for the motion sensors and the edge connector.""" ... def scan() -> List[int]: - """Scan the bus for devices. + """버스에서 장치를 스캔합니다. - Example: ``i2c.scan()`` +Example: ``i2c.scan()`` - :return: A list of 7-bit addresses corresponding to those devices that responded to the scan. - """ +:return: A list of 7-bit addresses corresponding to those devices that responded to the scan.""" ... -def read(addr: int, n: int, repeat: bool = False) -> bytes: - """Read bytes from a device. +def read(addr: int, n: int, repeat: bool=False) -> bytes: + """장치에서 바이트 값을 읽습니다. - Example: ``i2c.read(0x50, 64)`` +Example: ``i2c.read(0x50, 64)`` - :param addr: The 7-bit address of the device - :param n: The number of bytes to read - :param repeat: If ``True``, no stop bit will be sent - :return: The bytes read - """ +:param addr: 장치의 7비트 주소 +:param n: 읽을 바이트 수 +:param repeat: ``True``인 경우 스톱 비트가 전송되지 않습니다 +:return: The bytes read""" ... -def write(addr: int, buf: ReadableBuffer, repeat: bool = False) -> None: - """Write bytes to a device. +def write(addr: int, buf: ReadableBuffer, repeat: bool=False) -> None: + """장치에 바이트를 작성합니다. - Example: ``i2c.write(0x50, bytes([1, 2, 3]))`` +Example: ``i2c.write(0x50, bytes([1, 2, 3]))`` - :param addr: The 7-bit address of the device - :param buf: A buffer containing the bytes to write - :param repeat: If ``True``, no stop bit will be sent - """ - ... +:param addr: 장치의 7비트 주소 +:param buf: 작성할 바이트가 포함된 버퍼 +:param repeat: ``True``인 경우 스톱 비트가 전송되지 않습니다""" + ... \ No newline at end of file diff --git a/lang/ko/typeshed/stdlib/microbit/microphone.pyi b/lang/ko/typeshed/stdlib/microbit/microphone.pyi index 68e8f3a..9004514 100644 --- a/lang/ko/typeshed/stdlib/microbit/microphone.pyi +++ b/lang/ko/typeshed/stdlib/microbit/microphone.pyi @@ -1,70 +1,62 @@ -"""Respond to sound using the built-in microphone (V2 only). -""" - +"""내장 마이크를 사용해 소리에 반응합니다(V2 전용).""" from typing import Optional, Tuple from ..microbit import SoundEvent def current_event() -> Optional[SoundEvent]: - """Get the last recorded sound event + """마지막으로 기록된 소리 이벤트 - Example: ``microphone.current_event()`` +Example: ``microphone.current_event()`` - :return: The event, ``SoundEvent('loud')`` or ``SoundEvent('quiet')``. - """ +:return: The event, ``SoundEvent('loud')`` or ``SoundEvent('quiet')``.""" ... def was_event(event: SoundEvent) -> bool: - """Check if a sound was heard at least once since the last call. + """마지막 호출 이후로 소리가 들렸는지 확인합니다. - Example: ``microphone.was_event(SoundEvent.LOUD)`` +Example: ``microphone.was_event(SoundEvent.LOUD)`` - This call clears the sound history before returning. +This call clears the sound history before returning. - :param event: The event to check for, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET`` - :return: ``True`` if sound was heard at least once since the last call, otherwise ``False``. - """ +:param event: ``SoundEvent.LOUD`` 또는 ``SoundEvent.QUIET`` 등을 확인하기 위한 이벤트 +:return: ``True`` if sound was heard at least once since the last call, otherwise ``False``.""" ... def is_event(event: SoundEvent) -> bool: - """Check the most recent sound event detected. + """가장 최근 탐지된 소리 이벤트를 확인합니다. - Example: ``microphone.is_event(SoundEvent.LOUD)`` +Example: ``microphone.is_event(SoundEvent.LOUD)`` - This call does not clear the sound event history. +This call does not clear the sound event history. - :param event: The event to check for, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET`` - :return: ``True`` if sound was the most recent heard, ``False`` otherwise. - """ +:param event: ``SoundEvent.LOUD`` 또는 ``SoundEvent.QUIET`` 등을 확인하기 위한 이벤트 +:return: ``True`` if sound was the most recent heard, ``False`` otherwise.""" ... def get_events() -> Tuple[SoundEvent, ...]: - """Get the sound event history as a tuple. + """소리 이벤트 기록을 튜플로 가져옵니다. - Example: ``microphone.get_events()`` +Example: ``microphone.get_events()`` - This call clears the sound history before returning. +This call clears the sound history before returning. - :return: A tuple of the event history with the most recent event last. - """ +:return: A tuple of the event history with the most recent event last.""" ... def set_threshold(event: SoundEvent, value: int) -> None: - """Set the threshold for a sound event. + """소리 이벤트 임계값을 설정합니다. - Example: ``microphone.set_threshold(SoundEvent.LOUD, 250)`` +Example: ``microphone.set_threshold(SoundEvent.LOUD, 250)`` - A high threshold means the event will only trigger if the sound is very loud (>= 250 in the example). +A high threshold means the event will only trigger if the sound is very loud (>= 250 in the example). - :param event: A sound event, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET``. - :param value: The threshold level in the range 0-255. - """ +:param event: ``SoundEvent.LOUD`` 또는 ``SoundEvent.QUIET`` 등의 소리 이벤트입니다. +:param value: 0~255의 범위로 된 임계값입니다.""" ... def sound_level() -> int: - """Get the sound pressure level. + """음압 레벨을 불러옵니다. - Example: ``microphone.sound_level()`` +Example: ``microphone.sound_level()`` - :return: A representation of the sound pressure level in the range 0 to 255. - """ - ... +:return: A representation of the sound pressure level in the range 0 to 255.""" + ... \ No newline at end of file diff --git a/lang/ko/typeshed/stdlib/microbit/speaker.pyi b/lang/ko/typeshed/stdlib/microbit/speaker.pyi index 5a74a4d..ce3f1d8 100644 --- a/lang/ko/typeshed/stdlib/microbit/speaker.pyi +++ b/lang/ko/typeshed/stdlib/microbit/speaker.pyi @@ -1,18 +1,15 @@ -"""Control the built-in speaker (V2 only). -""" +"""내장 스피커를 제어합니다(V2 전용).""" def off() -> None: - """Turn the speaker off. + """스피커를 끕니다. - Example: ``speaker.off()`` +Example: ``speaker.off()`` - This does not disable sound output to an edge connector pin. - """ +This does not disable sound output to an edge connector pin.""" ... def on() -> None: - """Turn the speaker on. + """스피커를 켭니다. - Example: ``speaker.on()`` - """ - ... +Example: ``speaker.on()``""" + ... \ No newline at end of file diff --git a/lang/ko/typeshed/stdlib/microbit/spi.pyi b/lang/ko/typeshed/stdlib/microbit/spi.pyi index 09c4046..192f1a2 100644 --- a/lang/ko/typeshed/stdlib/microbit/spi.pyi +++ b/lang/ko/typeshed/stdlib/microbit/spi.pyi @@ -1,60 +1,47 @@ -"""Communicate with devices using the serial peripheral interface (SPI) bus. -""" - +"""직렬 주변 장치 인터페이스(SPI) 버스를 사용해 장치와 통신합니다.""" from _typeshed import ReadableBuffer, WriteableBuffer from ..microbit import pin13, pin14, pin15, MicroBitDigitalPin -def init( - baudrate: int = 1000000, - bits: int = 8, - mode: int = 0, - sclk: MicroBitDigitalPin = pin13, - mosi: MicroBitDigitalPin = pin15, - miso: MicroBitDigitalPin = pin14, -) -> None: - """Initialize SPI communication. - - Example: ``spi.init()`` - - For correct communication, the parameters have to be the same on both communicating devices. - - :param baudrate: The speed of communication. - :param bits: The width in bits of each transfer. Currently only ``bits=8`` is supported. However, this may change in the future. - :param mode: Determines the combination of clock polarity and phase - `see online table `_. - :param sclk: sclk pin (default 13) - :param mosi: mosi pin (default 15) - :param miso: miso pin (default 14) - """ +def init(baudrate: int=1000000, bits: int=8, mode: int=0, sclk: MicroBitDigitalPin=pin13, mosi: MicroBitDigitalPin=pin15, miso: MicroBitDigitalPin=pin14) -> None: + """SPI 통신을 시작합니다. (string) + +Example: ``spi.init()`` + +For correct communication, the parameters have to be the same on both communicating devices. + +:param baudrate: 통신 속도입니다. +:param bits: 각 전송의 비트의 너비입니다. 현재 ``bits=8``만 지원되나 향후 변경될 수 있습니다. +:param mode: 클럭 극성과 페이즈의 조합을 결정합니다. 온라인 테이블을 참조하세요 `_. +:param sclk: sclk 핀(기본값 13) +:param mosi: mosi 핀(기본값 15) +:param miso: miso 핀(기본값 14)""" ... -def read(nbytes: int, out: int = 0) -> bytes: - """Read at most ``nbytes`` while continuously writing the single byte given by ``out``. +def read(nbytes: int, out: int=0) -> bytes: + """바이트를 읽습니다. - Example: ``spi.read(64)`` +Example: ``spi.read(64)`` - :param nbytes: Maximum number of bytes to read. - :param out: The byte value to write (default 0). - :return: The bytes read. - """ +:param nbytes: 읽을 바이트의 최대 수입니다. +:param out: The byte value to write (default 0). +:return: The bytes read.""" ... def write(buffer: ReadableBuffer) -> None: - """Write bytes to the bus. + """버스에 바이트를 작성합니다. - Example: ``spi.write(bytes([1, 2, 3]))`` +Example: ``spi.write(bytes([1, 2, 3]))`` - :param buffer: A buffer to read data from. - """ +:param buffer: 데이터를 읽을 버퍼입니다.""" ... def write_readinto(out: WriteableBuffer, in_: ReadableBuffer) -> None: - """Write the ``out`` buffer to the bus and read any response into the ``in_`` buffer. + """버스에 ``out`` 버퍼를 작성하고 발생하는 ``in_`` 버퍼의 모든 응답을 읽습니다. - Example: ``spi.write_readinto(out_buffer, in_buffer)`` +Example: ``spi.write_readinto(out_buffer, in_buffer)`` - The length of the buffers should be the same. The buffers can be the same object. +The length of the buffers should be the same. The buffers can be the same object. - :param out: The buffer to write any response to. - :param in_: The buffer to read data from. - """ - ... +:param out: 응답을 작성할 버퍼입니다. +:param in_: 데이터를 읽을 버퍼입니다.""" + ... \ No newline at end of file diff --git a/lang/ko/typeshed/stdlib/microbit/uart.pyi b/lang/ko/typeshed/stdlib/microbit/uart.pyi index 2ab650f..f40a262 100644 --- a/lang/ko/typeshed/stdlib/microbit/uart.pyi +++ b/lang/ko/typeshed/stdlib/microbit/uart.pyi @@ -1,96 +1,79 @@ -"""Communicate with a device using a serial interface. -""" - +"""직렬 인터페이스를 사용해 장치와 통신합니다.""" from _typeshed import WriteableBuffer from ..microbit import MicroBitDigitalPin from typing import Optional, Union - ODD: int -"""Odd parity""" - +"""홀수 패리티""" EVEN: int -"""Even parity""" - -def init( - baudrate: int = 9600, - bits: int = 8, - parity: Optional[int] = None, - stop: int = 1, - tx: Optional[MicroBitDigitalPin] = None, - rx: Optional[MicroBitDigitalPin] = None, -) -> None: - """Initialize serial communication. - - Example: ``uart.init(115200, tx=pin0, rx=pin1)`` - - :param baudrate: The speed of communication. - :param bits: The size of bytes being transmitted. micro:bit only supports 8. - :param parity: How parity is checked, ``None``, ``uart.ODD`` or ``uart.EVEN``. - :param stop: The number of stop bits, has to be 1 for micro:bit. - :param tx: Transmitting pin. - :param rx: Receiving pin. - - 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. - - For more details see `the online documentation `_. - """ +"""짝수 패리티""" + +def init(baudrate: int=9600, bits: int=8, parity: Optional[int]=None, stop: int=1, tx: Optional[MicroBitDigitalPin]=None, rx: Optional[MicroBitDigitalPin]=None) -> None: + """직렬 통신을 시작합니다. (string) + +Example: ``uart.init(115200, tx=pin0, rx=pin1)`` + +:param baudrate: 통신 속도입니다. +:param bits: 전송되는 바이트의 크기입니다. micro:bit는 8바이트만 지원합니다. +:param parity: (패리티) 패리티가 체크되는 방식으로 ``None``, ``uart.ODD`` 또는 ``uart.EVEN``을 사용합니다. +:param stop: 스톱 비트의 번호입니다. micro:bit는 1이어야 합니다. +:param tx: 전송하는 핀입니다. +:param rx: 수신하는 핀입니다. + +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. + +For more details see `the online documentation `_.""" ... def any() -> bool: - """Check if any data is waiting. + """대기 중인 데이터가 있는지 확인합니다. - Example: ``uart.any()`` +Example: ``uart.any()`` - :return: ``True`` if any data is waiting, else ``False``. - """ +:return: ``True`` if any data is waiting, else ``False``.""" ... -def read(nbytes: Optional[int] = None) -> Optional[bytes]: - """Read bytes. +def read(nbytes: Optional[int]=None) -> Optional[bytes]: + """바이트를 읽습니다. - Example: ``uart.read()`` +Example: ``uart.read()`` - :param nbytes: If ``nbytes`` is specified then read at most that many bytes, otherwise read as many bytes as possible - :return: A bytes object or ``None`` on timeout - """ +:param nbytes: ``nbytes``가 특정되어 있다면 해당 바이트 수만큼 읽습니다. 특정되지 않은 경우 최대한 많은 바이트를 읽습니다. +:return: A bytes object or ``None`` on timeout""" ... -def readinto(buf: WriteableBuffer, nbytes: Optional[int] = None) -> Optional[int]: - """Read bytes into the ``buf``. +def readinto(buf: WriteableBuffer, nbytes: Optional[int]=None) -> Optional[int]: + """``buf``로 바이트를 읽습니다. - Example: ``uart.readinto(input_buffer)`` +Example: ``uart.readinto(input_buffer)`` - :param buf: The buffer to write to. - :param nbytes: If ``nbytes`` is specified then read at most that many bytes, otherwise read ``len(buf)`` bytes. - :return: number of bytes read and stored into ``buf`` or ``None`` on timeout. - """ +:param buf: 바이트를 기록할 버퍼입니다. +:param nbytes: ``nbytes``가 특정되어 있다면 해당 바이트 수만큼 읽습니다. 특정되지 않은 경우 ``len(buf)``바이트를 읽습니다. +:return: number of bytes read and stored into ``buf`` or ``None`` on timeout.""" ... def readline() -> Optional[bytes]: - """Read a line, ending in a newline character. + """새로운 줄 문자로 끝나는 줄을 읽습니다. - Example: ``uart.readline()`` +Example: ``uart.readline()`` - :return: The line read or ``None`` on timeout. The newline character is included in the returned bytes. - """ +:return: The line read or ``None`` on timeout. The newline character is included in the returned bytes.""" ... def write(buf: Union[bytes, str]) -> Optional[int]: - """Write a buffer to the bus. + """버스에 버퍼를 기록합니다. - Example: ``uart.write('hello world')`` +Example: ``uart.write('hello world')`` - :param buf: A bytes object or a string. - :return: The number of bytes written, or ``None`` on timeout. +:param buf: 바이트 오브젝트 또는 문자열입니다. +:return: The number of bytes written, or ``None`` on timeout. - Examples:: +Examples:: - uart.write('hello world') - uart.write(b'hello world') - uart.write(bytes([1, 2, 3])) - """ - ... + uart.write('hello world') + uart.write(b'hello world') + uart.write(bytes([1, 2, 3]))""" + ... \ No newline at end of file diff --git a/lang/ko/typeshed/stdlib/micropython.pyi b/lang/ko/typeshed/stdlib/micropython.pyi index 7a6079f..1f469da 100644 --- a/lang/ko/typeshed/stdlib/micropython.pyi +++ b/lang/ko/typeshed/stdlib/micropython.pyi @@ -1,144 +1,131 @@ -"""MicroPython internals.""" - +"""MicroPython 내부 정보입니다.""" from typing import Any, TypeVar, overload - -_T = TypeVar("_T") +_T = TypeVar('_T') def const(expr: _T) -> _T: - """Used to declare that the expression is a constant so that the compiler can - optimise it. + """컴파일러가 최적화할 수 있도록 해당 수식이 상수임을 선언합니다. - The use of this function should be as follows:: +The use of this function should be as follows:: - from micropython import const - CONST_X = const(123) - CONST_Y = const(2 * CONST_X + 1) + from micropython import const + CONST_X = const(123) + CONST_Y = const(2 * CONST_X + 1) - Constants declared this way are still accessible as global variables from - outside the module they are declared in. On the other hand, if a constant - begins with an underscore then it is hidden, it is not available as a - global variable, and does not take up any memory during execution. +Constants declared this way are still accessible as global variables from +outside the module they are declared in. On the other hand, if a constant +begins with an underscore then it is hidden, it is not available as a +global variable, and does not take up any memory during execution. - :param expr: A constant expression. - """ +:param expr: 상수 표현식입니다.""" ... @overload def opt_level() -> int: - """Get the current optimisation level for the compilation of scripts. + """스크립트의 현재 컴파일 최적화 레벨을 불러옵니다. - Example: ``micropython.opt_level()`` +Example: ``micropython.opt_level()`` - The optimisation level controls the following compilation features: +The optimisation level controls the following compilation features: - - Assertions: at level 0 assertion statements are enabled and compiled - into the bytecode; at levels 1 and higher assertions are not compiled. +- Assertions: at level 0 assertion statements are enabled and compiled + into the bytecode; at levels 1 and higher assertions are not compiled. - - Built-in ``__debug__`` variable: at level 0 this variable expands to - True; at levels 1 and higher it expands to False. +- Built-in ``__debug__`` variable: at level 0 this variable expands to + True; at levels 1 and higher it expands to False. - - Source-code line numbers: at levels 0, 1 and 2 source-code line number - are stored along with the bytecode so that exceptions can report the - line number they occurred at; at levels 3 and higher line numbers are - not stored. +- Source-code line numbers: at levels 0, 1 and 2 source-code line number + are stored along with the bytecode so that exceptions can report the + line number they occurred at; at levels 3 and higher line numbers are + not stored. - :return: An integer representing the current level. - """ +:return: An integer representing the current level.""" ... @overload def opt_level(level: int) -> None: - """Sets the optimisation level for subsequent compilation of scripts. + """스크립트의 후속 컴파일 최적화 레벨을 설정합니다. - Example: ``micropython.opt_level(1)`` +Example: ``micropython.opt_level(1)`` - The optimisation level controls the following compilation features: +The optimisation level controls the following compilation features: - - Assertions: at level 0 assertion statements are enabled and compiled - into the bytecode; at levels 1 and higher assertions are not compiled. +- Assertions: at level 0 assertion statements are enabled and compiled + into the bytecode; at levels 1 and higher assertions are not compiled. - - Built-in ``__debug__`` variable: at level 0 this variable expands to - True; at levels 1 and higher it expands to False. +- Built-in ``__debug__`` variable: at level 0 this variable expands to + True; at levels 1 and higher it expands to False. - - Source-code line numbers: at levels 0, 1 and 2 source-code line number - are stored along with the bytecode so that exceptions can report the - line number they occurred at; at levels 3 and higher line numbers are - not stored. +- Source-code line numbers: at levels 0, 1 and 2 source-code line number + are stored along with the bytecode so that exceptions can report the + line number they occurred at; at levels 3 and higher line numbers are + not stored. - The default optimisation level is usually level 0. +The default optimisation level is usually level 0. - :param level: An integer optimisation level. - """ +:param level: 정수로 된 최적화 레벨입니다.""" ... -def mem_info(verbose: Any = None) -> None: - """Print information about currently used memory. +def mem_info(verbose: Any=None) -> None: + """현재 사용 중인 메모리에 대한 정보를 프린트합니다. - Example: ``micropython.mem_info()`` +Example: ``micropython.mem_info()`` - :param verbose: If the ``verbose`` argument is given then extra information is printed. - """ +:param verbose: ``verbose`` 인자가 주어지면 추가 정보를 프린트합니다.""" ... -def qstr_info(verbose: Any = None) -> None: - """Print information about currently interned strings. +def qstr_info(verbose: Any=None) -> None: + """현재 반환된 문자열에 대한 정보를 프린트합니다. - Example: ``micropython.qstr_info()`` +Example: ``micropython.qstr_info()`` - :param verbose: If the ``verbose`` argument is given then extra information is printed. +:param verbose: ``verbose`` 인자가 주어지면 추가 정보를 프린트합니다. - The information that is printed is implementation dependent, but currently - includes the number of interned strings and the amount of RAM they use. In - verbose mode it prints out the names of all RAM-interned strings. - """ +The information that is printed is implementation dependent, but currently +includes the number of interned strings and the amount of RAM they use. In +verbose mode it prints out the names of all RAM-interned strings.""" ... def stack_use() -> int: - """Return an integer representing the current amount of stack that is being - used. + """현재 사용 중인 스택의 수를 나타내는 정수를 반환합니다. - Example: ``micropython.stack_use()`` +Example: ``micropython.stack_use()`` - The absolute value of this is not particularly useful, rather it - should be used to compute differences in stack usage at different points. +The absolute value of this is not particularly useful, rather it +should be used to compute differences in stack usage at different points. - :return: An integer representing current stack use. - """ +:return: An integer representing current stack use.""" ... def heap_lock() -> None: - """Lock the heap. + """힙을 잠급니다. - Example: ``micropython.heap_lock()`` +Example: ``micropython.heap_lock()`` - When locked no memory allocation can occur and a ``MemoryError`` will be - raised if any heap allocation is attempted. - """ +When locked no memory allocation can occur and a ``MemoryError`` will be +raised if any heap allocation is attempted.""" ... def heap_unlock() -> None: - """Unlock the heap. + """힙을 잠금 해제합니다. - Example: ``micropython.heap_unlock()`` +Example: ``micropython.heap_unlock()`` - When locked no memory allocation can occur and a ``MemoryError`` will be - raised if any heap allocation is attempted. - """ +When locked no memory allocation can occur and a ``MemoryError`` will be +raised if any heap allocation is attempted.""" ... def kbd_intr(chr: int) -> None: - """Set the character that will raise a ``KeyboardInterrupt`` exception. + """``KeyboardInterrupt`` 예외를 제기할 문자를 설정합니다. - Example: ``micropython.kbd_intr(-1)`` +Example: ``micropython.kbd_intr(-1)`` - :param chr: Character code to raise the interrupt or -1 to disable capture of Ctrl-C. +:param chr: 인터럽트를 제기하기 위한 문자 코드입니다. -1은 Ctrl-C 캡처를 비활성화합니다. - By default this is set to 3 during script execution, corresponding to Ctrl-C. - Passing -1 to this function will disable capture of Ctrl-C, and passing 3 - will restore it. +By default this is set to 3 during script execution, corresponding to Ctrl-C. +Passing -1 to this function will disable capture of Ctrl-C, and passing 3 +will restore it. - This function can be used to prevent the capturing of Ctrl-C on the - incoming stream of characters that is usually used for the REPL, in case - that stream is used for other purposes. - """ - ... +This function can be used to prevent the capturing of Ctrl-C on the +incoming stream of characters that is usually used for the REPL, in case +that stream is used for other purposes.""" + ... \ No newline at end of file diff --git a/lang/ko/typeshed/stdlib/music.pyi b/lang/ko/typeshed/stdlib/music.pyi index 5f4778b..e61bcd8 100644 --- a/lang/ko/typeshed/stdlib/music.pyi +++ b/lang/ko/typeshed/stdlib/music.pyi @@ -1,167 +1,128 @@ -"""Create and play melodies. -""" +"""멜로디를 생성하고 재생합니다.""" from typing import Optional, Tuple, Union, List - from .microbit import MicroBitDigitalPin, pin0 - DADADADUM: Tuple[str, ...] -"""Melody: the opening to Beethoven’s 5th Symphony in C minor.""" - +"""멜로디: 베토벤의 교향곡 제5번 다 단조 도입부입니다.""" ENTERTAINER: Tuple[str, ...] -"""Melody: the opening fragment of Scott Joplin’s Ragtime classic “The Entertainer”.""" - +"""멜로디: 스콧 조플린의 래그타임 고전 “The Entertainer” 도입부 일부입니다.""" PRELUDE: Tuple[str, ...] -"""Melody: the opening of the first Prelude in C Major of J.S.Bach’s 48 Preludes and Fugues.""" - +"""멜로디: 요한 제바스티안 바흐의 48 Preludes and Fugues 다 장조 첫 전주곡 도입부입니다.""" ODE: Tuple[str, ...] -"""Melody: the “Ode to Joy” theme from Beethoven’s 9th Symphony in D minor.""" - +"""멜로디: 베토벤의 교향곡 제9번 라 단조 “Ode to Joy” 테마입니다.""" NYAN: Tuple[str, ...] -"""Melody: the Nyan Cat theme (http://www.nyan.cat/). +"""멜로디: Nyan Cat 테마입니다(http://www.nyan.cat/). The composer is unknown. This is fair use for educational porpoises (as they say in New York).""" - RINGTONE: Tuple[str, ...] -"""Melody: something that sounds like a mobile phone ringtone. +"""멜로디: 휴대폰 벨소리와 유사한 소리입니다. To be used to indicate an incoming message. """ - FUNK: Tuple[str, ...] -"""Melody: a funky bass line for secret agents and criminal masterminds.""" - +"""멜로디: 비밀 요원과 천재 범죄자에 어울리는 펑키 베이스 라인입니다.""" BLUES: Tuple[str, ...] -"""Melody: a boogie-woogie 12-bar blues walking bass.""" - +"""멜로디: 부기 우기 12바 블루스 워킹 베이스입니다.""" BIRTHDAY: Tuple[str, ...] -"""Melody: “Happy Birthday to You…” +"""멜로디: 생일 축하 노래입니다. For copyright status see: http://www.bbc.co.uk/news/world-us-canada-34332853 """ - WEDDING: Tuple[str, ...] -"""Melody: the bridal chorus from Wagner’s opera “Lohengrin”.""" - +"""Melody: 바그너의 오페라 “로엔그린”의 결혼식 합창입니다.""" FUNERAL: Tuple[str, ...] -"""Melody: the “funeral march” otherwise known as Frédéric Chopin’s Piano Sonata No. 2 in B♭ minor, Op. 35.""" - +"""멜로디: “장송행진곡”이라고도 알려진 프레데리크 쇼팽의 피아노 소나타 제2번 B♭ 단조 Op. 35입니다.""" PUNCHLINE: Tuple[str, ...] -"""Melody: a fun fragment that signifies a joke has been made.""" - +"""멜로디: 농담할 때 나오는 재미있는 멜로디입니다.""" PYTHON: Tuple[str, ...] -"""Melody: John Philip Sousa’s march “Liberty Bell” aka, the theme for “Monty Python’s Flying Circus” (after which the Python programming language is named).""" - +"""멜로디: 존 필립 수자의 “자유의 종” 행진곡입니다. “몬티 파이튼의 비행 서커스” 테마곡으로도 알려져 있습니다(Python 프로그래밍 언어는 몬티 파이튼의 이름에서 유래했습니다).""" BADDY: Tuple[str, ...] -"""Melody: silent movie era entrance of a baddy.""" - +"""멜로디: 무성 영화 시대의 악당 등장 멜로디입니다.""" CHASE: Tuple[str, ...] -"""Melody: silent movie era chase scene.""" - +"""멜로디: 무성 영화 시대의 추격 장면 멜로디입니다.""" BA_DING: Tuple[str, ...] -"""Melody: a short signal to indicate something has happened.""" - +"""멜로디:어떤 일이 일어났다는 것을 알려주는 짧은 신호음입니다.""" WAWAWAWAA: Tuple[str, ...] -"""Melody: a very sad trombone.""" - +"""멜로디: 아주 슬픈 트럼본 소리입니다.""" JUMP_UP: Tuple[str, ...] -"""Melody: for use in a game, indicating upward movement.""" - +"""멜로디: 게임에서 위로 움직이는 것을 표현하는 소리입니다.""" JUMP_DOWN: Tuple[str, ...] -"""Melody: for use in a game, indicating downward movement.""" - +"""멜로디: 게임에서 아래로 움직이는 것을 표현하는 소리입니다.""" POWER_UP: Tuple[str, ...] -"""Melody: a fanfare to indicate an achievement unlocked.""" - +"""멜로디: 업적 달성을 알리는 팡파르 소리입니다.""" POWER_DOWN: Tuple[str, ...] -"""Melody: a sad fanfare to indicate an achievement lost.""" +"""멜로디: 업적 달성 실패를 의미하는 슬픈 팡파르 소리입니다.""" -def set_tempo(ticks: int = 4, bpm: int = 120) -> None: - """Sets the approximate tempo for playback. +def set_tempo(ticks: int=4, bpm: int=120) -> None: + """플레이백의 빠르기를 대략적으로 설정합니다. - Example: ``music.set_tempo(bpm=120)`` +Example: ``music.set_tempo(bpm=120)`` - :param ticks: The number of ticks constituting a beat. - :param bpm: An integer determining how many beats per minute. +:param ticks: 비트 하나를 구성하는 틱의 수입니다. +:param bpm: 분당 비트 수를 결정하는 정수입니다. - Suggested default values allow the following useful behaviour: +Suggested default values allow the following useful behaviour: - - music.set_tempo() – reset the tempo to default of ticks = 4, bpm = 120 - - music.set_tempo(ticks=8) – change the “definition” of a beat - - music.set_tempo(bpm=180) – just change the tempo +- music.set_tempo() – reset the tempo to default of ticks = 4, bpm = 120 +- music.set_tempo(ticks=8) – change the “definition” of a beat +- music.set_tempo(bpm=180) – just change the tempo - To work out the length of a tick in milliseconds is very simple arithmetic: - 60000/bpm/ticks_per_beat. For the default values that’s - 60000/120/4 = 125 milliseconds or 1 beat = 500 milliseconds. - """ +To work out the length of a tick in milliseconds is very simple arithmetic: +60000/bpm/ticks_per_beat. For the default values that’s +60000/120/4 = 125 milliseconds or 1 beat = 500 milliseconds.""" ... def get_tempo() -> Tuple[int, int]: - """Gets the current tempo as a tuple of integers: ``(ticks, bpm)``. + """현재 빠르기를 정수 튜플로 가져옵니다: ``(ticks, bpm)``. - Example: ``ticks, beats = music.get_tempo()`` +Example: ``ticks, beats = music.get_tempo()`` - :return: The temp as a tuple with two integer values, the ticks then the beats per minute. - """ +:return: The temp as a tuple with two integer values, the ticks then the beats per minute.""" ... -def play( - music: Union[str, List[str], Tuple[str, ...]], - pin: Optional[MicroBitDigitalPin] = pin0, - wait: bool = True, - loop: bool = False, -) -> None: - """Plays music. +def play(music: Union[str, List[str], Tuple[str, ...]], pin: Optional[MicroBitDigitalPin]=pin0, wait: bool=True, loop: bool=False) -> None: + """음악을 재생합니다. - Example: ``music.play(music.NYAN)`` +Example: ``music.play(music.NYAN)`` - :param music: music specified in `a special notation `_ - :param pin: the output pin for use with an external speaker (default ``pin0``), ``None`` for no sound. - :param wait: If ``wait`` is set to ``True``, this function is blocking. - :param loop: If ``loop`` is set to ``True``, the tune repeats until ``stop`` is called or the blocking call is interrupted. +:param music: `별첨 `_에 명시된 음악 +:param pin: (핀) 외장 스피커에 사용할 출력 핀입니다(기본값 ``pin0``). ``None``으로 설정하면 소리가 재생되지 않습니다. +:param wait: ``wait``이 ``True``로 설정된 경우 이 기능은 블로킹 상태가 됩니다. +:param loop: ``loop``가 ``True``인 경우 ``stop``이 호출되거나 블로킹 호출이 인터럽트되기 전까지 계속 반복됩니다. - Many built-in melodies are defined in this module. - """ +Many built-in melodies are defined in this module.""" ... -def pitch( - frequency: int, - duration: int = -1, - pin: Optional[MicroBitDigitalPin] = pin0, - wait: bool = True, -) -> None: - """Play a note. +def pitch(frequency: int, duration: int=-1, pin: Optional[MicroBitDigitalPin]=pin0, wait: bool=True) -> None: + """음을 재생합니다. (앞-뒤 기울기) - Example: ``music.pitch(185, 1000)`` +Example: ``music.pitch(185, 1000)`` - :param frequency: An integer frequency - :param duration: A millisecond duration. If negative then sound is continuous until the next call or a call to ``stop``. - :param pin: Optional output pin (default ``pin0``). - :param wait: If ``wait`` is set to ``True``, this function is blocking. +:param frequency: (진동수) 정수 진동수입니다. +:param duration: 밀리초 단위의 기간입니다. 음수인 경우 소리가 다음 호출 또는 ``stop`` 호출까지 계속 재생됩니다. +:param pin: (핀) 출력 핀입니다(기본값 ``pin0``)(선택 사항). +:param wait: ``wait``이 ``True``로 설정된 경우 이 기능은 블로킹 상태가 됩니다. - For example, if the frequency is set to 440 and the length to - 1000 then we hear a standard concert A for one second. +For example, if the frequency is set to 440 and the length to +1000 then we hear a standard concert A for one second. - You can only play one pitch on one pin at any one time. - """ +You can only play one pitch on one pin at any one time.""" ... -def stop(pin: Optional[MicroBitDigitalPin] = pin0) -> None: - """Stops all music playback on the built-in speaker and any pin outputting sound. +def stop(pin: Optional[MicroBitDigitalPin]=pin0) -> None: + """내장 스피커와 핀으로 출력되는 모든 음악 플레이백을 멈춥니다. - Example: ``music.stop()`` +Example: ``music.stop()`` - :param pin: An optional argument can be provided to specify a pin, e.g. ``music.stop(pin1)``. - """ +:param pin: (핀) 핀을 특정하기 위한 인자입니다(예: ``music.stop(pin1)``)(선택 사항).""" def reset() -> None: - """Resets ticks, bpm, duration and octave to their default values. + """틱, bpm, 기간 및 옥타브를 기본값으로 초기화합니다. - Example: ``music.reset()`` +Example: ``music.reset()`` - Values: - - ``ticks = 4`` - - ``bpm = 120`` - - ``duration = 4`` - - ``octave = 4`` - """ - ... +Values: +- ``ticks = 4`` +- ``bpm = 120`` +- ``duration = 4`` +- ``octave = 4``""" + ... \ No newline at end of file diff --git a/lang/ko/typeshed/stdlib/neopixel.pyi b/lang/ko/typeshed/stdlib/neopixel.pyi index 2d5a749..275839b 100644 --- a/lang/ko/typeshed/stdlib/neopixel.pyi +++ b/lang/ko/typeshed/stdlib/neopixel.pyi @@ -1,82 +1,81 @@ -"""Individually addressable RGB and RGBW LED strips. -""" +"""개별 주소를 지정할 수 있는 RGB 및 RGBW LED 스트립입니다.""" from .microbit import MicroBitDigitalPin from typing import Tuple class NeoPixel: - def __init__(self, pin: MicroBitDigitalPin, n: int, bpp: int = 3) -> None: - """Initialise a new strip of neopixel LEDs controlled via a pin. - Example: ``np = neopixel.NeoPixel(pin0, 8)`` + def __init__(self, pin: MicroBitDigitalPin, n: int, bpp: int=3) -> None: + """핀으로 제어되는 새로운 스트립의 네오픽셀 LED를 시작합니다. (string) - To support RGBW neopixels, a third argument can be passed to - ``NeoPixel`` to indicate the number of bytes per pixel (``bpp``). - For RGBW, this is is 4 rather than the default of 3 for RGB and GRB. +Example: ``np = neopixel.NeoPixel(pin0, 8)`` - Each pixel is addressed by a position (starting from 0). Neopixels are - given RGB (red, green, blue) / RGBW (red, green, blue, white) values - between 0-255 as a tuple. For example, in RGB, ``(255,255,255)`` is - white. In RGBW, ``(255,255,255,0)`` or ``(0,0,0,255)`` is white. +To support RGBW neopixels, a third argument can be passed to +``NeoPixel`` to indicate the number of bytes per pixel (``bpp``). +For RGBW, this is is 4 rather than the default of 3 for RGB and GRB. - See `the online docs `_ for warnings and other advice. +Each pixel is addressed by a position (starting from 0). Neopixels are +given RGB (red, green, blue) / RGBW (red, green, blue, white) values +between 0-255 as a tuple. For example, in RGB, ``(255,255,255)`` is +white. In RGBW, ``(255,255,255,0)`` or ``(0,0,0,255)`` is white. - :param pin: The pin controlling the neopixel strip. - :param n: The number of neopixels in the strip. - :param bpp: Bytes per pixel. For RGBW neopixel support, pass 4 rather than the default of 3 for RGB and GRB. - """ +See `the online docs `_ for warnings and other advice. + +:param pin: (핀) 네오픽셀 스트립을 제어하는 핀입니다. +:param n: 스트립의 네오픽셀 수입니다. +:param bpp: 픽셀당 바이트입니다. RGBW 네오픽셀 지원을 위해서는 RGB 및 GRB의 기본값 3 대신 4를 패스해야 합니다.""" ... + def clear(self) -> None: - """Clear all the pixels. + """모든 픽셀을 지웁니다. - Example: ``np.clear()`` - """ +Example: ``np.clear()``""" ... + def show(self) -> None: - """Show the pixels. + """픽셀을 표시합니다. - Example: ``np.show()`` +Example: ``np.show()`` - Must be called for any updates to become visible. - """ +Must be called for any updates to become visible.""" ... + def write(self) -> None: - """Show the pixels (micro:bit V2 only). + """픽셀을 표시합니다(micro:bit V2 전용). - Example: ``np.write()`` +Example: ``np.write()`` - Must be called for any updates to become visible. +Must be called for any updates to become visible. - Equivalent to ``show``. - """ +Equivalent to ``show``.""" ... + def fill(self, colour: Tuple[int, ...]) -> None: - """Colour all pixels a given RGB/RGBW value (micro:bit V2 only). + """모든 픽셀에 주어진 RGB/RGBW 값을 칠합니다(micro:bit V2 전용). - Example: ``np.fill((0, 0, 255))`` +Example: ``np.fill((0, 0, 255))`` - :param colour: A tuple of the same length as the number of bytes per pixel (bpp). +:param colour: 픽셀 당 바이트 수(bpp)와 같은 길이의 튜플입니다. - Use in conjunction with ``show()`` to update the neopixels. - """ +Use in conjunction with ``show()`` to update the neopixels.""" ... + def __setitem__(self, key: int, value: Tuple[int, ...]) -> None: - """Set a pixel colour. + """픽셀 색상을 설정합니다. - Example: ``np[0] = (255, 0, 0)`` +Example: ``np[0] = (255, 0, 0)`` + +:param key: 픽셀 번호입니다. +:param value: 색상입니다.""" - :param key: The pixel number. - :param value: The colour. - """ def __getitem__(self, key: int) -> Tuple[int, ...]: - """Get a pixel colour. + """픽셀 색상을 불러옵니다. + +Example: ``r, g, b = np[0]`` - Example: ``r, g, b = np[0]`` +:param key: 픽셀 번호입니다. +:return: The colour tuple.""" - :param key: The pixel number. - :return: The colour tuple. - """ def __len__(self) -> int: - """Get length of this pixel strip. + """이 픽셀 스트립의 길이를 불러옵니다. - Example: ``len(np)`` - """ +Example: ``len(np)``""" \ No newline at end of file diff --git a/lang/ko/typeshed/stdlib/os.pyi b/lang/ko/typeshed/stdlib/os.pyi index 2f2db77..510ffbf 100644 --- a/lang/ko/typeshed/stdlib/os.pyi +++ b/lang/ko/typeshed/stdlib/os.pyi @@ -1,73 +1,63 @@ -"""Access the file system. -""" - +"""파일 시스템에 액세스합니다.""" from typing import Tuple from typing import List def listdir() -> List[str]: - """List files. + """파일을 나열합니다. - Example: ``os.listdir()`` +Example: ``os.listdir()`` - :return: A list of the names of all the files contained within the local - persistent on-device file system. - """ +:return: A list of the names of all the files contained within the local +persistent on-device file system.""" ... def remove(filename: str) -> None: - """Remove (delete) a file. + """파일을 제거(삭제)합니다. - Example: ``os.remove('data.txt')`` +Example: ``os.remove('data.txt')`` - :param filename: The file to delete. +:param filename: 삭제할 파일입니다. - If the file does not exist an ``OSError`` exception will occur. - """ +If the file does not exist an ``OSError`` exception will occur.""" ... def size(filename: str) -> int: - """Returns the size of a file. + """파일의 크기를 반환합니다. - Example: ``os.size('data.txt')`` +Example: ``os.size('data.txt')`` - :param filename: The file - :return: The size in bytes. +:param filename: 파일 +:return: The size in bytes. - If the file does not exist an ``OSError`` exception will occur. - """ +If the file does not exist an ``OSError`` exception will occur.""" class uname_result(Tuple[str, str, str, str, str]): - """Result of ``os.uname()``""" + """``os.uname()``의 결과""" sysname: str - """Operating system name.""" - + """운영 체제 이름입니다.""" nodename: str - """Name of machine on network (implementation-defined).""" - + """네트워크상의 머신 이름입니다(구현 방법에 따라 정의됨).""" release: str - """Operating system release.""" - + """운영 체제 릴리스입니다.""" version: str - """Operating system version.""" - + """운영 체제 버전입니다.""" machine: str - """Hardware identifier.""" + """하드웨어 식별자입니다.""" def uname() -> uname_result: - """Returns information identifying the current operating system. + """현재 운영 시스템을 식별하는 정보를 반환합니다. - Example: ``os.uname()`` +Example: ``os.uname()`` - The return value is an object with five attributes: +The return value is an object with five attributes: - - ``sysname`` - operating system name - - ``nodename`` - name of machine on network (implementation-defined) - - ``release`` - operating system release - - ``version`` - operating system version - - ``machine`` - hardware identifier +- ``sysname`` - operating system name +- ``nodename`` - name of machine on network (implementation-defined) +- ``release`` - operating system release +- ``version`` - operating system version +- ``machine`` - hardware identifier - There is no underlying operating system in MicroPython. As a result the - information returned by the ``uname`` function is mostly useful for - versioning details. - """ - ... +There is no underlying operating system in MicroPython. As a result the +information returned by the ``uname`` function is mostly useful for +versioning details.""" + ... \ No newline at end of file diff --git a/lang/ko/typeshed/stdlib/radio.pyi b/lang/ko/typeshed/stdlib/radio.pyi index 8dd0267..48868c8 100644 --- a/lang/ko/typeshed/stdlib/radio.pyi +++ b/lang/ko/typeshed/stdlib/radio.pyi @@ -1,152 +1,125 @@ -"""Communicate between micro:bits with the built-in radio. -""" - +"""내장 라디오를 사용해 micro:bit끼리 통신합니다.""" from _typeshed import WriteableBuffer from typing import Optional, Tuple - RATE_1MBIT: int -"""Constant used to indicate a throughput of 1 MBit a second.""" - +"""초당 1 MBit의 처리율을 지정하는 데 사용하는 상수""" RATE_2MBIT: int -"""Constant used to indicate a throughput of 2 MBit a second.""" +"""초당 2 MBit의 처리율을 지정하는 데 사용하는 상수.""" def on() -> None: - """Turns the radio on. + """라디오를 켭니다. - Example: ``radio.on()`` +Example: ``radio.on()`` - This needs to be explicitly called since the radio draws power and takes - up memory that you may otherwise need. - """ +This needs to be explicitly called since the radio draws power and takes +up memory that you may otherwise need.""" ... def off() -> None: - """Turns off the radio, saving power and memory. + """라디오를 꺼 전력과 메모리를 절약합니다. - Example: ``radio.off()`` - """ +Example: ``radio.off()``""" ... -def config( - length: int = 32, - queue: int = 3, - channel: int = 7, - power: int = 6, - address: int = 0x75626974, - group: int = 0, - data_rate: int = RATE_1MBIT, -) -> None: - """Configures the radio. - - Example: ``radio.config(group=42)`` - - The default configuration is suitable for most use. - - :param length: (default=32) defines the maximum length, in bytes, of a message sent via the radio. - It can be up to 251 bytes long (254 - 3 bytes for S0, LENGTH and S1 preamble). - :param queue: (default=3) specifies the number of messages that can be stored on the incoming message queue. - If there are no spaces left on the queue for incoming messages, then the incoming message is dropped. - :param channel: (default=7) an integer value from 0 to 83 (inclusive) that defines an arbitrary "channel" to which the radio is tuned. - Messages will be sent via this channel and only messages received via this channel will be put onto the incoming message queue. Each step is 1MHz wide, based at 2400MHz. - :param power: (default=6) is an integer value from 0 to 7 (inclusive) to indicate the strength of signal used when broadcasting a message. - The higher the value the stronger the signal, but the more power is consumed by the device. The numbering translates to positions in the following list of dBm (decibel milliwatt) values: -30, -20, -16, -12, -8, -4, 0, 4. - :param address: (default=0x75626974) an arbitrary name, expressed as a 32-bit address, that's used to filter incoming packets at the hardware level, keeping only those that match the address you set. - The default used by other micro:bit related platforms is the default setting used here. - :param group: (default=0) an 8-bit value (0-255) used with the ``address`` when filtering messages. - Conceptually, "address" is like a house/office address and "group" is like the person at that address to which you want to send your message. - :param data_rate: (default=``radio.RATE_1MBIT``) indicates the speed at which data throughput takes place. - Can be one of the following constants defined in the ``radio`` module: ``RATE_250KBIT``, ``RATE_1MBIT`` or ``RATE_2MBIT``. - - If ``config`` is not called then the defaults described above are assumed. - """ +def config(length: int=32, queue: int=3, channel: int=7, power: int=6, address: int=1969383796, group: int=0, data_rate: int=RATE_1MBIT) -> None: + """라디오를 설정합니다. + +Example: ``radio.config(group=42)`` + +The default configuration is suitable for most use. + +:param length: (기본값=32) 라디오를 통해 전송되는 메시지의 최대 길이를 바이트로 정의합니다. +최대 251바이트까지 정의할 수 있습니다(S0, LENGTH 및 S1 프리앰블의 경우 254 - 3바이트). +:param queue: (기본값=3) 수신 메시지 대기열에 보관할 수 있는 메시지의 수를 특정합니다. 만약 수신 메시지의 대기열 공간이 부족하다면 수신 메시지는 드롭됩니다. +:param channel: (기본값=7) 임의의 "채널"을 라디오 채널로 설정하는 0부터 83까지의 정수(경계값 포함)입니다. 메시지는 이 채널로 전송되며 이 채널을 통해 받은 메시지만 수신 메시지 대기열에 등록됩니다. 2400MHz 기준으로 각 단계는 1MHz 대역입니다. +:param power: (기본값=6) 0부터 7의 정수값(경계값 포함)으로 메시지를 송출할 때의 신호 강도를 표현합니다. +값이 높을 수록 신호는 강해지지만 장치의 전력을 더 소모합니다. 각 숫자는 다음 dBm(데시벨 밀리와트)값 리스트의 위치로 변환됩니다: -30, -20, -16, -12, -8, -4, 0, 4. +:param address: (기본=0x75626974) 32비트로 표현되는 임의의 이름입니다. 하드웨어 레벨에서 수신 패킷을 필터링하는 데 사용되며 설정한 주소와 일치하는 패킷만 유지합니다. 다른 micro:bit 관련 플랫폼이 사용하는 기본값은 여기에서도 사용됩니다. +:param group: 메시지를 필터링할 때 ``address``와 함께 사용되는 8비트 값(0~255)입니다. 개념상 "address(주소)"는 집/사무실 주소, "group(그룹)"은 해당 주소에서 메시지를 보내고자 하는 인물입니다. +:param data_rate: (default=``radio.RATE_1MBIT``) 데이터 처리율의 속도를 지정합니다. ``radio`` 모듈의 다음 상수 중 하나가 될 수 있습니다: ``RATE_250KBIT``, ``RATE_1MBIT`` 또는 ``RATE_2MBIT``. + +If ``config`` is not called then the defaults described above are assumed.""" ... def reset() -> None: - """Reset the settings to their default values. + """설정을 기본값으로 초기화합니다. - Example: ``radio.reset()`` +Example: ``radio.reset()`` - The defaults as as per the ``config`` function above. - """ +The defaults as as per the ``config`` function above.""" ... def send_bytes(message: bytes) -> None: - """Sends a message containing bytes. + """바이트가 포함된 메시지를 전송합니다. - Example: ``radio.send_bytes(b'hello')`` +Example: ``radio.send_bytes(b'hello')`` - :param message: The bytes to send. - """ +:param message: 전송할 바이트입니다.""" ... def receive_bytes() -> Optional[bytes]: - """Receive the next incoming message on the message queue. + """메시지 대기열에 있는 다음 수신 메시지를 받습니다. - Example: ``radio.receive_bytes()`` +Example: ``radio.receive_bytes()`` - :return: The message bytes if any, otherwise ``None``. - """ +:return: The message bytes if any, otherwise ``None``.""" ... def receive_bytes_into(buffer: WriteableBuffer) -> Optional[int]: - """Copy the next incoming message on the message queue into a buffer. + """메시지 대기열에 있는 다음 수신 메시지를 버퍼에 복사합니다. - Example: ``radio.receive_bytes_info(buffer)`` +Example: ``radio.receive_bytes_info(buffer)`` - :param buffer: The target buffer. The message is truncated if larger than the buffer. - :return: ``None`` if there are no pending messages, otherwise it returns the length of the message (which might be more than the length of the buffer). - """ +:param buffer: 목표 버퍼입니다. 메시지가 버퍼보다 크면 메시지가 잘립니다. +:return: ``None`` if there are no pending messages, otherwise it returns the length of the message (which might be more than the length of the buffer).""" ... def send(message: str) -> None: - """Sends a message string. + """메시지 문자열을 전송합니다. - Example: ``radio.send('hello')`` +Example: ``radio.send('hello')`` - This is the equivalent of ``radio.send_bytes(bytes(message, 'utf8'))`` but with ``b'\x01\x00\x01'`` - prepended to the front (to make it compatible with other platforms that target the micro:bit). +This is the equivalent of ``radio.send_bytes(bytes(message, 'utf8'))`` but with ``b'\x01\x00\x01'`` +prepended to the front (to make it compatible with other platforms that target the micro:bit). - :param message: The string to send. - """ +:param message: 전송할 문자열입니다.""" ... def receive() -> Optional[str]: - """Works in exactly the same way as ``receive_bytes`` but returns whatever was sent. + """``receive_bytes``와 정확히 동일한 작업을 하지만 모든 전송 항목을 반환한다는 차이가 있습니다. - Example: ``radio.receive()`` +Example: ``radio.receive()`` - Equivalent to ``str(receive_bytes(), 'utf8')`` but with a check that the the first - three bytes are ``b'\x01\x00\x01'`` (to make it compatible with other platforms that - may target the micro:bit). +Equivalent to ``str(receive_bytes(), 'utf8')`` but with a check that the the first +three bytes are ``b'\x01\x00\x01'`` (to make it compatible with other platforms that +may target the micro:bit). - :return: The message with the prepended bytes stripped and converted to a string. +:return: The message with the prepended bytes stripped and converted to a string. - A ``ValueError`` exception is raised if conversion to string fails. - """ +A ``ValueError`` exception is raised if conversion to string fails.""" ... def receive_full() -> Optional[Tuple[bytes, int, int]]: - """Returns a tuple containing three values representing the next incoming message on the message queue. + """메시지 대기열에 있는 다음 수신 메시지의 정보를 세 종류의 값이 포함된 튜플로 반환합니다. - Example: ``radio.receive_full()`` +Example: ``radio.receive_full()`` - If there are no pending messages then ``None`` is returned. +If there are no pending messages then ``None`` is returned. - The three values in the tuple represent: +The three values in the tuple represent: - - the next incoming message on the message queue as bytes. - - the RSSI (signal strength): a value between 0 (strongest) and -255 (weakest) as measured in dBm. - - a microsecond timestamp: the value returned by ``time.ticks_us()`` when the message was received. +- the next incoming message on the message queue as bytes. +- the RSSI (signal strength): a value between 0 (strongest) and -255 (weakest) as measured in dBm. +- a microsecond timestamp: the value returned by ``time.ticks_us()`` when the message was received. - For example:: +For example:: - details = radio.receive_full() - if details: - msg, rssi, timestamp = details + details = radio.receive_full() + if details: + msg, rssi, timestamp = details - This function is useful for providing information needed for triangulation - and/or trilateration with other micro:bit devices. +This function is useful for providing information needed for triangulation +and/or trilateration with other micro:bit devices. - :return: ``None`` if there is no message, otherwise a tuple of length three with the bytes, strength and timestamp values. - """ - ... +:return: ``None`` if there is no message, otherwise a tuple of length three with the bytes, strength and timestamp values.""" + ... \ No newline at end of file diff --git a/lang/ko/typeshed/stdlib/random.pyi b/lang/ko/typeshed/stdlib/random.pyi index a2c2ef3..ea623df 100644 --- a/lang/ko/typeshed/stdlib/random.pyi +++ b/lang/ko/typeshed/stdlib/random.pyi @@ -1,93 +1,80 @@ -"""Generate random numbers. -""" +"""무작위 숫자를 생성합니다.""" from typing import TypeVar, Sequence, Union, overload def getrandbits(n: int) -> int: - """Generate an integer with ``n`` random bits. + """무작위 비트가 ``n``개 있는 정수를 생성합니다. - Example: ``random.getrandbits(1)`` +Example: ``random.getrandbits(1)`` - :param n: A value between 1-30 (inclusive). - """ +:param n: 1~30 사이의 값입니다(경계값 포함).""" ... def seed(n: int) -> None: - """Initialize the random number generator. + """무작위 숫자 생성기를 초기화합니다. - Example: ``random.seed(0)`` +Example: ``random.seed(0)`` - :param n: The integer seed +:param n: 정수 시드 - This will give you reproducibly deterministic randomness from a given starting - state (``n``). - """ +This will give you reproducibly deterministic randomness from a given starting +state (``n``).""" ... def randint(a: int, b: int) -> int: - """Choose a random integer between ``a`` and ``b`` inclusive. + """``a``부터 ``b``까지 중 무작위 정수를 선택합니다(경계값 포함). - Example: ``random.randint(0, 9)`` +Example: ``random.randint(0, 9)`` - :param a: Start value for the range (inclusive) - :param b: End value for the range (inclusive) +:param a: 범위 시작 값(경계값 포함) +:param b: 범위 종료 값(경계값 포함) - Alias for ``randrange(a, b + 1)``. - """ +Alias for ``randrange(a, b + 1)``.""" ... @overload def randrange(stop: int) -> int: - """Choose a randomly selected integer between zero and up to (but not - including) ``stop``. + """0과``stop``사이의 무작위 정수를 선택합니다(경계값 제외). - Example: ``random.randrange(10)`` +Example: ``random.randrange(10)`` - :param stop: End value for the range (exclusive) - """ +:param stop: 범위 종료 값(경계값 제외)""" ... @overload -def randrange(start: int, stop: int, step: int = 1) -> int: - """ - Choose a randomly selected element from ``range(start, stop, step)``. +def randrange(start: int, stop: int, step: int=1) -> int: + """``range(start, stop, step)``에서 무작위로 정해지는 요소를 선택합니다. - Example: ``random.randrange(0, 10)`` +Example: ``random.randrange(0, 10)`` - :param start: The start of the range (inclusive) - :param stop: The end of the range (exclusive) - :param step: The step. - """ +:param start: 범위 시작(경계값 포함) +:param stop: 범위 끝(경계값 제외) +:param step: 걸음 수입니다.""" ... - -_T = TypeVar("_T") +_T = TypeVar('_T') def choice(seq: Sequence[_T]) -> _T: - """Choose a random element from the non-empty sequence ``seq``. + """공백이 아닌 ``seq`` 시퀀스로부터 무작위 요소를 선택합니다. - Example: ``random.choice([Image.HAPPY, Image.SAD])`` +Example: ``random.choice([Image.HAPPY, Image.SAD])`` - :param seq: A sequence. +:param seq: 시퀀스입니다. - If ``seq`` is empty, raises ``IndexError``. - """ +If ``seq`` is empty, raises ``IndexError``.""" ... def random() -> float: - """Generate a random floating point number in the range [0.0, 1.0). + """[0.0, 1.0) 범위 내의 무작위 부동 소수점 수를 생성합니다. - Example: ``random.random()`` +Example: ``random.random()`` - :return: The random floating point number - """ +:return: The random floating point number""" ... def uniform(a: float, b: float) -> float: - """ - Return a random floating point number between ``a`` and ``b`` inclusive. + """경계값을 포함한 ``a``와 ``b``사이의 무작위 부동 소수점 수를 반환합니다. - Example: ``random.uniform(0, 9)`` +Example: ``random.uniform(0, 9)`` - :param a: Start value for the range (inclusive) - :param b: End value for the range (inclusive) - """ - ... +:param a: 범위 시작 값(경계값 포함) +:param b: 범위 종료 값(경계값 포함)""" + ... \ No newline at end of file diff --git a/lang/ko/typeshed/stdlib/speech.pyi b/lang/ko/typeshed/stdlib/speech.pyi index 349d188..7a58115 100644 --- a/lang/ko/typeshed/stdlib/speech.pyi +++ b/lang/ko/typeshed/stdlib/speech.pyi @@ -1,106 +1,79 @@ -"""Make the micro:bit talk, sing and make other speech like sounds. -""" - +"""micro:bit이 말하고 노래부르고 소리를 재생하게 합니다.""" from typing import Optional from .microbit import MicroBitDigitalPin, pin0 def translate(words: str) -> str: - """Translate English words to phonemes. + """영단어를 음소로 변환합니다. - Example: ``speech.translate('hello world')`` +Example: ``speech.translate('hello world')`` - :param words: A string of English words. - :return: A string containing a best guess at the appropriate phonemes to pronounce. - The output is generated from this `text to phoneme translation table `_. +:param words: 영단어 문자열입니다. +:return: A string containing a best guess at the appropriate phonemes to pronounce. +The output is generated from this `text to phoneme translation table `_. - This function should be used to generate a first approximation of phonemes - that can be further hand-edited to improve accuracy, inflection and - emphasis. +This function should be used to generate a first approximation of phonemes +that can be further hand-edited to improve accuracy, inflection and +emphasis. - See `the online documentation `_ for detailed information. - """ +See `the online documentation `_ for detailed information.""" ... -def pronounce( - phonemes: str, - pitch: int = 64, - speed: int = 72, - mouth: int = 128, - throat: int = 128, - pin: Optional[MicroBitDigitalPin] = pin0, -) -> None: - """Pronounce phonemes. - - Example: ``speech.pronounce(' /HEHLOW WERLD')`` - - :param phonemes: The string of phonemes to pronounce - :param pitch: A number representing the pitch of the voice - :param speed: A number representing the speed of the voice - :param mouth: A number representing the mouth of the voice - :param throat: A number representing the throat of the voice - :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. - If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. - - Override the optional pitch, speed, mouth and throat settings to change the - timbre (quality) of the voice. - - See `the online documentation `_ for detailed information. - """ - ... +def pronounce(phonemes: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: Optional[MicroBitDigitalPin]=pin0) -> None: + """음소를 발음합니다. + +Example: ``speech.pronounce(' /HEHLOW WERLD')`` + +:param phonemes: 발음할 음소의 문자열 +:param pitch: (앞-뒤 기울기) 목소리의 음높이를 표현하는 숫자 +:param speed: 목소리의 속도를 표현하는 숫자 +:param mouth: 목소리의 입 모양을 표현하는 숫자 +:param throat: 목소리의 목 모양을 표현하는 숫자 +:param pin: (핀) ``pin0``의 기본값을 덮어쓰고 출력 핀을 특정하는 인자입니다(선택 사항). +핀에서 사운드를 재생하기 싫다면 ``pin=None``을 사용할 수 있습니다. micro:bit V2 전용입니다. -def say( - words: str, - pitch: int = 64, - speed: int = 72, - mouth: int = 128, - throat: int = 128, - pin: MicroBitDigitalPin = pin0, -) -> None: - """Say English words. - - Example: ``speech.say('hello world')`` - - :param words: The string of words to say. - :param pitch: A number representing the pitch of the voice - :param speed: A number representing the speed of the voice - :param mouth: A number representing the mouth of the voice - :param throat: A number representing the throat of the voice - :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. - If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. - - The result is semi-accurate for English. Override the optional pitch, speed, - mouth and throat settings to change the timbre (quality) of the voice. - - This is a short-hand equivalent of: - ``speech.pronounce(speech.translate(words))`` - - See `the online documentation `_ for detailed information. - """ +Override the optional pitch, speed, mouth and throat settings to change the +timbre (quality) of the voice. + +See `the online documentation `_ for detailed information.""" ... -def sing( - phonemes: str, - pitch: int = 64, - speed: int = 72, - mouth: int = 128, - throat: int = 128, - pin: MicroBitDigitalPin = pin0, -) -> None: - """Sing phonemes. - - Example: ``speech.sing(' /HEHLOW WERLD')`` - - :param phonemes: The string of words to sing. - :param pitch: A number representing the pitch of the voice - :param speed: A number representing the speed of the voice - :param mouth: A number representing the mouth of the voice - :param throat: A number representing the throat of the voice - :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. - If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. - - Override the optional pitch, speed, mouth and throat settings to change - the timbre (quality) of the voice. - - See `the online documentation `_ for detailed information. - """ +def say(words: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: MicroBitDigitalPin=pin0) -> None: + """영어 단어를 말합니다. + +Example: ``speech.say('hello world')`` + +:param words: 말할 단어의 문자열입니다. +:param pitch: (앞-뒤 기울기) 목소리의 음높이를 표현하는 숫자 +:param speed: 목소리의 속도를 표현하는 숫자 +:param mouth: 목소리의 입 모양을 표현하는 숫자 +:param throat: 목소리의 목 모양을 표현하는 숫자 +:param pin: (핀) ``pin0``의 기본값을 덮어쓰고 출력 핀을 특정하는 인자입니다(선택 사항). +핀에서 사운드를 재생하기 싫다면 ``pin=None``을 사용할 수 있습니다. micro:bit V2 전용입니다. + +The result is semi-accurate for English. Override the optional pitch, speed, +mouth and throat settings to change the timbre (quality) of the voice. + +This is a short-hand equivalent of: +``speech.pronounce(speech.translate(words))`` + +See `the online documentation `_ for detailed information.""" ... + +def sing(phonemes: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: MicroBitDigitalPin=pin0) -> None: + """음소를 노래합니다. + +Example: ``speech.sing(' /HEHLOW WERLD')`` + +:param phonemes: 노래할 단어 문자열입니다. +:param pitch: (앞-뒤 기울기) 목소리의 음높이를 표현하는 숫자 +:param speed: 목소리의 속도를 표현하는 숫자 +:param mouth: 목소리의 입 모양을 표현하는 숫자 +:param throat: 목소리의 목 모양을 표현하는 숫자 +:param pin: (핀) ``pin0``의 기본값을 덮어쓰고 출력 핀을 특정하는 인자입니다(선택 사항). +핀에서 사운드를 재생하기 싫다면 ``pin=None``을 사용할 수 있습니다. micro:bit V2 전용입니다. + +Override the optional pitch, speed, mouth and throat settings to change +the timbre (quality) of the voice. + +See `the online documentation `_ for detailed information.""" + ... \ No newline at end of file diff --git a/lang/ko/typeshed/stdlib/struct.pyi b/lang/ko/typeshed/stdlib/struct.pyi index 53b3e0b..03c8b8c 100644 --- a/lang/ko/typeshed/stdlib/struct.pyi +++ b/lang/ko/typeshed/stdlib/struct.pyi @@ -1,65 +1,56 @@ -"""Pack and unpack primitive data types. -""" - +"""원시 데이터 유형을 패킹하고 언패킹합니다.""" from _typeshed import ReadableBuffer, WriteableBuffer from typing import Any, Tuple, Union def calcsize(fmt: str) -> int: - """Get the number of bytes needed to store the given ``fmt``. + """주어진 ``fmt``를 저장하는 데 필요한 바이트의 수를 불러옵니다. - Example: ``struct.calcsize('hf')`` +Example: ``struct.calcsize('hf')`` - :param fmt: A format string. - :return The number of bytes needed to store such a value. - """ +:param fmt: 형식 문자열입니다. +:return The number of bytes needed to store such a value.""" ... def pack(fmt: str, v1: Any, *vn: Any) -> bytes: - """Pack values according to a format string. + """형식 문자열에 따라 값을 패킹합니다. - Example: ``struct.pack('hf', 1, 3.1415)`` +Example: ``struct.pack('hf', 1, 3.1415)`` - :param fmt: The format string. - :param v1: The first value. - :param *vn: The remaining values. - :return A bytes object encoding the values. - """ +:param fmt: 형식 문자열입니다. +:param v1: 첫 값입니다. +:param *vn: 남은 값입니다. +:return A bytes object encoding the values.""" ... -def pack_into( - fmt: str, buffer: WriteableBuffer, offset: int, v1: Any, *vn: Any -) -> None: - """Pack values according to a format string. +def pack_into(fmt: str, buffer: WriteableBuffer, offset: int, v1: Any, *vn: Any) -> None: + """형식 문자열에 따라 값을 패킹합니다. - Example: ``struct.pack_info('hf', buffer, 1, 3.1415)`` +Example: ``struct.pack_info('hf', buffer, 1, 3.1415)`` - :param fmt: The format string. - :param buffer: The target buffer to write into. - :param offset: The offset into the buffer. May be negative to count from the end of the buffer. - :param v1: The first value. - :param *vn: The remaining values. - """ +:param fmt: 형식 문자열입니다. +:param buffer: 작성할 목표 버퍼입니다. +:param offset: 버퍼에 적용할 오프셋입니다. 음수를 입력하면 버퍼 끝부터 셀 수 있습니다. +:param v1: 첫 값입니다. +:param *vn: 남은 값입니다.""" ... def unpack(fmt: str, data: ReadableBuffer) -> Tuple[Any, ...]: - """Unpack data according to a format string. + """형식 문자열에 따라 데이터를 언패킹합니다. - Example: ``v1, v2 = struct.unpack('hf', buffer)`` +Example: ``v1, v2 = struct.unpack('hf', buffer)`` - :param fmt: The format string. - :param data: The data. - :return: A tuple of the unpacked values. - """ +:param fmt: 형식 문자열입니다. +:param data: 데이터입니다. +:return: A tuple of the unpacked values.""" ... -def unpack_from(fmt: str, buffer: ReadableBuffer, offset: int = 0) -> Tuple: - """Unpack data from a buffer according to a format string. +def unpack_from(fmt: str, buffer: ReadableBuffer, offset: int=0) -> Tuple: + """형식 문자열에 따라 버퍼로부터 데이터를 언패킹합니다. - Example: ``v1, v2 = struct.unpack_from('hf', buffer)`` +Example: ``v1, v2 = struct.unpack_from('hf', buffer)`` - :param fmt: The format string. - :param buffer: The source buffer to read from. - :param offset: The offset into the buffer. May be negative to count from the end of the buffer. - :return: A tuple of the unpacked values. - """ - ... +:param fmt: 형식 문자열입니다. +:param buffer: 읽을 소스 버퍼입니다. +:param offset: (오프셋) 버퍼에 적용할 오프셋입니다. 음수를 입력하면 버퍼 끝부터 셀 수 있습니다. +:return: A tuple of the unpacked values.""" + ... \ No newline at end of file diff --git a/lang/ko/typeshed/stdlib/sys.pyi b/lang/ko/typeshed/stdlib/sys.pyi index 320bac9..73473c5 100644 --- a/lang/ko/typeshed/stdlib/sys.pyi +++ b/lang/ko/typeshed/stdlib/sys.pyi @@ -1,43 +1,36 @@ -"""System specific functions""" - +"""시스템 특정 함수""" from typing import Any, Dict, List, NoReturn, TextIO, Tuple -def exit(retval: object = ...) -> NoReturn: - """Terminate current program with a given exit code. +def exit(retval: object=...) -> NoReturn: + """주어진 종료 코드로 현재 프로그램을 종료합니다. - Example: ``sys.exit(1)`` +Example: ``sys.exit(1)`` - This function raises a ``SystemExit`` exception. If an argument is given, its - value given as an argument to ``SystemExit``. +This function raises a ``SystemExit`` exception. If an argument is given, its +value given as an argument to ``SystemExit``. - :param retval: The exit code or message. - """ +:param retval: 종료 코드 또는 메시지입니다.""" ... def print_exception(exc: Exception) -> None: - """ - Print an exception with a traceback. - - Example: ``sys.print_exception(e)`` + """트레이스백으로 예외를 프린트합니다. - :param exc: The exception to print +Example: ``sys.print_exception(e)`` - This is simplified version of a function which appears in the - ``traceback`` module in CPython. - """ +:param exc: 프린트할 예외 +This is simplified version of a function which appears in the +``traceback`` module in CPython.""" argv: List[str] -"""A mutable list of arguments the current program was started with.""" - +"""현재 프로그램과 같이 시작된 인자의 가변 리스트입니다.""" byteorder: str -"""The byte order of the system (``"little"`` or ``"big"``).""" +"""시스템의 바이트 순서를 (``"little"`` 또는 ``"big"``)으로 정렬합니다.""" class _implementation: name: str version: Tuple[int, int, int] - implementation: _implementation -"""Object with information about the current Python implementation. +"""현재 Python 구현에 관한 정보가 담긴 개체 For MicroPython, it has following attributes: @@ -51,13 +44,9 @@ minimal ports). CPython mandates more attributes for this object, but the actual useful bare minimum is implemented in MicroPython. """ - maxsize: int """ -Maximum value which a native integer type can hold on the current platform, -or maximum value representable by MicroPython integer type, if it's smaller -than platform max value (that is the case for MicroPython ports without -long int support). +현재 플랫폼에서 자연 정수 유형이 지원할 수 있는 최대 값, 또는 값이 플랫폼의 최대 값보다 작다면 MicroPython 정수 유형으로 표현할 수 있는 최대 값입니다(long int를 지원하지 않는 MicroPython 포트의 경우). This attribute is useful for detecting "bitness" of a platform (32-bit vs 64-bit, etc.). It's recommended to not compare this attribute to some @@ -77,17 +66,14 @@ value directly, but instead count number of bits in it:: # (e.g. 31) due to peculiarities described above, so use "> 16", # "> 32", "> 64" style of comparisons. """ - modules: Dict[str, Any] -"""Dictionary of loaded modules. +"""로드된 모듈의 딕셔너리입니다. On some ports, it may not include builtin modules.""" - path: List[str] -"""A mutable list of directories to search for imported modules.""" - +"""불러온 모듈을 검색하기 위한 딕셔너리 가변 리스트입니다.""" platform: str -"""The platform that MicroPython is running on. +"""MicroPython이 실행되고 있는 플랫폼입니다. For OS/RTOS ports, this is usually an identifier of the OS, e.g. ``"linux"``. For baremetal ports it is an identifier of a board, e.g. ``"pyboard"`` for @@ -97,13 +83,11 @@ distinguish one board from another. If you need to check whether your program runs on MicroPython (vs other Python implementation), use ``sys.implementation`` instead. """ - version: str -"""Python language version that this implementation conforms to, as a string.""" - +"""이 구현이 준수하는 Python 언어 버전을 문자열로 제공합니다.""" version_info: Tuple[int, int, int] -"""Python language version that this implementation conforms to, as a tuple of ints. +"""이 구현이 준수하는 Python 언어 버전을 정수 튜플로 제공합니다. Only the first three version numbers (major, minor, micro) are supported and they can be referenced only by index, not by name. -""" +""" \ No newline at end of file diff --git a/lang/ko/typeshed/stdlib/time.pyi b/lang/ko/typeshed/stdlib/time.pyi index 598c483..fe2abeb 100644 --- a/lang/ko/typeshed/stdlib/time.pyi +++ b/lang/ko/typeshed/stdlib/time.pyi @@ -1,132 +1,111 @@ -"""Measure time and add delays to programs. -""" - +"""시간을 측정하고 프로그램에 지연을 부여합니다.""" from typing import Union def sleep(seconds: Union[int, float]) -> None: - """ - Delay a number of seconds. + """초 단위로 지연을 부여합니다. - Example: ``time.sleep(1)`` +Example: ``time.sleep(1)`` - :param seconds: The number of seconds to sleep for. - Use a floating-point number to sleep for a fractional number of seconds. - """ +:param seconds: 절전 상태를 설정할 초 단위입니다. +초 단위 미만으로 절전 상태를 설정하려면 부동 소수점 수를 사용하세요.""" ... def sleep_ms(ms: int) -> None: - """ - Delay for given number of milliseconds. + """밀리초 단위로 지연을 부여합니다. - Example: ``time.sleep_ms(1_000_000)`` +Example: ``time.sleep_ms(1_000_000)`` - :param ms: The number of milliseconds delay (>= 0). - """ +:param ms: 밀리초 단위의 지연 시간입니다(>= 0).""" ... def sleep_us(us: int) -> None: - """ - Delay for given number of microseconds. + """마이크로초 단위로 지연을 부여합니다. - Example: ``time.sleep_us(1000)`` +Example: ``time.sleep_us(1000)`` - :param us: The number of microseconds delay (>= 0). - """ +:param us: 마이크로초 단위의 지연 시간입니다(>= 0).""" ... def ticks_ms() -> int: - """ - Get an increasing, millisecond counter with an arbitrary reference point, - that wraps around after some value. + """임의의 레퍼런스 포인트가 있는 점진적으로 증가하는 밀리초 카운터로, 일부 값을 따라 래핑합니다. - Example: ``time.ticks_ms()`` +Example: ``time.ticks_ms()`` - :return: The counter value in milliseconds. - """ +:return: The counter value in milliseconds.""" ... def ticks_us() -> int: - """ - Get an increasing, microsecond counter with an arbitrary reference point, - that wraps around after some value. + """임의의 레퍼런스 포인트가 있는 점진적으로 증가하는 마이크로초 카운터로, 일부 값을 따라 래핑합니다. - Example: ``time.ticks_us()`` +Example: ``time.ticks_us()`` - :return: The counter value in microseconds. - """ +:return: The counter value in microseconds.""" ... def ticks_add(ticks: int, delta: int) -> int: - """ - Offset ticks value by a given number, which can be either positive or - negative. + """주어진 숫자에 따라 틱 값을 오프셋으로 사용합니다. 양수나 음수일 수 있습니다. - Example: ``time.ticks_add(time.ticks_ms(), 200)`` +Example: ``time.ticks_add(time.ticks_ms(), 200)`` - Given a ticks value, this function allows to calculate ticks - value delta ticks before or after it, following modular-arithmetic - definition of tick values. +Given a ticks value, this function allows to calculate ticks +value delta ticks before or after it, following modular-arithmetic +definition of tick values. - :param ticks: A ticks value - :param delta: An integer offset +:param ticks: 틱 값 +:param delta: 정수 오프셋 - Example:: +Example:: - # Find out what ticks value there was 100ms ago - print(ticks_add(time.ticks_ms(), -100)) + # Find out what ticks value there was 100ms ago + print(ticks_add(time.ticks_ms(), -100)) - # Calculate deadline for operation and test for it - deadline = ticks_add(time.ticks_ms(), 200) - while ticks_diff(deadline, time.ticks_ms()) > 0: - do_a_little_of_something() + # Calculate deadline for operation and test for it + deadline = ticks_add(time.ticks_ms(), 200) + while ticks_diff(deadline, time.ticks_ms()) > 0: + do_a_little_of_something() - # Find out TICKS_MAX used by this port - print(ticks_add(0, -1)) - """ + # Find out TICKS_MAX used by this port + print(ticks_add(0, -1))""" ... def ticks_diff(ticks1: int, ticks2: int) -> int: - """ - Measure ticks difference between values returned from - ``time.ticks_ms()`` or ``ticks_us()``, as a signed value - which may wrap around. - - Example: ``time.ticks_diff(scheduled_time, now)`` - - :param ticks1: The value to subtract from - :param ticks2: The value to subtract - - The argument order is the same as for subtraction operator, - ``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. - - ``ticks_diff()`` is designed to accommodate various usage - patterns, among them: - - Polling with timeout. In this case, the order of events is known, and you - will deal only with positive results of :func:`time.ticks_diff()`:: - - # Wait for GPIO pin to be asserted, but at most 500us - start = time.ticks_us() - while pin.value() == 0: - if time.ticks_diff(time.ticks_us(), start) > 500: - raise TimeoutError - - - Scheduling events. In this case, :func:`time.ticks_diff()` result may be - negative if an event is overdue:: - - # This code snippet is not optimized - now = time.ticks_ms() - scheduled_time = task.scheduled_time() - if ticks_diff(scheduled_time, now) > 0: - print("Too early, let's nap") - sleep_ms(ticks_diff(scheduled_time, now)) - task.run() - elif ticks_diff(scheduled_time, now) == 0: - print("Right at time!") - task.run() - elif ticks_diff(scheduled_time, now) < 0: - print("Oops, running late, tell task to run faster!") - task.run(run_faster=True) - """ - ... + """``time.ticks_ms()`` 또는 ``ticks_us()``에서 반환된 값 사이의 틱 차이를 측정합니다. 서명된 값은 래핑될 수 있습니다. + +Example: ``time.ticks_diff(scheduled_time, now)`` + +:param ticks1: 뺄 값 +:param ticks2: 뺄 값 + +The argument order is the same as for subtraction operator, +``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. + +``ticks_diff()`` is designed to accommodate various usage +patterns, among them: + +Polling with timeout. In this case, the order of events is known, and you +will deal only with positive results of :func:`time.ticks_diff()`:: + + # Wait for GPIO pin to be asserted, but at most 500us + start = time.ticks_us() + while pin.value() == 0: + if time.ticks_diff(time.ticks_us(), start) > 500: + raise TimeoutError + + +Scheduling events. In this case, :func:`time.ticks_diff()` result may be +negative if an event is overdue:: + + # This code snippet is not optimized + now = time.ticks_ms() + scheduled_time = task.scheduled_time() + if ticks_diff(scheduled_time, now) > 0: + print("Too early, let's nap") + sleep_ms(ticks_diff(scheduled_time, now)) + task.run() + elif ticks_diff(scheduled_time, now) == 0: + print("Right at time!") + task.run() + elif ticks_diff(scheduled_time, now) < 0: + print("Oops, running late, tell task to run faster!") + task.run(run_faster=True)""" + ... \ No newline at end of file diff --git a/lang/lol/typeshed/stdlib/gc.pyi b/lang/lol/typeshed/stdlib/gc.pyi index 1370abf..d91bd02 100644 --- a/lang/lol/typeshed/stdlib/gc.pyi +++ b/lang/lol/typeshed/stdlib/gc.pyi @@ -1,73 +1,68 @@ -"""Control the garbage collector""" - +"""crwdns328732:0crwdne328732:0 (crwdns328730:0crwdne328730:0)""" from typing import overload def enable() -> None: - """Enable automatic garbage collection.""" + """crwdns328736:0crwdne328736:0 (crwdns328734:0crwdne328734:0)""" ... def disable() -> None: - """Disable automatic garbage collection. + """crwdns328740:0crwdne328740:0 (crwdns328738:0crwdne328738:0) - Heap memory can still be allocated, - and garbage collection can still be initiated manually using ``gc.collect``.""" +Heap memory can still be allocated, +and garbage collection can still be initiated manually using ``gc.collect``.""" def collect() -> None: - """Run a garbage collection.""" + """crwdns328744:0crwdne328744:0 (crwdns328742:0crwdne328742:0)""" ... def mem_alloc() -> int: - """Get the number of bytes of heap RAM that are allocated. + """crwdns328748:0crwdne328748:0 (crwdns328746:0crwdne328746:0) - :return: The number of bytes allocated. +:return: The number of bytes allocated. - This function is MicroPython extension. - """ +This function is MicroPython extension.""" ... def mem_free() -> int: - """Get the number of bytes of available heap RAM, or -1 if this amount is not known. + """crwdns328752:0crwdne328752:0 (crwdns328750:0crwdne328750:0) - :return: The number of bytes free. +:return: The number of bytes free. - This function is MicroPython extension. - """ +This function is MicroPython extension.""" ... @overload def threshold() -> int: - """Query the additional GC allocation threshold. + """crwdns328756:0crwdne328756:0 (crwdns328754:0crwdne328754:0) - :return: The GC allocation threshold. +:return: The GC allocation threshold. - This function is a MicroPython extension. CPython has a similar - function - ``set_threshold()``, but due to different GC - implementations, its signature and semantics are different. - """ +This function is a MicroPython extension. CPython has a similar +function - ``set_threshold()``, but due to different GC +implementations, its signature and semantics are different.""" ... @overload def threshold(amount: int) -> None: - """Set the additional GC allocation threshold. - - Normally, a collection is triggered only when a new allocation - cannot be satisfied, i.e. on an out-of-memory (OOM) condition. - If this function is called, in addition to OOM, a collection - will be triggered each time after ``amount`` bytes have been - allocated (in total, since the previous time such an amount of bytes - have been allocated). ``amount`` is usually specified as less than the - full heap size, with the intention to trigger a collection earlier than when the - heap becomes exhausted, and in the hope that an early collection will prevent - excessive memory fragmentation. This is a heuristic measure, the effect - of which will vary from application to application, as well as - the optimal value of the ``amount`` parameter. - - A value of -1 means a disabled allocation threshold. - - This function is a MicroPython extension. CPython has a similar - function - ``set_threshold()``, but due to different GC - implementations, its signature and semantics are different. - - :param amount: The number of bytes after which a garbage collection should be triggered. - """ - ... + """crwdns328760:0crwdne328760:0 (crwdns328758:0crwdne328758:0) + +Normally, a collection is triggered only when a new allocation +cannot be satisfied, i.e. on an out-of-memory (OOM) condition. +If this function is called, in addition to OOM, a collection +will be triggered each time after ``amount`` bytes have been +allocated (in total, since the previous time such an amount of bytes +have been allocated). ``amount`` is usually specified as less than the +full heap size, with the intention to trigger a collection earlier than when the +heap becomes exhausted, and in the hope that an early collection will prevent +excessive memory fragmentation. This is a heuristic measure, the effect +of which will vary from application to application, as well as +the optimal value of the ``amount`` parameter. + +A value of -1 means a disabled allocation threshold. + +This function is a MicroPython extension. CPython has a similar +function - ``set_threshold()``, but due to different GC +implementations, its signature and semantics are different. + +:param amount: (crwdns328762:0crwdne328762:0) crwdns328764:0crwdne328764:0""" + ... \ No newline at end of file diff --git a/lang/lol/typeshed/stdlib/log.pyi b/lang/lol/typeshed/stdlib/log.pyi index c9870fa..725cc6e 100644 --- a/lang/lol/typeshed/stdlib/log.pyi +++ b/lang/lol/typeshed/stdlib/log.pyi @@ -1,104 +1,89 @@ -"""Log data to your micro:bit V2.""" - +"""crwdns328768:0crwdne328768:0 (crwdns328766:0crwdne328766:0)""" from typing import Literal, Mapping, Optional, Union, overload - MILLISECONDS = 1 -"""Milliseconds timestamp format.""" - +"""crwdns328772:0crwdne328772:0 (crwdns328770:0crwdne328770:0)""" SECONDS = 10 -"""Seconds timestamp format.""" - +"""crwdns328776:0crwdne328776:0 (crwdns328774:0crwdne328774:0)""" MINUTES = 600 -"""Minutes timestamp format.""" - +"""crwdns328780:0crwdne328780:0 (crwdns328778:0crwdne328778:0)""" HOURS = 36000 -"""Hours timestamp format.""" - +"""crwdns328784:0crwdne328784:0 (crwdns328782:0crwdne328782:0)""" DAYS = 864000 -"""Days timestamp format.""" +"""crwdns328788:0crwdne328788:0 (crwdns328786:0crwdne328786:0)""" -def set_labels( - *labels: str, timestamp: Optional[Literal[1, 10, 36000, 864000]] = SECONDS -) -> None: - """Set up the log file header. +def set_labels(*labels: str, timestamp: Optional[Literal[1, 10, 36000, 864000]]=SECONDS) -> None: + """crwdns328792:0crwdne328792:0 (crwdns328790:0crwdne328790:0) - Example: ``log.set_labels('X', 'Y', 'Z', timestamp=log.MINUTES)`` +Example: ``log.set_labels('X', 'Y', 'Z', timestamp=log.MINUTES)`` - Ideally this function should be called a single time, before any data is - logged, to configure the data table header once. +Ideally this function should be called a single time, before any data is +logged, to configure the data table header once. - If a log file already exists when the program starts, or if this function - is called multiple times, it will check the labels already defined in the - log file. If this function call contains any new labels not already - present, it will generate a new header row with the additional columns. +If a log file already exists when the program starts, or if this function +is called multiple times, it will check the labels already defined in the +log file. If this function call contains any new labels not already +present, it will generate a new header row with the additional columns. - By default the first column contains a timestamp for each row. The time - unit can be selected via the timestamp argument. +By default the first column contains a timestamp for each row. The time +unit can be selected via the timestamp argument. - :param *labels: Any number of positional arguments, each corresponding to an entry in the log header. - :param timestamp: Select the timestamp unit that will be automatically added as the first column in every row. Timestamp values can be one of ``log.MILLISECONDS``, ``log.SECONDS``, ``log.MINUTES``, ``log.HOURS``, ``log.DAYS`` or ``None`` to disable the timestamp. The default value is ``log.SECONDS``. - """ +:param *labels: (crwdns335772:0crwdne335772:0) crwdns335774:0crwdne335774:0 +:param timestamp: (crwdns328798:0crwdne328798:0) crwdns335776:0``log.MILLISECONDS``crwdnd335776:0``log.SECONDS``crwdnd335776:0``log.MINUTES``crwdnd335776:0``log.HOURS``crwdnd335776:0``log.DAYS``crwdnd335776:0``None``crwdnd335776:0``log.SECONDS``crwdne335776:0""" ... @overload -def add( - data_dictionary: Optional[Mapping[str, Union[str, int, float]]], -) -> None: - """Add a data row to the log by passing a dictionary of headers and values. +def add(data_dictionary: Optional[Mapping[str, Union[str, int, float]]]) -> None: + """crwdns328804:0crwdne328804:0 (crwdns328802:0crwdne328802:0) - Example: ``log.add({ 'temp': temperature() })`` +Example: ``log.add({ 'temp': temperature() })`` - Each call to this function adds a row to the log. +Each call to this function adds a row to the log. - New labels not previously specified via the set_labels function, or by a - previous call to this function, will trigger a new header entry to be added - to the log with the extra labels. +New labels not previously specified via the set_labels function, or by a +previous call to this function, will trigger a new header entry to be added +to the log with the extra labels. - Labels previously specified and not present in a call to this function will - be skipped with an empty value in the log row. +Labels previously specified and not present in a call to this function will +be skipped with an empty value in the log row. - :param data_dictionary: The data to log as a dictionary with a key for each header. - """ +:param data_dictionary: (crwdns335778:0crwdne335778:0) crwdns335780:0crwdne335780:0""" ... @overload def add(**kwargs: Union[str, int, float]) -> None: - """Add a data row to the log using keyword arguments. + """crwdns328812:0crwdne328812:0 (crwdns328810:0crwdne328810:0) - Example: ``log.add(temp=temperature())`` +Example: ``log.add(temp=temperature())`` - Each call to this function adds a row to the log. +Each call to this function adds a row to the log. - New labels not previously specified via the set_labels function, or by a - previous call to this function, will trigger a new header entry to be added - to the log with the extra labels. +New labels not previously specified via the set_labels function, or by a +previous call to this function, will trigger a new header entry to be added +to the log with the extra labels. - Labels previously specified and not present in a call to this function will - be skipped with an empty value in the log row. - """ +Labels previously specified and not present in a call to this function will +be skipped with an empty value in the log row.""" ... def delete(full=False): - """Deletes the contents of the log, including headers. + """crwdns328816:0crwdne328816:0 (crwdns328814:0crwdne328814:0) - Example: ``log.delete()`` +Example: ``log.delete()`` - To add the log headers again the ``set_labels`` function should to be called after this function. +To add the log headers again the ``set_labels`` function should to be called after this function. - There are two erase modes; “full” completely removes the data from the physical storage, - and “fast” invalidates the data without removing it. +There are two erase modes; “full” completely removes the data from the physical storage, +and “fast” invalidates the data without removing it. - :param full: ``True`` selects a “full” erase and ``False`` selects the “fast” erase method. - """ +:param full: (crwdns328818:0crwdne328818:0) crwdns335782:0``True``crwdnd335782:0``False``crwdne335782:0""" ... def set_mirroring(serial: bool): - """Configure mirroring of the data logging activity to the serial output. + """crwdns335784:0crwdne335784:0 (crwdns328822:0crwdne328822:0) - Example: ``log.set_mirroring(True)`` +Example: ``log.set_mirroring(True)`` - Serial mirroring is disabled by default. When enabled, it will print to serial each row logged into the log file. +Serial mirroring is disabled by default. When enabled, it will print to serial each row logged into the log file. - :param serial: ``True`` enables mirroring data to the serial output. - """ - ... +:param serial: (crwdns328826:0crwdne328826:0) crwdns335786:0``True``crwdne335786:0""" + ... \ No newline at end of file diff --git a/lang/lol/typeshed/stdlib/machine.pyi b/lang/lol/typeshed/stdlib/machine.pyi index 2e82f5b..6dd178c 100644 --- a/lang/lol/typeshed/stdlib/machine.pyi +++ b/lang/lol/typeshed/stdlib/machine.pyi @@ -1,97 +1,84 @@ -"""Low-level utilities. -""" +"""crwdns328832:0crwdne328832:0 (crwdns328830:0crwdne328830:0)""" from typing import Any from .microbit import MicroBitDigitalPin def unique_id() -> bytes: - """Get a byte string with a unique identifier of a board. + """crwdns328836:0crwdne328836:0 (crwdns328834:0crwdne328834:0) - Example: ``machine.unique_id()`` +Example: ``machine.unique_id()`` - :return: An identifier that varies from one board instance to another. - """ +:return: An identifier that varies from one board instance to another.""" ... def reset() -> None: - """Reset the device in a manner similar to pushing the external RESET button. + """crwdns328840:0crwdne328840:0 (crwdns328838:0crwdne328838:0) - Example: ``machine.reset()`` - """ +Example: ``machine.reset()``""" ... def freq() -> int: - """Get the CPU frequency in hertz. + """crwdns328844:0crwdne328844:0 (crwdns328842:0crwdne328842:0) - Example: ``machine.freq()`` +Example: ``machine.freq()`` - :return: The CPU frequency. - """ +:return: The CPU frequency.""" ... def disable_irq() -> Any: - """Disable interrupt requests. + """crwdns328848:0crwdne328848:0 (crwdns328846:0crwdne328846:0) - Example: ``interrupt_state = machine.disable_irq()`` +Example: ``interrupt_state = machine.disable_irq()`` - :return: the previous IRQ state which should be considered an opaque value +:return: the previous IRQ state which should be considered an opaque value - The return value should be passed to the ``enable_irq`` function to restore - interrupts to their original state. - """ +The return value should be passed to the ``enable_irq`` function to restore +interrupts to their original state.""" ... def enable_irq(state: Any) -> None: - """Re-enable interrupt requests. + """crwdns328852:0crwdne328852:0 (crwdns328850:0crwdne328850:0) - Example: ``machine.enable_irq(interrupt_state)`` +Example: ``machine.enable_irq(interrupt_state)`` - :param state: The value that was returned from the most recent call to the ``disable_irq`` function. - """ +:param state: (crwdns328854:0crwdne328854:0) crwdns328856:0``disable_irq``crwdne328856:0""" ... -def time_pulse_us( - pin: MicroBitDigitalPin, pulse_level: int, timeout_us: int = 1000000 -) -> int: - """Time a pulse on a pin. +def time_pulse_us(pin: MicroBitDigitalPin, pulse_level: int, timeout_us: int=1000000) -> int: + """crwdns328860:0crwdne328860:0 (crwdns328858:0crwdne328858:0) - Example: ``time_pulse_us(pin0, 1)`` +Example: ``time_pulse_us(pin0, 1)`` - If the current input value of the pin is different to ``pulse_level``, the - function first waits until the pin input becomes equal to - ``pulse_level``, then times the duration that the pin is equal to - ``pulse_level``. If the pin is already equal to ``pulse_level`` then timing - starts straight away. +If the current input value of the pin is different to ``pulse_level``, the +function first waits until the pin input becomes equal to +``pulse_level``, then times the duration that the pin is equal to +``pulse_level``. If the pin is already equal to ``pulse_level`` then timing +starts straight away. - :param pin: The pin to use - :param pulse_level: 0 to time a low pulse or 1 to time a high pulse - :param timeout_us: A microsecond timeout - :return: The duration of the pulse in microseconds, or -1 for a timeout waiting for the level to match ``pulse_level``, or -2 on timeout waiting for the pulse to end - """ +:param pin: (crwdns328862:0crwdne328862:0) crwdns328864:0crwdne328864:0 +:param pulse_level: (crwdns328866:0crwdne328866:0) crwdns328868:0crwdne328868:0 +:param timeout_us: (crwdns328870:0crwdne328870:0) crwdns328872:0crwdne328872:0 +:return: The duration of the pulse in microseconds, or -1 for a timeout waiting for the level to match ``pulse_level``, or -2 on timeout waiting for the pulse to end""" ... class mem: - """The class for the ``mem8``, ``mem16`` and ``mem32`` memory views.""" + """crwdns328876:0``mem8``crwdnd328876:0``mem16``crwdnd328876:0``mem32``crwdne328876:0 (crwdns328874:0crwdne328874:0)""" def __getitem__(self, address: int) -> int: - """Access a value from memory. + """crwdns328880:0crwdne328880:0 (crwdns328878:0crwdne328878:0) - :param address: The memory address. - :return: The value at that address as an integer. - """ +:param address: (crwdns328882:0crwdne328882:0) crwdns328884:0crwdne328884:0 +:return: The value at that address as an integer.""" ... + def __setitem__(self, address: int, value: int) -> None: - """Set a value at the given address. + """crwdns328888:0crwdne328888:0 (crwdns328886:0crwdne328886:0) - :param address: The memory address. - :param value: The integer value to set. - """ +:param address: (crwdns328890:0crwdne328890:0) crwdns328892:0crwdne328892:0 +:param value: (crwdns328894:0crwdne328894:0) crwdns328896:0crwdne328896:0""" ... - mem8: mem -"""8-bit (byte) view of memory.""" - +"""crwdns328900:0crwdne328900:0 (crwdns328898:0crwdne328898:0)""" mem16: mem -"""16-bit view of memory.""" - +"""crwdns328904:0crwdne328904:0 (crwdns328902:0crwdne328902:0)""" mem32: mem -"""32-bit view of memory.""" +"""crwdns328908:0crwdne328908:0 (crwdns328906:0crwdne328906:0)""" \ No newline at end of file diff --git a/lang/lol/typeshed/stdlib/math.pyi b/lang/lol/typeshed/stdlib/math.pyi index f82d4de..9373c19 100644 --- a/lang/lol/typeshed/stdlib/math.pyi +++ b/lang/lol/typeshed/stdlib/math.pyi @@ -1,273 +1,246 @@ -"""Mathematical functions. -""" - +"""crwdns328912:0crwdne328912:0 (crwdns328910:0crwdne328910:0)""" from typing import Tuple def acos(x: float) -> float: - """Calculate the inverse cosine. + """crwdns328916:0crwdne328916:0 (crwdns328914:0crwdne328914:0) - Example: ``math.acos(1)`` +Example: ``math.acos(1)`` - :param x: A number - :return: The inverse cosine of ``x`` - """ +:param x: (crwdns328918:0crwdne328918:0) crwdns328920:0crwdne328920:0 +:return: The inverse cosine of ``x``""" ... def asin(x: float) -> float: - """Calculate the inverse sine. + """crwdns328924:0crwdne328924:0 (crwdns328922:0crwdne328922:0) - Example: ``math.asin(0)`` +Example: ``math.asin(0)`` - :param x: A number - :return: The inverse sine of ``x`` - """ +:param x: (crwdns328926:0crwdne328926:0) crwdns328928:0crwdne328928:0 +:return: The inverse sine of ``x``""" ... def atan(x: float) -> float: - """Calculate the inverse tangent. + """crwdns328932:0crwdne328932:0 (crwdns328930:0crwdne328930:0) - Example: ``math.atan(0)`` +Example: ``math.atan(0)`` - :param x: A number - :return: The inverse tangent of ``x`` - """ +:param x: (crwdns328934:0crwdne328934:0) crwdns328936:0crwdne328936:0 +:return: The inverse tangent of ``x``""" ... def atan2(y: float, x: float) -> float: - """Calculate the principal value of the inverse tangent of ``y/x``. + """crwdns328940:0``y/x``crwdne328940:0 (crwdns328938:0crwdne328938:0) - Example: ``math.atan2(0, -1)`` +Example: ``math.atan2(0, -1)`` - :param y: A number - :param x: A number - :return: The principal value of the inverse tangent of ``y/x`` - """ +:param y: (crwdns328942:0crwdne328942:0) crwdns328944:0crwdne328944:0 +:param x: (crwdns328942:0crwdne328942:0) crwdns328944:0crwdne328944:0 +:return: The principal value of the inverse tangent of ``y/x``""" ... def ceil(x: float) -> float: - """Round a number towards positive infinity. + """crwdns328952:0crwdne328952:0 (crwdns328950:0crwdne328950:0) - Example: ``math.ceil(0.1)`` +Example: ``math.ceil(0.1)`` - :param x: A number - :return: ``x`` rounded towards positive infinity. - """ +:param x: (crwdns328954:0crwdne328954:0) crwdns328956:0crwdne328956:0 +:return: ``x`` rounded towards positive infinity.""" ... def copysign(x: float, y: float) -> float: - """Calculate ``x`` with the sign of ``y``. + """crwdns328960:0``x``crwdnd328960:0``y``crwdne328960:0 (crwdns328958:0crwdne328958:0) - Example: ``math.copysign(1, -1)`` +Example: ``math.copysign(1, -1)`` - :param x: A number - :param y: The source of the sign for the return value - :return: ``x`` with the sign of ``y`` - """ +:param x: (crwdns328962:0crwdne328962:0) crwdns328964:0crwdne328964:0 +:param y: (crwdns328966:0crwdne328966:0) crwdns328968:0crwdne328968:0 +:return: ``x`` with the sign of ``y``""" ... def cos(x: float) -> float: - """Calculate the cosine of ``x``. + """crwdns328972:0``x``crwdne328972:0 (crwdns328970:0crwdne328970:0) - Example: ``math.cos(0)`` +Example: ``math.cos(0)`` - :param x: A number - :return: The cosine of ``x`` - """ +:param x: (crwdns328974:0crwdne328974:0) crwdns328976:0crwdne328976:0 +:return: The cosine of ``x``""" ... def degrees(x: float) -> float: - """Convert radians to degrees. + """crwdns328980:0crwdne328980:0 (crwdns328978:0crwdne328978:0) - Example: ``math.degrees(2 * math.pi)`` +Example: ``math.degrees(2 * math.pi)`` - :param x: A value in radians - :return: The value converted to degrees""" +:param x: (crwdns328982:0crwdne328982:0) crwdns328984:0crwdne328984:0 +:return: The value converted to degrees""" ... def exp(x: float) -> float: - """Calculate the exponential of ``x``. + """crwdns328988:0``x``crwdne328988:0 (crwdns328986:0crwdne328986:0) - Example: ``math.exp(1)`` +Example: ``math.exp(1)`` - :param x: A number - :return: The exponential of ``x``. - """ +:param x: (crwdns328990:0crwdne328990:0) crwdns328992:0crwdne328992:0 +:return: The exponential of ``x``.""" ... def fabs(x: float) -> float: - """Return the absolute value of ``x``. + """crwdns328996:0``x``crwdne328996:0 (crwdns328994:0crwdne328994:0) - Example: ``math.fabs(-0.1)`` +Example: ``math.fabs(-0.1)`` - :param x: A number - :return: The absolute value of ``x`` - """ +:param x: (crwdns328998:0crwdne328998:0) crwdns329000:0crwdne329000:0 +:return: The absolute value of ``x``""" ... def floor(x: float) -> int: - """Round a number towards negative infinity. + """crwdns329004:0crwdne329004:0 (crwdns329002:0crwdne329002:0) - Example: ``math.floor(0.9)`` +Example: ``math.floor(0.9)`` - :param x: A number - :return: ``x`` rounded towards negative infinity. - """ +:param x: (crwdns329006:0crwdne329006:0) crwdns329008:0crwdne329008:0 +:return: ``x`` rounded towards negative infinity.""" ... def fmod(x: float, y: float) -> float: - """Calculate the remainder of ``x/y``. + """crwdns329012:0``x/y``crwdne329012:0 (crwdns329010:0crwdne329010:0) - Example: ``math.fmod(10, 3)`` +Example: ``math.fmod(10, 3)`` - :param x: The numerator - :param y: The denominator - """ +:param x: (crwdns329014:0crwdne329014:0) crwdns329016:0crwdne329016:0 +:param y: (crwdns329018:0crwdne329018:0) crwdns329020:0crwdne329020:0""" ... def frexp(x: float) -> Tuple[float, int]: - """Decomposes a floating-point number into its mantissa and exponent. + """crwdns329024:0crwdne329024:0 (crwdns329022:0crwdne329022:0) - Example: ``mantissa, exponent = math.frexp(2)`` +Example: ``mantissa, exponent = math.frexp(2)`` - The returned value is the tuple ``(m, e)`` such that ``x == m * 2**e`` - exactly. If ``x == 0`` then the function returns ``(0.0, 0)``, otherwise - the relation ``0.5 <= abs(m) < 1`` holds. +The returned value is the tuple ``(m, e)`` such that ``x == m * 2**e`` +exactly. If ``x == 0`` then the function returns ``(0.0, 0)``, otherwise +the relation ``0.5 <= abs(m) < 1`` holds. - :param x: A floating-point number - :return: A tuple of length two containing its mantissa then exponent - """ +:param x: (crwdns329026:0crwdne329026:0) crwdns329028:0crwdne329028:0 +:return: A tuple of length two containing its mantissa then exponent""" ... def isfinite(x: float) -> bool: - """Check if a value is finite. + """crwdns329032:0crwdne329032:0 (crwdns329030:0crwdne329030:0) - Example: ``math.isfinite(float('inf'))`` +Example: ``math.isfinite(float('inf'))`` - :param x: A number. - :return: ``True`` if ``x`` is finite, ``False`` otherwise. - """ +:param x: (crwdns329034:0crwdne329034:0) crwdns329036:0crwdne329036:0 +:return: ``True`` if ``x`` is finite, ``False`` otherwise.""" ... def isinf(x: float) -> bool: - """Check if a value is infinite. + """crwdns329040:0crwdne329040:0 (crwdns329038:0crwdne329038:0) - Example: ``math.isinf(float('-inf'))`` +Example: ``math.isinf(float('-inf'))`` - :param x: A number. - :return: ``True`` if ``x`` is infinite, ``False`` otherwise. - """ +:param x: (crwdns329042:0crwdne329042:0) crwdns329044:0crwdne329044:0 +:return: ``True`` if ``x`` is infinite, ``False`` otherwise.""" ... def isnan(x: float) -> bool: - """Check if a value is not-a-number (NaN). + """crwdns329048:0crwdne329048:0 (crwdns329046:0crwdne329046:0) - Example: ``math.isnan(float('nan'))`` +Example: ``math.isnan(float('nan'))`` - :param x: A number - :return: ``True`` if ``x`` is not-a-number (NaN), ``False`` otherwise.""" +:param x: (crwdns329050:0crwdne329050:0) crwdns329052:0crwdne329052:0 +:return: ``True`` if ``x`` is not-a-number (NaN), ``False`` otherwise.""" ... def ldexp(x: float, exp: int) -> float: - """Calculate ``x * (2**exp)``. + """crwdns329056:0crwdne329056:0 (crwdns329054:0crwdne329054:0) - Example: ``math.ldexp(0.5, 2)`` +Example: ``math.ldexp(0.5, 2)`` - :param x: A number - :param exp: Integer exponent - :return: ``x * (2**exp)`` - """ +:param x: (crwdns329062:0crwdne329062:0) crwdns329064:0crwdne329064:0 +:param exp: (crwdns329058:0crwdne329058:0) crwdns329060:0crwdne329060:0 +:return: ``x * (2**exp)``""" ... -def log(x: float, base: float = e) -> float: - """Calculate the logarithm of ``x`` to the given base (defaults to natural logorithm). +def log(x: float, base: float=e) -> float: + """crwdns329068:0``x``crwdne329068:0 (crwdns329066:0crwdne329066:0) - Example: ``math.log(math.e)`` +Example: ``math.log(math.e)`` - With one argument, return the natural logarithm of x (to base e). +With one argument, return the natural logarithm of x (to base e). - With two arguments, return the logarithm of x to the given base, calculated as ``log(x)/log(base)``. +With two arguments, return the logarithm of x to the given base, calculated as ``log(x)/log(base)``. - :param x: A number - :param base: The base to use - :return: The natural logarithm of ``x`` - """ +:param x: (crwdns329074:0crwdne329074:0) crwdns329076:0crwdne329076:0 +:param base: (crwdns329070:0crwdne329070:0) crwdns329072:0crwdne329072:0 +:return: The natural logarithm of ``x``""" ... def modf(x: float) -> Tuple[float, float]: - """Calculate the fractional and integral parts of ``x``. + """crwdns329080:0``x``crwdne329080:0 (crwdns329078:0crwdne329078:0) - Example: ``fractional, integral = math.modf(1.5)`` +Example: ``fractional, integral = math.modf(1.5)`` - :param x: A number - :return: A tuple of two floats representing the fractional then integral parts of ``x``. +:param x: (crwdns329082:0crwdne329082:0) crwdns329084:0crwdne329084:0 +:return: A tuple of two floats representing the fractional then integral parts of ``x``. - Both the fractional and integral values have the same sign as ``x``. - """ +Both the fractional and integral values have the same sign as ``x``.""" ... def pow(x: float, y: float) -> float: - """Returns ``x`` to the power of ``y``. + """crwdns329088:0``x``crwdnd329088:0``y``crwdne329088:0 (crwdns329086:0crwdne329086:0) - Example: ``math.pow(4, 0.5)`` +Example: ``math.pow(4, 0.5)`` - :param x: A number - :param y: The exponent - :return: ``x`` to the power of ``y`` - """ +:param x: (crwdns329090:0crwdne329090:0) crwdns329092:0crwdne329092:0 +:param y: (crwdns329094:0crwdne329094:0) crwdns329096:0crwdne329096:0 +:return: ``x`` to the power of ``y``""" ... def radians(x: float) -> float: - """Convert a degrees to radians. + """crwdns329100:0crwdne329100:0 (crwdns329098:0crwdne329098:0) - Example: ``math.radians(360)`` +Example: ``math.radians(360)`` - :param x: A value in degrees - :return: The value converted to radians - """ +:param x: (crwdns329102:0crwdne329102:0) crwdns329104:0crwdne329104:0 +:return: The value converted to radians""" ... def sin(x: float) -> float: - """Calculate the sine of ``x``. + """crwdns329108:0``x``crwdne329108:0 (crwdns329106:0crwdne329106:0) - Example: ``math.sin(math.pi/2)`` +Example: ``math.sin(math.pi/2)`` - :param x: A number - :return: The sine of ``x`` - """ +:param x: (crwdns329110:0crwdne329110:0) crwdns329112:0crwdne329112:0 +:return: The sine of ``x``""" ... def sqrt(x: float) -> float: - """Calculate the square root of ``x``. + """crwdns329116:0``x``crwdne329116:0 (crwdns329114:0crwdne329114:0) - Example: ``math.sqrt(4)`` +Example: ``math.sqrt(4)`` - :param x: A number - :return: The square root of ``x`` - """ +:param x: (crwdns329118:0crwdne329118:0) crwdns329120:0crwdne329120:0 +:return: The square root of ``x``""" ... def tan(x: float) -> float: - """Calculate the tangent of ``x``. + """crwdns329124:0``x``crwdne329124:0 (crwdns329122:0crwdne329122:0) - Example: ``math.tan(0)`` +Example: ``math.tan(0)`` - :param x: A number - :return: The tangent of ``x``. - """ +:param x: (crwdns329126:0crwdne329126:0) crwdns329128:0crwdne329128:0 +:return: The tangent of ``x``.""" ... def trunc(x: float) -> int: - """Round a number towards 0. + """crwdns329132:0crwdne329132:0 (crwdns329130:0crwdne329130:0) - Example: ``math.trunc(-0.9)`` +Example: ``math.trunc(-0.9)`` - :param x: A number - :return: ``x`` rounded towards zero. - """ +:param x: (crwdns329134:0crwdne329134:0) crwdns329136:0crwdne329136:0 +:return: ``x`` rounded towards zero.""" ... - e: float -"""Base of the natural logarithm""" - +"""crwdns329140:0crwdne329140:0 (crwdns329138:0crwdne329138:0)""" pi: float -"""The ratio of a circle's circumference to its diameter""" +"""crwdns329144:0crwdne329144:0 (crwdns329142:0crwdne329142:0)""" \ No newline at end of file diff --git a/lang/lol/typeshed/stdlib/microbit/__init__.pyi b/lang/lol/typeshed/stdlib/microbit/__init__.pyi index f12158f..f0c5493 100644 --- a/lang/lol/typeshed/stdlib/microbit/__init__.pyi +++ b/lang/lol/typeshed/stdlib/microbit/__init__.pyi @@ -1,11 +1,6 @@ -"""Pins, images, sounds, temperature and volume. -""" - +"""crwdns329148:0crwdne329148:0 (crwdns329146:0crwdne329146:0)""" from typing import Any, Callable, List, Optional, Tuple, Union, overload - from _typeshed import ReadableBuffer - -# V2 only from . import accelerometer as accelerometer from . import audio as audio from . import compass as compass @@ -16,831 +11,696 @@ from . import speaker as speaker from . import spi as spi from . import uart as uart -def run_every( - callback: Optional[Callable[[], None]] = None, - days: int = 0, - h: int = 0, - min: int = 0, - s: int = 0, - ms: int = 0, -) -> Callable[[Callable[[], None]], Callable[[], None]]: - """Schedule to run a function at the interval specified by the time arguments **V2 only**. +def run_every(callback: Optional[Callable[[], None]]=None, days: int=0, h: int=0, min: int=0, s: int=0, ms: int=0) -> Callable[[Callable[[], None]], Callable[[], None]]: + """crwdns335788:0crwdne335788:0 (crwdns329150:0crwdne329150:0) - Example: ``run_every(my_logging, min=5)`` +Example: ``run_every(my_logging, min=5)`` - ``run_every`` can be used in two ways: +``run_every`` can be used in two ways: - As a Decorator - placed on top of the function to schedule. For example:: +As a Decorator - placed on top of the function to schedule. For example:: - @run_every(h=1, min=20, s=30, ms=50) - def my_function(): - # Do something here + @run_every(h=1, min=20, s=30, ms=50) + def my_function(): + # Do something here - As a Function - passing the callback as a positional argument. For example:: +As a Function - passing the callback as a positional argument. For example:: - def my_function(): - # Do something here - run_every(my_function, s=30) + def my_function(): + # Do something here + run_every(my_function, s=30) - Each argument corresponds to a different time unit and they are additive. - So ``run_every(min=1, s=30)`` schedules the callback every minute and a half. +Each argument corresponds to a different time unit and they are additive. +So ``run_every(min=1, s=30)`` schedules the callback every minute and a half. - When an exception is thrown inside the callback function it deschedules the - function. To avoid this you can catch exceptions with ``try/except``. +When an exception is thrown inside the callback function it deschedules the +function. To avoid this you can catch exceptions with ``try/except``. - :param callback: Function to call at the provided interval. Omit when using as a decorator. - :param days: Sets the day mark for the scheduling. - :param h: Sets the hour mark for the scheduling. - :param min: Sets the minute mark for the scheduling. - :param s: Sets the second mark for the scheduling. - :param ms: Sets the millisecond mark for the scheduling. - """ +:param callback: (crwdns329154:0crwdne329154:0) crwdns335790:0crwdne335790:0 +:param days: (crwdns329158:0crwdne329158:0) crwdns335792:0crwdne335792:0 +:param h: (crwdns329162:0crwdne329162:0) crwdns335794:0crwdne335794:0 +:param min: (crwdns329166:0crwdne329166:0) crwdns335796:0crwdne335796:0 +:param s: (crwdns329174:0crwdne329174:0) crwdns335800:0crwdne335800:0 +:param ms: (crwdns329170:0crwdne329170:0) crwdns335798:0crwdne335798:0""" def panic(n: int) -> None: - """Enter a panic mode. + """crwdns329180:0crwdne329180:0 (crwdns329178:0crwdne329178:0) - Example: ``panic(127)`` +Example: ``panic(127)`` - :param n: An arbitrary integer <= 255 to indicate a status. +:param n: (crwdns329182:0crwdne329182:0) crwdns329184:0crwdne329184:0 - Requires restart. - """ +Requires restart.""" def reset() -> None: - """Restart the board.""" - + """crwdns329188:0crwdne329188:0 (crwdns329186:0crwdne329186:0)""" @overload def scale(value: float, from_: Tuple[float, float], to: Tuple[int, int]) -> int: - """Converts a value from a range to an integer range. + """crwdns336078:0crwdne336078:0 (crwdns336076:0crwdne336076:0) - Example: ``volume = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255))`` +Example: ``volume = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255))`` - For example, to convert an accelerometer X value to a speaker volume. +For example, to convert an accelerometer X value to a speaker volume. - If one of the numbers in the ``to`` parameter is a floating point - (i.e a decimal number like ``10.0``), this function will return a - floating point number. +If one of the numbers in the ``to`` parameter is a floating point +(i.e a decimal number like ``10.0``), this function will return a +floating point number. - temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0)) + temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0)) - :param value: A number to convert. - :param from_: A tuple to define the range to convert from. - :param to: A tuple to define the range to convert to. - :return: The ``value`` converted to the ``to`` range. - """ +:param value: (crwdns336088:0crwdne336088:0) crwdns336090:0crwdne336090:0 +:param from_: (crwdns336080:0crwdne336080:0) crwdns336082:0crwdne336082:0 +:param to: (crwdns336084:0crwdne336084:0) crwdns336086:0crwdne336086:0 +:return: The ``value`` converted to the ``to`` range.""" @overload def scale(value: float, from_: Tuple[float, float], to: Tuple[float, float]) -> float: - """Converts a value from a range to a floating point range. + """crwdns336094:0crwdne336094:0 (crwdns336092:0crwdne336092:0) - Example: ``temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0))`` +Example: ``temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0))`` - For example, to convert temperature from a Celsius scale to Fahrenheit. +For example, to convert temperature from a Celsius scale to Fahrenheit. - If one of the numbers in the ``to`` parameter is a floating point - (i.e a decimal number like ``10.0``), this function will return a - floating point number. - If they are both integers (i.e ``10``), it will return an integer:: +If one of the numbers in the ``to`` parameter is a floating point +(i.e a decimal number like ``10.0``), this function will return a +floating point number. +If they are both integers (i.e ``10``), it will return an integer:: - returns_int = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255)) + returns_int = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255)) - :param value: A number to convert. - :param from_: A tuple to define the range to convert from. - :param to: A tuple to define the range to convert to. - :return: The ``value`` converted to the ``to`` range. - """ +:param value: (crwdns336104:0crwdne336104:0) crwdns336106:0crwdne336106:0 +:param from_: (crwdns336096:0crwdne336096:0) crwdns336098:0crwdne336098:0 +:param to: (crwdns336100:0crwdne336100:0) crwdns336102:0crwdne336102:0 +:return: The ``value`` converted to the ``to`` range.""" def sleep(n: float) -> None: - """Wait for ``n`` milliseconds. + """crwdns329192:0``n``crwdne329192:0 (crwdns329190:0crwdne329190:0) - Example: ``sleep(1000)`` +Example: ``sleep(1000)`` - :param n: The number of milliseconds to wait +:param n: (crwdns329194:0crwdne329194:0) crwdns329196:0crwdne329196:0 - One second is 1000 milliseconds, so:: +One second is 1000 milliseconds, so:: - microbit.sleep(1000) + microbit.sleep(1000) - will pause the execution for one second. - """ +will pause the execution for one second.""" def running_time() -> int: - """Get the running time of the board. + """crwdns329200:0crwdne329200:0 (crwdns329198:0crwdne329198:0) - :return: The number of milliseconds since the board was switched on or restarted. - """ +:return: The number of milliseconds since the board was switched on or restarted.""" def temperature() -> int: - """Get the temperature of the micro:bit in degrees Celsius.""" + """crwdns329204:0crwdne329204:0 (crwdns329202:0crwdne329202:0)""" def set_volume(v: int) -> None: - """Sets the volume. + """crwdns329208:0crwdne329208:0 (crwdns329206:0crwdne329206:0) - Example: ``set_volume(127)`` +Example: ``set_volume(127)`` - :param v: a value between 0 (low) and 255 (high). +:param v: (crwdns329210:0crwdne329210:0) crwdns329212:0crwdne329212:0 - Out of range values will be clamped to 0 or 255. +Out of range values will be clamped to 0 or 255. - **V2** only. - """ +**V2** only.""" ... class Button: - """The class for the buttons ``button_a`` and ``button_b``.""" + """crwdns329216:0``button_a``crwdnd329216:0``button_b``crwdne329216:0 (crwdns329214:0crwdne329214:0)""" def is_pressed(self) -> bool: - """Check if the button is pressed. + """crwdns329220:0crwdne329220:0 (crwdns329218:0crwdne329218:0) - :return: ``True`` if the specified button ``button`` is pressed, and ``False`` otherwise. - """ +:return: ``True`` if the specified button ``button`` is pressed, and ``False`` otherwise.""" ... + def was_pressed(self) -> bool: - """Check if the button was pressed since the device started or the last time this method was called. + """crwdns329224:0crwdne329224:0 (crwdns329222:0crwdne329222:0) - Calling this method will clear the press state so - that the button must be pressed again before this method will return - ``True`` again. +Calling this method will clear the press state so +that the button must be pressed again before this method will return +``True`` again. - :return: ``True`` if the specified button ``button`` was pressed, and ``False`` otherwise - """ +:return: ``True`` if the specified button ``button`` was pressed, and ``False`` otherwise""" ... + def get_presses(self) -> int: - """Get the running total of button presses, and resets this total - to zero before returning. + """crwdns329228:0crwdne329228:0 (crwdns329226:0crwdne329226:0) - :return: The number of presses since the device started or the last time this method was called - """ +:return: The number of presses since the device started or the last time this method was called""" ... - button_a: Button -"""The left button ``Button`` object.""" - +"""crwdns329232:0``Button``crwdne329232:0 (crwdns329230:0crwdne329230:0)""" button_b: Button -"""The right button ``Button`` object.""" +"""crwdns329236:0``Button``crwdne329236:0 (crwdns329234:0crwdne329234:0)""" class MicroBitDigitalPin: - """A digital pin. - - Some pins support analog and touch features using the ``MicroBitAnalogDigitalPin`` and ``MicroBitTouchPin`` subclasses. - """ + """crwdns329240:0crwdne329240:0 (crwdns329238:0crwdne329238:0) +Some pins support analog and touch features using the ``MicroBitAnalogDigitalPin`` and ``MicroBitTouchPin`` subclasses.""" NO_PULL: int PULL_UP: int PULL_DOWN: int + def read_digital(self) -> int: - """Get the digital value of the pin. + """crwdns329244:0crwdne329244:0 (crwdns329242:0crwdne329242:0) - Example: ``value = pin0.read_digital()`` +Example: ``value = pin0.read_digital()`` - :return: 1 if the pin is high, and 0 if it's low. - """ +:return: 1 if the pin is high, and 0 if it's low.""" ... + def write_digital(self, value: int) -> None: - """Set the digital value of the pin. + """crwdns329248:0crwdne329248:0 (crwdns329246:0crwdne329246:0) - Example: ``pin0.write_digital(1)`` +Example: ``pin0.write_digital(1)`` - :param value: 1 to set the pin high or 0 to set the pin low""" +:param value: (crwdns329250:0crwdne329250:0) crwdns329252:0crwdne329252:0""" ... + def set_pull(self, value: int) -> None: - """Set the pull state to one of three possible values: ``PULL_UP``, ``PULL_DOWN`` or ``NO_PULL``. + """crwdns329256:0``PULL_UP``crwdnd329256:0``PULL_DOWN``crwdnd329256:0``NO_PULL``crwdne329256:0 (crwdns329254:0crwdne329254:0) - Example: ``pin0.set_pull(pin0.PULL_UP)`` +Example: ``pin0.set_pull(pin0.PULL_UP)`` - :param value: The pull state from the relevant pin, e.g. ``pin0.PULL_UP``. - """ +:param value: (crwdns329258:0crwdne329258:0) crwdns329260:0``pin0.PULL_UP``crwdne329260:0""" ... + def get_pull(self) -> int: - """Get the pull state on a pin. + """crwdns329264:0crwdne329264:0 (crwdns329262:0crwdne329262:0) - Example: ``pin0.get_pull()`` +Example: ``pin0.get_pull()`` - :return: ``NO_PULL``, ``PULL_DOWN``, or ``PULL_UP`` +:return: ``NO_PULL``, ``PULL_DOWN``, or ``PULL_UP`` - These are set using the ``set_pull()`` method or automatically configured - when a pin mode requires it. - """ +These are set using the ``set_pull()`` method or automatically configured +when a pin mode requires it.""" ... + def get_mode(self) -> str: - """Returns the pin mode. + """crwdns329268:0crwdne329268:0 (crwdns329266:0crwdne329266:0) - Example: ``pin0.get_mode()`` +Example: ``pin0.get_mode()`` - When a pin is used for a specific function, like - writing a digital value, or reading an analog value, the pin mode - changes. +When a pin is used for a specific function, like +writing a digital value, or reading an analog value, the pin mode +changes. - :return: ``"unused"``, ``"analog"``, ``"read_digital"``, ``"write_digital"``, ``"display"``, ``"button"``, ``"music"``, ``"audio"``, ``"touch"``, ``"i2c"``, or ``"spi"`` - """ +:return: ``"unused"``, ``"analog"``, ``"read_digital"``, ``"write_digital"``, ``"display"``, ``"button"``, ``"music"``, ``"audio"``, ``"touch"``, ``"i2c"``, or ``"spi"``""" ... + def write_analog(self, value: int) -> None: - """Output a PWM signal on the pin, with the duty cycle proportional to ``value``. + """crwdns329272:0``value``crwdne329272:0 (crwdns329270:0crwdne329270:0) + +Example: ``pin0.write_analog(254)`` - Example: ``pin0.write_analog(254)`` +:param value: (crwdns329274:0crwdne329274:0) crwdns329276:0crwdne329276:0""" - :param value: 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. + """crwdns329280:0``period``crwdne329280:0 (crwdns329278:0crwdne329278:0) - Example: ``pin0.set_analog_period(10)`` +Example: ``pin0.set_analog_period(10)`` + +:param period: (crwdns329282:0crwdne329282:0) crwdns329284:0crwdne329284:0""" - :param period: The period in milliseconds with a minimum valid value of 1ms. - """ def set_analog_period_microseconds(self, period: int) -> None: - """Set the period of the PWM signal being output to ``period`` in microseconds. + """crwdns329288:0``period``crwdne329288:0 (crwdns329286:0crwdne329286:0) - Example: ``pin0.set_analog_period_microseconds(512)`` +Example: ``pin0.set_analog_period_microseconds(512)`` - :param period: The period in microseconds with a minimum valid value of 256µs. - """ +:param period: (crwdns329290:0crwdne329290:0) crwdns329292:0crwdne329292:0""" class MicroBitAnalogDigitalPin(MicroBitDigitalPin): - """A pin with analog and digital features.""" + """crwdns329296:0crwdne329296:0 (crwdns329294:0crwdne329294:0)""" def read_analog(self) -> int: - """Read the voltage applied to the pin. + """crwdns329300:0crwdne329300:0 (crwdns329298:0crwdne329298:0) - Example: ``pin0.read_analog()`` +Example: ``pin0.read_analog()`` - :return: An integer between 0 (meaning 0V) and 1023 (meaning 3.3V). - """ +:return: An integer between 0 (meaning 0V) and 1023 (meaning 3.3V).""" class MicroBitTouchPin(MicroBitAnalogDigitalPin): - """A pin with analog, digital and touch features.""" - + """crwdns329304:0crwdne329304:0 (crwdns329302:0crwdne329302:0)""" CAPACITIVE: int RESISTIVE: int + def is_touched(self) -> bool: - """Check if the pin is being touched. + """crwdns329308:0crwdne329308:0 (crwdns329306:0crwdne329306:0) - Example: ``pin0.is_touched()`` +Example: ``pin0.is_touched()`` - The default touch mode for the pins on the edge connector is ``resistive``. - The default for the logo pin **V2** is ``capacitive``. +The default touch mode for the pins on the edge connector is ``resistive``. +The default for the logo pin **V2** is ``capacitive``. - **Resistive touch** - This test is done by measuring how much resistance there is between the - pin and ground. A low resistance gives a reading of ``True``. To get - a reliable reading using a finger you may need to touch the ground pin - with another part of your body, for example your other hand. +**Resistive touch** +This test is done by measuring how much resistance there is between the +pin and ground. A low resistance gives a reading of ``True``. To get +a reliable reading using a finger you may need to touch the ground pin +with another part of your body, for example your other hand. - **Capacitive touch** - This test is done by interacting with the electric field of a capacitor - using a finger as a conductor. `Capacitive touch - `_ - does not require you to make a ground connection as part of a circuit. +**Capacitive touch** +This test is done by interacting with the electric field of a capacitor +using a finger as a conductor. `Capacitive touch +`_ +does not require you to make a ground connection as part of a circuit. - :return: ``True`` if the pin is being touched with a finger, otherwise return ``False``. - """ +:return: ``True`` if the pin is being touched with a finger, otherwise return ``False``.""" ... + def set_touch_mode(self, value: int) -> None: - """Set the touch mode for the pin. + """crwdns329312:0crwdne329312:0 (crwdns329310:0crwdne329310:0) - Example: ``pin0.set_touch_mode(pin0.CAPACITIVE)`` +Example: ``pin0.set_touch_mode(pin0.CAPACITIVE)`` - The default touch mode for the pins on the edge connector is - ``resistive``. The default for the logo pin **V2** is ``capacitive``. +The default touch mode for the pins on the edge connector is +``resistive``. The default for the logo pin **V2** is ``capacitive``. - :param value: ``CAPACITIVE`` or ``RESISTIVE`` from the relevant pin. - """ +:param value: (crwdns329314:0crwdne329314:0) crwdns329316:0``CAPACITIVE``crwdnd329316:0``RESISTIVE``crwdne329316:0""" ... - pin0: MicroBitTouchPin -"""Pin with digital, analog and touch features.""" - +"""crwdns329320:0crwdne329320:0 (crwdns329318:0crwdne329318:0)""" pin1: MicroBitTouchPin -"""Pin with digital, analog and touch features.""" - +"""crwdns329324:0crwdne329324:0 (crwdns329322:0crwdne329322:0)""" pin2: MicroBitTouchPin -"""Pin with digital, analog and touch features.""" - +"""crwdns329328:0crwdne329328:0 (crwdns329326:0crwdne329326:0)""" pin3: MicroBitAnalogDigitalPin -"""Pin with digital and analog features.""" - +"""crwdns329332:0crwdne329332:0 (crwdns329330:0crwdne329330:0)""" pin4: MicroBitAnalogDigitalPin -"""Pin with digital and analog features.""" - +"""crwdns329336:0crwdne329336:0 (crwdns329334:0crwdne329334:0)""" pin5: MicroBitDigitalPin -"""Pin with digital features.""" - +"""crwdns329340:0crwdne329340:0 (crwdns329338:0crwdne329338:0)""" pin6: MicroBitDigitalPin -"""Pin with digital features.""" - +"""crwdns329344:0crwdne329344:0 (crwdns329342:0crwdne329342:0)""" pin7: MicroBitDigitalPin -"""Pin with digital features.""" - +"""crwdns329348:0crwdne329348:0 (crwdns329346:0crwdne329346:0)""" pin8: MicroBitDigitalPin -"""Pin with digital features.""" - +"""crwdns329352:0crwdne329352:0 (crwdns329350:0crwdne329350:0)""" pin9: MicroBitDigitalPin -"""Pin with digital features.""" - +"""crwdns329356:0crwdne329356:0 (crwdns329354:0crwdne329354:0)""" pin10: MicroBitAnalogDigitalPin -"""Pin with digital and analog features.""" - +"""crwdns329360:0crwdne329360:0 (crwdns329358:0crwdne329358:0)""" pin11: MicroBitDigitalPin -"""Pin with digital features.""" - +"""crwdns329364:0crwdne329364:0 (crwdns329362:0crwdne329362:0)""" pin12: MicroBitDigitalPin -"""Pin with digital features.""" - +"""crwdns329368:0crwdne329368:0 (crwdns329366:0crwdne329366:0)""" pin13: MicroBitDigitalPin -"""Pin with digital features.""" - +"""crwdns329372:0crwdne329372:0 (crwdns329370:0crwdne329370:0)""" pin14: MicroBitDigitalPin -"""Pin with digital features.""" - +"""crwdns329376:0crwdne329376:0 (crwdns329374:0crwdne329374:0)""" pin15: MicroBitDigitalPin -"""Pin with digital features.""" - +"""crwdns329380:0crwdne329380:0 (crwdns329378:0crwdne329378:0)""" pin16: MicroBitDigitalPin -"""Pin with digital features.""" - +"""crwdns329384:0crwdne329384:0 (crwdns329382:0crwdne329382:0)""" pin19: MicroBitDigitalPin -"""Pin with digital features.""" - +"""crwdns329388:0crwdne329388:0 (crwdns329386:0crwdne329386:0)""" pin20: MicroBitDigitalPin -"""Pin with digital features.""" - +"""crwdns329392:0crwdne329392:0 (crwdns329390:0crwdne329390:0)""" pin_logo: MicroBitTouchPin -"""A touch sensitive logo pin on the front of the micro:bit, which by default is set to capacitive touch mode.""" - +"""crwdns329396:0crwdne329396:0 (crwdns329394:0crwdne329394:0)""" pin_speaker: MicroBitAnalogDigitalPin -"""A pin to address the micro:bit speaker. +"""crwdns329400:0crwdne329400:0 (crwdns329398:0crwdne329398:0) This API is intended only for use in Pulse-Width Modulation pin operations e.g. pin_speaker.write_analog(128). """ class Image: - """An image to show on the micro:bit LED display. + """crwdns329404:0crwdne329404:0 (crwdns329402:0crwdne329402:0) - Given an image object it's possible to display it via the ``display`` API:: - - display.show(Image.HAPPY) - """ +Given an image object it's possible to display it via the ``display`` API:: + display.show(Image.HAPPY)""" HEART: Image - """Heart image.""" - + """crwdns329408:0crwdne329408:0 (crwdns329406:0crwdne329406:0)""" HEART_SMALL: Image - """Small heart image.""" - + """crwdns329412:0crwdne329412:0 (crwdns329410:0crwdne329410:0)""" HAPPY: Image - """Happy face image.""" - + """crwdns329416:0crwdne329416:0 (crwdns329414:0crwdne329414:0)""" SMILE: Image - """Smiling mouth image.""" - + """crwdns329420:0crwdne329420:0 (crwdns329418:0crwdne329418:0)""" SAD: Image - """Sad face image.""" - + """crwdns329424:0crwdne329424:0 (crwdns329422:0crwdne329422:0)""" CONFUSED: Image - """Confused face image.""" - + """crwdns329428:0crwdne329428:0 (crwdns329426:0crwdne329426:0)""" ANGRY: Image - """Angry face image.""" - + """crwdns329432:0crwdne329432:0 (crwdns329430:0crwdne329430:0)""" ASLEEP: Image - """Sleeping face image.""" - + """crwdns329436:0crwdne329436:0 (crwdns329434:0crwdne329434:0)""" SURPRISED: Image - """Surprised face image.""" - + """crwdns329440:0crwdne329440:0 (crwdns329438:0crwdne329438:0)""" SILLY: Image - """Silly face image.""" - + """crwdns329444:0crwdne329444:0 (crwdns329442:0crwdne329442:0)""" FABULOUS: Image - """Sunglasses face image.""" - + """crwdns329448:0crwdne329448:0 (crwdns329446:0crwdne329446:0)""" MEH: Image - """Unimpressed face image.""" - + """crwdns329452:0crwdne329452:0 (crwdns329450:0crwdne329450:0)""" YES: Image - """Tick image.""" - + """crwdns329456:0crwdne329456:0 (crwdns329454:0crwdne329454:0)""" NO: Image - """Cross image.""" - + """crwdns329460:0crwdne329460:0 (crwdns329458:0crwdne329458:0)""" CLOCK12: Image - """Image with line pointing to 12 o'clock.""" - + """crwdns329464:0crwdne329464:0 (crwdns329462:0crwdne329462:0)""" CLOCK11: Image - """Image with line pointing to 11 o'clock.""" - + """crwdns329468:0crwdne329468:0 (crwdns329466:0crwdne329466:0)""" CLOCK10: Image - """Image with line pointing to 10 o'clock.""" - + """crwdns329472:0crwdne329472:0 (crwdns329470:0crwdne329470:0)""" CLOCK9: Image - """Image with line pointing to 9 o'clock.""" - + """crwdns329476:0crwdne329476:0 (crwdns329474:0crwdne329474:0)""" CLOCK8: Image - """Image with line pointing to 8 o'clock.""" - + """crwdns329480:0crwdne329480:0 (crwdns329478:0crwdne329478:0)""" CLOCK7: Image - """Image with line pointing to 7 o'clock.""" - + """crwdns329484:0crwdne329484:0 (crwdns329482:0crwdne329482:0)""" CLOCK6: Image - """Image with line pointing to 6 o'clock.""" - + """crwdns329488:0crwdne329488:0 (crwdns329486:0crwdne329486:0)""" CLOCK5: Image - """Image with line pointing to 5 o'clock.""" - + """crwdns329492:0crwdne329492:0 (crwdns329490:0crwdne329490:0)""" CLOCK4: Image - """Image with line pointing to 4 o'clock.""" - + """crwdns329496:0crwdne329496:0 (crwdns329494:0crwdne329494:0)""" CLOCK3: Image - """Image with line pointing to 3 o'clock.""" - + """crwdns329500:0crwdne329500:0 (crwdns329498:0crwdne329498:0)""" CLOCK2: Image - """Image with line pointing to 2 o'clock.""" - + """crwdns329504:0crwdne329504:0 (crwdns329502:0crwdne329502:0)""" CLOCK1: Image - """Image with line pointing to 1 o'clock.""" - + """crwdns329508:0crwdne329508:0 (crwdns329506:0crwdne329506:0)""" ARROW_N: Image - """Image of arrow pointing north.""" - + """crwdns329512:0crwdne329512:0 (crwdns329510:0crwdne329510:0)""" ARROW_NE: Image - """Image of arrow pointing north east.""" - + """crwdns329516:0crwdne329516:0 (crwdns329514:0crwdne329514:0)""" ARROW_E: Image - """Image of arrow pointing east.""" - + """crwdns329520:0crwdne329520:0 (crwdns329518:0crwdne329518:0)""" ARROW_SE: Image - """Image of arrow pointing south east.""" - + """crwdns329524:0crwdne329524:0 (crwdns329522:0crwdne329522:0)""" ARROW_S: Image - """Image of arrow pointing south.""" - + """crwdns329528:0crwdne329528:0 (crwdns329526:0crwdne329526:0)""" ARROW_SW: Image - """Image of arrow pointing south west.""" - + """crwdns329532:0crwdne329532:0 (crwdns329530:0crwdne329530:0)""" ARROW_W: Image - """Image of arrow pointing west.""" - + """crwdns329536:0crwdne329536:0 (crwdns329534:0crwdne329534:0)""" ARROW_NW: Image - """Image of arrow pointing north west.""" - + """crwdns329540:0crwdne329540:0 (crwdns329538:0crwdne329538:0)""" TRIANGLE: Image - """Image of a triangle pointing up.""" - + """crwdns329544:0crwdne329544:0 (crwdns329542:0crwdne329542:0)""" TRIANGLE_LEFT: Image - """Image of a triangle in the left corner.""" - + """crwdns329548:0crwdne329548:0 (crwdns329546:0crwdne329546:0)""" CHESSBOARD: Image - """Alternate LEDs lit in a chessboard pattern.""" - + """crwdns329552:0crwdne329552:0 (crwdns329550:0crwdne329550:0)""" DIAMOND: Image - """Diamond image.""" - + """crwdns329556:0crwdne329556:0 (crwdns329554:0crwdne329554:0)""" DIAMOND_SMALL: Image - """Small diamond image.""" - + """crwdns329560:0crwdne329560:0 (crwdns329558:0crwdne329558:0)""" SQUARE: Image - """Square image.""" - + """crwdns329564:0crwdne329564:0 (crwdns329562:0crwdne329562:0)""" SQUARE_SMALL: Image - """Small square image.""" - + """crwdns329568:0crwdne329568:0 (crwdns329566:0crwdne329566:0)""" RABBIT: Image - """Rabbit image.""" - + """crwdns329572:0crwdne329572:0 (crwdns329570:0crwdne329570:0)""" COW: Image - """Cow image.""" - + """crwdns329576:0crwdne329576:0 (crwdns329574:0crwdne329574:0)""" MUSIC_CROTCHET: Image - """Crotchet note image.""" - + """crwdns329580:0crwdne329580:0 (crwdns329578:0crwdne329578:0)""" MUSIC_QUAVER: Image - """Quaver note image.""" - + """crwdns329584:0crwdne329584:0 (crwdns329582:0crwdne329582:0)""" MUSIC_QUAVERS: Image - """Pair of quavers note image.""" - + """crwdns329588:0crwdne329588:0 (crwdns329586:0crwdne329586:0)""" PITCHFORK: Image - """Pitchfork image.""" - + """crwdns329592:0crwdne329592:0 (crwdns329590:0crwdne329590:0)""" XMAS: Image - """Christmas tree image.""" - + """crwdns329596:0crwdne329596:0 (crwdns329594:0crwdne329594:0)""" PACMAN: Image - """Pac-Man arcade character image.""" - + """crwdns329600:0crwdne329600:0 (crwdns329598:0crwdne329598:0)""" TARGET: Image - """Target image.""" - + """crwdns329604:0crwdne329604:0 (crwdns329602:0crwdne329602:0)""" TSHIRT: Image - """T-shirt image.""" - + """crwdns329608:0crwdne329608:0 (crwdns329606:0crwdne329606:0)""" ROLLERSKATE: Image - """Rollerskate image.""" - + """crwdns329612:0crwdne329612:0 (crwdns329610:0crwdne329610:0)""" DUCK: Image - """Duck image.""" - + """crwdns329616:0crwdne329616:0 (crwdns329614:0crwdne329614:0)""" HOUSE: Image - """House image.""" - + """crwdns329620:0crwdne329620:0 (crwdns329618:0crwdne329618:0)""" TORTOISE: Image - """Tortoise image.""" - + """crwdns329624:0crwdne329624:0 (crwdns329622:0crwdne329622:0)""" BUTTERFLY: Image - """Butterfly image.""" - + """crwdns329628:0crwdne329628:0 (crwdns329626:0crwdne329626:0)""" STICKFIGURE: Image - """Stick figure image.""" - + """crwdns329632:0crwdne329632:0 (crwdns329630:0crwdne329630:0)""" GHOST: Image - """Ghost image.""" - + """crwdns329636:0crwdne329636:0 (crwdns329634:0crwdne329634:0)""" SWORD: Image - """Sword image.""" - + """crwdns329640:0crwdne329640:0 (crwdns329638:0crwdne329638:0)""" GIRAFFE: Image - """Giraffe image.""" - + """crwdns329644:0crwdne329644:0 (crwdns329642:0crwdne329642:0)""" SKULL: Image - """Skull image.""" - + """crwdns329648:0crwdne329648:0 (crwdns329646:0crwdne329646:0)""" UMBRELLA: Image - """Umbrella image.""" - + """crwdns329652:0crwdne329652:0 (crwdns329650:0crwdne329650:0)""" SNAKE: Image - """Snake image.""" - + """crwdns329656:0crwdne329656:0 (crwdns329654:0crwdne329654:0)""" SCISSORS: Image - """Scissors image.""" - + """crwdns335820:0crwdne335820:0 (crwdns335818:0crwdne335818:0)""" ALL_CLOCKS: List[Image] - """A list containing all the CLOCK_ images in sequence.""" - + """crwdns329660:0crwdne329660:0 (crwdns329658:0crwdne329658:0)""" ALL_ARROWS: List[Image] - """A list containing all the ARROW_ images in sequence.""" + """crwdns329664:0crwdne329664:0 (crwdns329662:0crwdne329662:0)""" + @overload def __init__(self, string: str) -> None: - """Create an image from a string describing which LEDs are lit. + """crwdns329668:0crwdne329668:0 (crwdns329666:0crwdne329666:0) - ``string`` has to consist of digits 0-9 arranged into lines, - describing the image, for example:: +``string`` has to consist of digits 0-9 arranged into lines, +describing the image, for example:: - image = Image("90009:" - "09090:" - "00900:" - "09090:" - "90009") + 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 newlines (\\n) insead of the colons. +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 newlines (\\n) insead of the colons. - :param string: The string describing the image. - """ +:param string: (crwdns329670:0crwdne329670:0) crwdns329672:0crwdne329672:0""" ... + @overload - def __init__( - self, width: int = 5, height: int = 5, buffer: ReadableBuffer = None - ) -> None: - """Create an empty image with ``width`` columns and ``height`` rows. + def __init__(self, width: int=5, height: int=5, buffer: ReadableBuffer=None) -> None: + """crwdns329676:0``width``crwdnd329676:0``height``crwdne329676:0 (crwdns329674:0crwdne329674:0) - :param width: Optional width of the image - :param height: Optional height of the image - :param buffer: Optional array or bytes of ``width``×``height`` integers in range 0-9 to initialize the image +:param width: (crwdns329686:0crwdne329686:0) crwdns329688:0crwdne329688:0 +:param height: (crwdns329682:0crwdne329682:0) crwdns329684:0crwdne329684:0 +:param buffer: (crwdns329678:0crwdne329678:0) crwdns329680:0``width``crwdnd329680:0``height``crwdne329680:0 - Examples:: +Examples:: - Image(2, 2, b'\x08\x08\x08\x08') - Image(2, 2, bytearray([9,9,9,9])) + Image(2, 2, b'\x08\x08\x08\x08') + Image(2, 2, bytearray([9,9,9,9])) - These create 2 x 2 pixel images at full brightness. - """ +These create 2 x 2 pixel images at full brightness.""" ... + def width(self) -> int: - """Get the number of columns. + """crwdns329692:0crwdne329692:0 (crwdns329690:0crwdne329690:0) - :return: The number of columns in the image - """ +:return: The number of columns in the image""" ... + def height(self) -> int: - """Get the number of rows. + """crwdns329696:0crwdne329696:0 (crwdns329694:0crwdne329694:0) - :return: The number of rows in the image - """ +:return: The number of rows in the image""" ... + def set_pixel(self, x: int, y: int, value: int) -> None: - """Set the brightness of a pixel. + """crwdns329700:0crwdne329700:0 (crwdns329698:0crwdne329698:0) - Example: ``my_image.set_pixel(0, 0, 9)`` +Example: ``my_image.set_pixel(0, 0, 9)`` - :param x: The column number - :param y: The row number - :param value: The brightness as an integer between 0 (dark) and 9 (bright) +:param x: (crwdns329706:0crwdne329706:0) crwdns329708:0crwdne329708:0 +:param y: (crwdns329710:0crwdne329710:0) crwdns329712:0crwdne329712:0 +:param value: (crwdns329702:0crwdne329702:0) crwdns329704:0crwdne329704:0 - This method will raise an exception when called on any of the built-in - read-only images, like ``Image.HEART``. - """ +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: - """Get the brightness of a pixel. + """crwdns329716:0crwdne329716:0 (crwdns329714:0crwdne329714:0) - Example: ``my_image.get_pixel(0, 0)`` +Example: ``my_image.get_pixel(0, 0)`` - :param x: The column number - :param y: The row number - :return: The brightness as an integer between 0 and 9. - """ +:param x: (crwdns329718:0crwdne329718:0) crwdns329720:0crwdne329720:0 +:param y: (crwdns329722:0crwdne329722:0) crwdns329724:0crwdne329724:0 +:return: The brightness as an integer between 0 and 9.""" ... + def shift_left(self, n: int) -> Image: - """Create a new image by shifting the picture left. + """crwdns329728:0crwdne329728:0 (crwdns329726:0crwdne329726:0) - Example: ``Image.HEART_SMALL.shift_left(1)`` +Example: ``Image.HEART_SMALL.shift_left(1)`` - :param n: The number of columns to shift by - :return: The shifted image - """ +:param n: (crwdns329730:0crwdne329730:0) crwdns329732:0crwdne329732:0 +:return: The shifted image""" ... + def shift_right(self, n: int) -> Image: - """Create a new image by shifting the picture right. + """crwdns329736:0crwdne329736:0 (crwdns329734:0crwdne329734:0) - Example: ``Image.HEART_SMALL.shift_right(1)`` +Example: ``Image.HEART_SMALL.shift_right(1)`` - :param n: The number of columns to shift by - :return: The shifted image - """ +:param n: (crwdns329738:0crwdne329738:0) crwdns329740:0crwdne329740:0 +:return: The shifted image""" ... + def shift_up(self, n: int) -> Image: - """Create a new image by shifting the picture up. + """crwdns329744:0crwdne329744:0 (crwdns329742:0crwdne329742:0) - Example: ``Image.HEART_SMALL.shift_up(1)`` +Example: ``Image.HEART_SMALL.shift_up(1)`` - :param n: The number of rows to shift by - :return: The shifted image - """ +:param n: (crwdns329746:0crwdne329746:0) crwdns329748:0crwdne329748:0 +:return: The shifted image""" ... + def shift_down(self, n: int) -> Image: - """Create a new image by shifting the picture down. + """crwdns329752:0crwdne329752:0 (crwdns329750:0crwdne329750:0) - Example: ``Image.HEART_SMALL.shift_down(1)`` +Example: ``Image.HEART_SMALL.shift_down(1)`` - :param n: The number of rows to shift by - :return: The shifted image - """ +:param n: (crwdns329754:0crwdne329754:0) crwdns329756:0crwdne329756:0 +:return: The shifted image""" ... + def crop(self, x: int, y: int, w: int, h: int) -> Image: - """Create a new image by cropping the picture. + """crwdns329760:0crwdne329760:0 (crwdns329758:0crwdne329758:0) - Example: ``Image.HEART.crop(1, 1, 3, 3)`` +Example: ``Image.HEART.crop(1, 1, 3, 3)`` - :param x: The crop offset column - :param y: The crop offset row - :param w: The crop width - :param h: The crop height - :return: The new image - """ +:param x: (crwdns329770:0crwdne329770:0) crwdns329772:0crwdne329772:0 +:param y: (crwdns329774:0crwdne329774:0) crwdns329776:0crwdne329776:0 +:param w: (crwdns329766:0crwdne329766:0) crwdns329768:0crwdne329768:0 +:param h: (crwdns329762:0crwdne329762:0) crwdns329764:0crwdne329764:0 +:return: The new image""" ... + def copy(self) -> Image: - """Create an exact copy of the image. + """crwdns329780:0crwdne329780:0 (crwdns329778:0crwdne329778:0) - Example: ``Image.HEART.copy()`` +Example: ``Image.HEART.copy()`` - :return: The new image - """ +:return: The new image""" ... + def invert(self) -> Image: - """Create a new image by inverting the brightness of the pixels in the - source image. + """crwdns329784:0crwdne329784:0 (crwdns329782:0crwdne329782:0) - Example: ``Image.SMALL_HEART.invert()`` +Example: ``Image.SMALL_HEART.invert()`` - :return: The new image. - """ +:return: The new image.""" ... + def fill(self, value: int) -> None: - """Set the brightness of all the pixels in the image. + """crwdns329788:0crwdne329788:0 (crwdns329786:0crwdne329786:0) - Example: ``my_image.fill(5)`` +Example: ``my_image.fill(5)`` - :param value: The new brightness as a number between 0 (dark) and 9 (bright). +:param value: (crwdns329790:0crwdne329790:0) crwdns329792:0crwdne329792:0 - This method will raise an exception when called on any of the built-in - read-only images, like ``Image.HEART``. - """ +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 an area from another image into this image. - - Example: ``my_image.blit(Image.HEART, 1, 1, 3, 3, 1, 1)`` - - :param src: The source image - :param x: The starting column offset in the source image - :param y: The starting row offset in the source image - :param w: The number of columns to copy - :param h: The number of rows to copy - :param xdest: The column offset to modify in this image - :param ydest: The row offset to modify in this image - - Pixels outside the source image are treated as having a brightness 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 blit(self, src: Image, x: int, y: int, w: int, h: int, xdest: int=0, ydest: int=0) -> None: + """crwdns329796:0crwdne329796:0 (crwdns329794:0crwdne329794:0) + +Example: ``my_image.blit(Image.HEART, 1, 1, 3, 3, 1, 1)`` + +:param src: (crwdns329802:0crwdne329802:0) crwdns329804:0crwdne329804:0 +:param x: (crwdns329810:0crwdne329810:0) crwdns329812:0crwdne329812:0 +:param y: (crwdns329818:0crwdne329818:0) crwdns329820:0crwdne329820:0 +:param w: (crwdns329806:0crwdne329806:0) crwdns329808:0crwdne329808:0 +:param h: (crwdns329798:0crwdne329798:0) crwdns329800:0crwdne329800:0 +:param xdest: (crwdns329814:0crwdne329814:0) crwdns329816:0crwdne329816:0 +:param ydest: (crwdns329822:0crwdne329822:0) crwdns329824:0crwdne329824:0 + +Pixels outside the source image are treated as having a brightness 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.""" + """crwdns329828:0crwdne329828:0 (crwdns329826:0crwdne329826:0)""" ... + def __str__(self) -> str: - """Get a readable string representation of the image.""" + """crwdns329832:0crwdne329832:0 (crwdns329830:0crwdne329830:0)""" ... + def __add__(self, other: Image) -> Image: - """Create a new image by adding the brightness values from the two - images for each pixel. + """crwdns329836:0crwdne329836:0 (crwdns329834:0crwdne329834:0) - Example: ``Image.HEART + Image.HAPPY`` +Example: ``Image.HEART + Image.HAPPY`` - :param other: The image to add. - """ +:param other: (crwdns329838:0crwdne329838:0) crwdns329840:0crwdne329840:0""" ... + def __sub__(self, other: Image) -> Image: - """Create a new image by subtracting the brightness values of the - other image from this image. + """crwdns329844:0crwdne329844:0 (crwdns329842:0crwdne329842:0) - Example: ``Image.HEART - Image.HEART_SMALL`` +Example: ``Image.HEART - Image.HEART_SMALL`` - :param other: The image to subtract. - """ +:param other: (crwdns329846:0crwdne329846:0) crwdns329848:0crwdne329848:0""" ... + def __mul__(self, n: float) -> Image: - """Create a new image by multiplying the brightness of each pixel by - ``n``. + """crwdns329852:0``n``crwdne329852:0 (crwdns329850:0crwdne329850:0) - Example: ``Image.HEART * 0.5`` +Example: ``Image.HEART * 0.5`` - :param n: The value to multiply by. - """ +:param n: (crwdns329854:0crwdne329854:0) crwdns329856:0crwdne329856:0""" ... + def __truediv__(self, n: float) -> Image: - """Create a new image by dividing the brightness of each pixel by - ``n``. + """crwdns329860:0``n``crwdne329860:0 (crwdns329858:0crwdne329858:0) - Example: ``Image.HEART / 2`` +Example: ``Image.HEART / 2`` - :param n: The value to divide by. - """ +:param n: (crwdns329862:0crwdne329862:0) crwdns329864:0crwdne329864:0""" ... class SoundEvent: LOUD: SoundEvent - """Represents the transition of sound events, from ``quiet`` to ``loud`` like clapping or shouting.""" - + """crwdns334408:0``quiet``crwdnd334408:0``loud``crwdne334408:0 (crwdns329866:0crwdne329866:0)""" QUIET: SoundEvent - """Represents the transition of sound events, from ``loud`` to ``quiet`` like speaking or background music.""" + """crwdns334410:0``loud``crwdnd334410:0``quiet``crwdne334410:0 (crwdns329870:0crwdne329870:0)""" class Sound: - """The built-in sounds can be called using ``audio.play(Sound.NAME)``.""" - + """crwdns329876:0``audio.play(Sound.NAME)``crwdne329876:0 (crwdns329874:0crwdne329874:0)""" GIGGLE: Sound - """Giggling sound.""" - + """crwdns329880:0crwdne329880:0 (crwdns329878:0crwdne329878:0)""" HAPPY: Sound - """Happy sound.""" - + """crwdns329884:0crwdne329884:0 (crwdns329882:0crwdne329882:0)""" HELLO: Sound - """Greeting sound.""" - + """crwdns329888:0crwdne329888:0 (crwdns329886:0crwdne329886:0)""" MYSTERIOUS: Sound - """Mysterious sound.""" - + """crwdns329892:0crwdne329892:0 (crwdns329890:0crwdne329890:0)""" SAD: Sound - """Sad sound.""" - + """crwdns329896:0crwdne329896:0 (crwdns329894:0crwdne329894:0)""" SLIDE: Sound - """Sliding sound.""" - + """crwdns329900:0crwdne329900:0 (crwdns329898:0crwdne329898:0)""" SOARING: Sound - """Soaring sound.""" - + """crwdns329904:0crwdne329904:0 (crwdns329902:0crwdne329902:0)""" SPRING: Sound - """Spring sound.""" - + """crwdns329908:0crwdne329908:0 (crwdns329906:0crwdne329906:0)""" TWINKLE: Sound - """Twinkling sound.""" - + """crwdns329912:0crwdne329912:0 (crwdns329910:0crwdne329910:0)""" YAWN: Sound - """Yawning sound.""" + """crwdns329916:0crwdne329916:0 (crwdns329914:0crwdne329914:0)""" \ No newline at end of file diff --git a/lang/lol/typeshed/stdlib/microbit/accelerometer.pyi b/lang/lol/typeshed/stdlib/microbit/accelerometer.pyi index bac82c0..23c0aee 100644 --- a/lang/lol/typeshed/stdlib/microbit/accelerometer.pyi +++ b/lang/lol/typeshed/stdlib/microbit/accelerometer.pyi @@ -1,115 +1,103 @@ -"""Measure the acceleration of the micro:bit and recognise gestures. -""" - +"""crwdns329920:0crwdne329920:0 (crwdns329918:0crwdne329918:0)""" from typing import Tuple def get_x() -> int: - """Get the acceleration measurement in the ``x`` axis in milli-g. + """crwdns329924:0``x``crwdne329924:0 (crwdns329922:0crwdne329922:0) - Example: ``accelerometer.get_x()`` +Example: ``accelerometer.get_x()`` - :return: A positive or negative integer depending on direction in the range +/- 2000mg. - """ +:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" ... def get_y() -> int: - """Get the acceleration measurement in the ``y`` axis in milli-g. + """crwdns329928:0``y``crwdne329928:0 (crwdns329926:0crwdne329926:0) - Example: ``accelerometer.get_y()`` +Example: ``accelerometer.get_y()`` - :return: A positive or negative integer depending on direction in the range +/- 2000mg. - """ +:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" ... def get_z() -> int: - """Get the acceleration measurement in the ``z`` axis in milli-g. + """crwdns329932:0``z``crwdne329932:0 (crwdns329930:0crwdne329930:0) - Example: ``accelerometer.get_z()`` +Example: ``accelerometer.get_z()`` - :return: A positive or negative integer depending on direction in the range +/- 2000mg. - """ +:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" ... def get_values() -> Tuple[int, int, int]: - """Get the acceleration measurements in all axes at once as a tuple. + """crwdns329936:0crwdne329936:0 (crwdns329934:0crwdne329934:0) - Example: ``x, y, z = accelerometer.get_values()`` +Example: ``x, y, z = accelerometer.get_values()`` - :return: a three-element tuple of integers ordered as X, Y, Z, each value a positive or negative integer depending on direction in the range +/- 2000mg - """ +:return: a three-element tuple of integers ordered as X, Y, Z, each value a positive or negative integer depending on direction in the range +/- 2000mg""" ... def get_strength() -> int: - """Get the acceleration measurement of all axes combined, as a positive integer. This is the Pythagorean sum of the X, Y and Z axes. + """crwdns335824:0crwdne335824:0 (crwdns335822:0crwdne335822:0) - Example: ``accelerometer.get_strength()`` +Example: ``accelerometer.get_strength()`` - :return: The combined acceleration strength of all the axes, in milli-g. - """ +:return: The combined acceleration strength of all the axes, in milli-g.""" ... def current_gesture() -> str: - """Get the name of the current gesture. + """crwdns329940:0crwdne329940:0 (crwdns329938:0crwdne329938:0) - Example: ``accelerometer.current_gesture()`` +Example: ``accelerometer.current_gesture()`` - 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. +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. - :return: The current gesture - """ +:return: The current gesture""" ... def is_gesture(name: str) -> bool: - """Check if the named gesture is currently active. + """crwdns329944:0crwdne329944:0 (crwdns329942:0crwdne329942:0) - Example: ``accelerometer.is_gesture('shake')`` +Example: ``accelerometer.is_gesture('shake')`` - 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. +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. - :param name: The gesture name. - :return: ``True`` if the gesture is active, ``False`` otherwise. - """ +:param name: (crwdns329946:0crwdne329946:0) crwdns329948:0crwdne329948:0 +:return: ``True`` if the gesture is active, ``False`` otherwise.""" ... def was_gesture(name: str) -> bool: - """Check if the named gesture was active since the last call. + """crwdns329952:0crwdne329952:0 (crwdns329950:0crwdne329950:0) - Example: ``accelerometer.was_gesture('shake')`` +Example: ``accelerometer.was_gesture('shake')`` - 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. +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. - :param name: The gesture name. - :return: ``True`` if the gesture was active since the last call, ``False`` otherwise. - """ +:param name: (crwdns329954:0crwdne329954:0) crwdns329956:0crwdne329956:0 +:return: ``True`` if the gesture was active since the last call, ``False`` otherwise.""" def get_gestures() -> Tuple[str, ...]: - """Return a tuple of the gesture history. + """crwdns329960:0crwdne329960:0 (crwdns329958:0crwdne329958:0) - Example: ``accelerometer.get_gestures()`` +Example: ``accelerometer.get_gestures()`` - Clears the gesture history before returning. +Clears the gesture history before returning. - Gestures are not updated in the background so there needs to be constant - calls to some accelerometer method to do the gesture detection. Usually - gestures can be detected using a loop with a small :func:`microbit.sleep` delay. +Gestures are not updated in the background so there needs to be constant +calls to some accelerometer method to do the gesture detection. Usually +gestures can be detected using a loop with a small :func:`microbit.sleep` delay. - :return: The history as a tuple, most recent last. - """ +:return: The history as a tuple, most recent last.""" ... def set_range(value: int) -> None: - """Set the accelerometer sensitivity range, in g (standard gravity), to the closest values supported by the hardware, so it rounds to either ``2``, ``4``, or ``8`` g. + """crwdns335828:0``2``crwdnd335828:0``4``crwdnd335828:0``8``crwdne335828:0 (crwdns335826:0crwdne335826:0) - Example: ``accelerometer.set_range(8)`` +Example: ``accelerometer.set_range(8)`` - :param value: New range for the accelerometer, an integer in ``g``. - """ +:param value: (crwdns335830:0crwdne335830:0) crwdns335832:0``g``crwdne335832:0""" \ No newline at end of file diff --git a/lang/lol/typeshed/stdlib/microbit/audio.pyi b/lang/lol/typeshed/stdlib/microbit/audio.pyi index 3b1e327..8cbcbf8 100644 --- a/lang/lol/typeshed/stdlib/microbit/audio.pyi +++ b/lang/lol/typeshed/stdlib/microbit/audio.pyi @@ -1,160 +1,123 @@ -"""Play sounds using the micro:bit (import ``audio`` for V1 compatibility). -""" - +"""crwdns329964:0``audio``crwdne329964:0 (crwdns329962:0crwdne329962:0)""" from ..microbit import MicroBitDigitalPin, Sound, pin0 from typing import ClassVar, Iterable, Union -def play( - source: Union[Iterable[AudioFrame], Sound, SoundEffect], - wait: bool = True, - pin: MicroBitDigitalPin = pin0, - return_pin: Union[MicroBitDigitalPin, None] = None, -) -> None: - """Play a built-in sound, sound effect or custom audio frames. +def play(source: Union[Iterable[AudioFrame], Sound, SoundEffect], wait: bool=True, pin: MicroBitDigitalPin=pin0, return_pin: Union[MicroBitDigitalPin, None]=None) -> None: + """crwdns335834:0crwdne335834:0 (crwdns329966:0crwdne329966:0) - Example: ``audio.play(Sound.GIGGLE)`` +Example: ``audio.play(Sound.GIGGLE)`` - :param source: A built-in ``Sound`` such as ``Sound.GIGGLE``, a ``SoundEffect`` or sample data as an iterable of ``AudioFrame`` objects. - :param wait: If ``wait`` is ``True``, this function will block until the sound is complete. - :param pin: An optional argument to specify the output pin can be used to override the default of ``pin0``. If we do not want any sound to play we can use ``pin=None``. - :param return_pin: Specifies a differential edge connector pin to connect to an external speaker instead of ground. This is ignored for the **V2** revision. - """ +:param source: (crwdns329978:0crwdne329978:0) crwdns335836:0``Sound``crwdnd335836:0``Sound.GIGGLE``crwdnd335836:0``SoundEffect``crwdnd335836:0``AudioFrame``crwdne335836:0 +:param wait: (crwdns329982:0crwdne329982:0) crwdns329984:0``wait``crwdnd329984:0``True``crwdne329984:0 +:param pin: (crwdns329970:0crwdne329970:0) crwdns329972:0``pin0``crwdne329972:0 +:param return_pin: (crwdns329974:0crwdne329974:0) crwdns329976:0crwdne329976:0""" def is_playing() -> bool: - """Check whether a sound is playing. + """crwdns329988:0crwdne329988:0 (crwdns329986:0crwdne329986:0) - Example: ``audio.is_playing()`` +Example: ``audio.is_playing()`` - :return: ``True`` if audio is playing, otherwise ``False``.""" +:return: ``True`` if audio is playing, otherwise ``False``.""" ... def stop() -> None: - """Stop all audio playback. + """crwdns329992:0crwdne329992:0 (crwdns329990:0crwdne329990:0) - Example: ``audio.stop()`` - """ +Example: ``audio.stop()``""" ... class SoundEffect: - """A sound effect, composed by a set of parameters configured via the constructor or attributes.""" - + """crwdns335840:0crwdne335840:0 (crwdns335838:0crwdne335838:0)""" WAVEFORM_SINE: ClassVar[int] - """Sine wave option used for the ``waveform`` parameter.""" - + """crwdns335844:0``waveform``crwdne335844:0 (crwdns335842:0crwdne335842:0)""" WAVEFORM_SAWTOOTH: ClassVar[int] - """Sawtooth wave option used for the ``waveform`` parameter.""" - + """crwdns335848:0``waveform``crwdne335848:0 (crwdns335846:0crwdne335846:0)""" WAVEFORM_TRIANGLE: ClassVar[int] - """Triangle wave option used for the ``waveform`` parameter.""" - + """crwdns335852:0``waveform``crwdne335852:0 (crwdns335850:0crwdne335850:0)""" WAVEFORM_SQUARE: ClassVar[int] - """Square wave option used for the ``waveform`` parameter.""" - + """crwdns335856:0``waveform``crwdne335856:0 (crwdns335854:0crwdne335854:0)""" WAVEFORM_NOISE: ClassVar[int] - """Noise option used for the ``waveform`` parameter.""" - + """crwdns335860:0``waveform``crwdne335860:0 (crwdns335858:0crwdne335858:0)""" SHAPE_LINEAR: ClassVar[int] - """Linear interpolation option used for the ``shape`` parameter.""" - + """crwdns335864:0``shape``crwdne335864:0 (crwdns335862:0crwdne335862:0)""" SHAPE_CURVE: ClassVar[int] - """Curve interpolation option used for the ``shape`` parameter.""" - + """crwdns335868:0``shape``crwdne335868:0 (crwdns335866:0crwdne335866:0)""" SHAPE_LOG: ClassVar[int] - """Logarithmic interpolation option used for the ``shape`` parameter.""" - + """crwdns335872:0``shape``crwdne335872:0 (crwdns335870:0crwdne335870:0)""" FX_NONE: ClassVar[int] - """No effect option used for the ``fx`` parameter.""" - + """crwdns335876:0``fx``crwdne335876:0 (crwdns335874:0crwdne335874:0)""" FX_TREMOLO: ClassVar[int] - """Tremolo effect option used for the ``fx`` parameter.""" - + """crwdns335880:0``fx``crwdne335880:0 (crwdns335878:0crwdne335878:0)""" FX_VIBRATO: ClassVar[int] - """Vibrato effect option used for the ``fx`` parameter.""" - + """crwdns335884:0``fx``crwdne335884:0 (crwdns335882:0crwdne335882:0)""" FX_WARBLE: ClassVar[int] - """Warble effect option used for the ``fx`` parameter.""" - + """crwdns335888:0``fx``crwdne335888:0 (crwdns335886:0crwdne335886:0)""" freq_start: int - """Start frequency in Hertz (Hz), a number between ``0`` and ``9999``""" - + """crwdns335892:0``0``crwdnd335892:0``9999``crwdne335892:0 (crwdns335890:0crwdne335890:0)""" freq_end: int - """End frequency in Hertz (Hz), a number between ``0`` and ``9999``""" - + """crwdns335896:0``0``crwdnd335896:0``9999``crwdne335896:0 (crwdns335894:0crwdne335894:0)""" duration: int - """Duration of the sound in milliseconds, a number between ``0`` and ``9999``""" - + """crwdns335900:0``0``crwdnd335900:0``9999``crwdne335900:0 (crwdns335898:0crwdne335898:0)""" vol_start: int - """Start volume value, a number between ``0`` and ``255``""" - + """crwdns335904:0``0``crwdnd335904:0``255``crwdne335904:0 (crwdns335902:0crwdne335902:0)""" vol_end: int - """End volume value, a number between ``0`` and ``255``""" - + """crwdns335908:0``0``crwdnd335908:0``255``crwdne335908:0 (crwdns335906:0crwdne335906:0)""" waveform: int - """Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise)""" - + """crwdns335912:0``WAVEFORM_SINE``crwdnd335912:0``WAVEFORM_SAWTOOTH``crwdnd335912:0``WAVEFORM_TRIANGLE``crwdnd335912:0``WAVEFORM_SQUARE``crwdnd335912:0``WAVEFORM_NOISE``crwdne335912:0 (crwdns335910:0crwdne335910:0)""" fx: int - """Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``""" - + """crwdns335916:0``FX_TREMOLO``crwdnd335916:0``FX_VIBRATO``crwdnd335916:0``FX_WARBLE``crwdnd335916:0``FX_NONE``crwdne335916:0 (crwdns335914:0crwdne335914:0)""" shape: int - """The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``""" - - def __init__( - self, - freq_start: int = 500, - freq_end: int = 2500, - duration: int = 500, - vol_start: int = 255, - vol_end: int = 0, - waveform: int = WAVEFORM_SQUARE, - fx: int = FX_NONE, - shape: int = SHAPE_LOG, - ): - """Create a new sound effect. - - Example: ``my_effect = SoundEffect(duration=1000)`` - - All the parameters are optional, with default values as shown above, and - they can all be modified via attributes of the same name. For example, we - can first create an effect ``my_effect = SoundEffect(duration=1000)``, - and then change its attributes ``my_effect.duration = 500``. - - :param freq_start: Start frequency in Hertz (Hz), a number between ``0`` and ``9999``. - :param freq_end: End frequency in Hertz (Hz), a number between ``0`` and ``9999``. - :param duration: Duration of the sound in milliseconds, a number between ``0`` and ``9999``. - :param vol_start: Start volume value, a number between ``0`` and ``255``. - :param vol_end: End volume value, a number between ``0`` and ``255``. - :param waveform: Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise). - :param fx: Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``. - :param shape: The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``. - """ + """crwdns335920:0``SHAPE_LINEAR``crwdnd335920:0``SHAPE_CURVE``crwdnd335920:0``SHAPE_LOG``crwdne335920:0 (crwdns335918:0crwdne335918:0)""" + + def __init__(self, freq_start: int=500, freq_end: int=2500, duration: int=500, vol_start: int=255, vol_end: int=0, waveform: int=WAVEFORM_SQUARE, fx: int=FX_NONE, shape: int=SHAPE_LOG): + """crwdns335924:0crwdne335924:0 (crwdns335922:0crwdne335922:0) + +Example: ``my_effect = SoundEffect(duration=1000)`` + +All the parameters are optional, with default values as shown above, and +they can all be modified via attributes of the same name. For example, we +can first create an effect ``my_effect = SoundEffect(duration=1000)``, +and then change its attributes ``my_effect.duration = 500``. + +:param freq_start: (crwdns335934:0crwdne335934:0) crwdns335936:0``0``crwdnd335936:0``9999``crwdne335936:0 +:param freq_end: (crwdns335930:0crwdne335930:0) crwdns335932:0``0``crwdnd335932:0``9999``crwdne335932:0 +:param duration: (crwdns335926:0crwdne335926:0) crwdns335928:0``0``crwdnd335928:0``9999``crwdne335928:0 +:param vol_start: (crwdns335950:0crwdne335950:0) crwdns335952:0``0``crwdnd335952:0``255``crwdne335952:0 +:param vol_end: (crwdns335946:0crwdne335946:0) crwdns335948:0``0``crwdnd335948:0``255``crwdne335948:0 +:param waveform: (crwdns335954:0crwdne335954:0) crwdns335956:0``WAVEFORM_SINE``crwdnd335956:0``WAVEFORM_SAWTOOTH``crwdnd335956:0``WAVEFORM_TRIANGLE``crwdnd335956:0``WAVEFORM_SQUARE``crwdnd335956:0``WAVEFORM_NOISE``crwdne335956:0 +:param fx: (crwdns335938:0crwdne335938:0) crwdns335940:0``FX_TREMOLO``crwdnd335940:0``FX_VIBRATO``crwdnd335940:0``FX_WARBLE``crwdnd335940:0``FX_NONE``crwdne335940:0 +:param shape: (crwdns335942:0crwdne335942:0) crwdns335944:0``SHAPE_LINEAR``crwdnd335944:0``SHAPE_CURVE``crwdnd335944:0``SHAPE_LOG``crwdne335944:0""" + def copy(self) -> SoundEffect: - """Create a copy of this ``SoundEffect``. + """crwdns335960:0``SoundEffect``crwdne335960:0 (crwdns335958:0crwdne335958:0) - Example: ``sound_2 = sound_1.copy()`` +Example: ``sound_2 = sound_1.copy()`` - :return: A copy of the SoundEffect. - """ +:return: A copy of the SoundEffect.""" class AudioFrame: - """An ``AudioFrame`` object is a list of 32 samples each of which is a unsigned byte - (whole number between 0 and 255). + """crwdns329996:0``AudioFrame``crwdne329996:0 (crwdns329994:0crwdne329994:0) - It takes just over 4 ms to play a single frame. +It takes just over 4 ms to play a single frame. - Example:: +Example:: - frame = AudioFrame() - for i in range(len(frame)): - frame[i] = 252 - i * 8 - """ + frame = AudioFrame() + for i in range(len(frame)): + frame[i] = 252 - i * 8""" def copyfrom(self, other: AudioFrame) -> None: - """Overwrite the data in this ``AudioFrame`` with the data from another ``AudioFrame`` instance. + """crwdns335964:0``AudioFrame``crwdnd335964:0``AudioFrame``crwdne335964:0 (crwdns335962:0crwdne335962:0) + +Example: ``my_frame.copyfrom(source_frame)`` + +:param other: (crwdns335966:0crwdne335966:0) crwdns335968:0``AudioFrame``crwdne335968:0""" + + def __len__(self) -> int: + ... - Example: ``my_frame.copyfrom(source_frame)`` + def __setitem__(self, key: int, value: int) -> None: + ... - :param other: ``AudioFrame`` instance from which to copy the data. - """ - def __len__(self) -> int: ... - def __setitem__(self, key: int, value: int) -> None: ... - def __getitem__(self, key: int) -> int: ... + def __getitem__(self, key: int) -> int: + ... \ No newline at end of file diff --git a/lang/lol/typeshed/stdlib/microbit/compass.pyi b/lang/lol/typeshed/stdlib/microbit/compass.pyi index c74a47b..38bf5a4 100644 --- a/lang/lol/typeshed/stdlib/microbit/compass.pyi +++ b/lang/lol/typeshed/stdlib/microbit/compass.pyi @@ -1,78 +1,70 @@ -"""Use the built-in compass. -""" +"""crwdns330004:0crwdne330004:0 (crwdns330002:0crwdne330002:0)""" def calibrate() -> None: - """Starts the calibration process. + """crwdns330008:0crwdne330008:0 (crwdns330006:0crwdne330006:0) - Example: ``compass.calibrate()`` +Example: ``compass.calibrate()`` - 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. - """ +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: - """Check is the compass is calibrated. + """crwdns330012:0crwdne330012:0 (crwdns330010:0crwdne330010:0) - Example: ``compass.is_calibrated()`` +Example: ``compass.is_calibrated()`` - :return: ``True`` if the compass has been successfully calibrated, ``False`` otherwise. - """ +:return: ``True`` if the compass has been successfully calibrated, ``False`` otherwise.""" ... def clear_calibration() -> None: - """Undoes the calibration, making the compass uncalibrated again. + """crwdns330016:0crwdne330016:0 (crwdns330014:0crwdne330014:0) - Example: ``compass.clear_calibration()`` - """ +Example: ``compass.clear_calibration()``""" ... def get_x() -> int: - """Get the magnetic field strength on the ``x`` axis. + """crwdns330020:0``x``crwdne330020:0 (crwdns330018:0crwdne330018:0) - Example: ``compass.get_x()`` +Example: ``compass.get_x()`` - Call ``calibrate`` first or the results will be inaccurate. +Call ``calibrate`` first or the results will be inaccurate. - :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. - """ +:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" ... def get_y() -> int: - """Get the magnetic field strength on the ``y`` axis. + """crwdns330024:0``y``crwdne330024:0 (crwdns330022:0crwdne330022:0) - Example: ``compass.get_y()`` +Example: ``compass.get_y()`` - Call ``calibrate`` first or the results will be inaccurate. +Call ``calibrate`` first or the results will be inaccurate. - :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. - """ +:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" ... def get_z() -> int: - """Get the magnetic field strength on the ``z`` axis. + """crwdns330028:0``z``crwdne330028:0 (crwdns330026:0crwdne330026:0) - Example: ``compass.get_z()`` +Example: ``compass.get_z()`` - Call ``calibrate`` first or the results will be inaccurate. +Call ``calibrate`` first or the results will be inaccurate. - :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. - """ +:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" ... def heading() -> int: - """Get the compass heading. + """crwdns330032:0crwdne330032:0 (crwdns330030:0crwdne330030:0) - Example: ``compass.heading()`` +Example: ``compass.heading()`` - :return: An integer in the range from 0 to 360, representing the angle in degrees, clockwise, with north as 0. - """ +:return: An integer in the range from 0 to 360, representing the angle in degrees, clockwise, with north as 0.""" ... def get_field_strength() -> int: - """Get the magnitude of the magnetic field around the device. + """crwdns330036:0crwdne330036:0 (crwdns330034:0crwdne330034:0) - Example: ``compass.get_field_strength()`` +Example: ``compass.get_field_strength()`` - :return: An integer indication of the magnitude of the magnetic field in nano tesla.""" - ... +:return: An integer indication of the magnitude of the magnetic field in nano tesla.""" + ... \ No newline at end of file diff --git a/lang/lol/typeshed/stdlib/microbit/display.pyi b/lang/lol/typeshed/stdlib/microbit/display.pyi index aa4013e..cf2dd2e 100644 --- a/lang/lol/typeshed/stdlib/microbit/display.pyi +++ b/lang/lol/typeshed/stdlib/microbit/display.pyi @@ -1,115 +1,92 @@ -"""Show text, images and animations on the 5×5 LED display. -""" - +"""crwdns330040:0crwdne330040:0 (crwdns330038:0crwdne330038:0)""" from ..microbit import Image from typing import Union, overload, Iterable def get_pixel(x: int, y: int) -> int: - """Get the brightness of the LED at column ``x`` and row ``y``. + """crwdns330044:0``x``crwdnd330044:0``y``crwdne330044:0 (crwdns330042:0crwdne330042:0) - Example: ``display.get_pixel(0, 0)`` +Example: ``display.get_pixel(0, 0)`` - :param x: The display column (0..4) - :param y: The display row (0..4) - :return: A number between 0 (off) and 9 (bright) - """ +:param x: (crwdns330046:0crwdne330046:0) crwdns330048:0crwdne330048:0 +:param y: (crwdns330050:0crwdne330050:0) crwdns330052:0crwdne330052:0 +:return: A number 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``. + """crwdns330056:0``x``crwdnd330056:0``y``crwdne330056:0 (crwdns330054:0crwdne330054:0) - Example: ``display.set_pixel(0, 0, 9)`` +Example: ``display.set_pixel(0, 0, 9)`` - :param x: The display column (0..4) - :param y: The display row (0..4) - :param value: The brightness between 0 (off) and 9 (bright) - """ +:param x: (crwdns330062:0crwdne330062:0) crwdns330064:0crwdne330064:0 +:param y: (crwdns330066:0crwdne330066:0) crwdns330068:0crwdne330068:0 +:param value: (crwdns330058:0crwdne330058:0) crwdns330060:0crwdne330060:0""" ... def clear() -> None: - """Set the brightness of all LEDs to 0 (off). + """crwdns330072:0crwdne330072:0 (crwdns330070:0crwdne330070:0) - Example: ``display.clear()`` - """ +Example: ``display.clear()``""" ... -def show( - image: Union[str, float, int, Image, Iterable[Image]], - delay: int = 400, - wait: bool = True, - loop: bool = False, - clear: bool = False, -) -> None: - """Shows images, letters or digits on the LED display. +def show(image: Union[str, float, int, Image, Iterable[Image]], delay: int=400, wait: bool=True, loop: bool=False, clear: bool=False) -> None: + """crwdns330076:0crwdne330076:0 (crwdns330074:0crwdne330074:0) - Example: ``display.show(Image.HEART)`` +Example: ``display.show(Image.HEART)`` - When ``image`` is an image or a list of images then each image is displayed in turn. - If ``image`` is a string or number, each letter or digit is displayed in turn. +When ``image`` is an image or a list of images then each image is displayed in turn. +If ``image`` is a string or number, each letter or digit is displayed in turn. - :param image: A string, number, image or list of images to show. - :param delay: Each letter, digit or image is shown with ``delay`` milliseconds between them. - :param wait: If ``wait`` is ``True``, this function will block until the animation is finished, otherwise the animation will happen in the background. - :param loop: If ``loop`` is ``True``, the animation will repeat forever. - :param clear: If ``clear`` is ``True``, the display will be cleared after the sequence has finished. +:param image: (crwdns330086:0crwdne330086:0) crwdns330088:0crwdne330088:0 +:param delay: (crwdns330082:0crwdne330082:0) crwdns330084:0``delay``crwdne330084:0 +:param wait: (crwdns330094:0crwdne330094:0) crwdns330096:0``wait``crwdnd330096:0``True``crwdne330096:0 +:param loop: (crwdns330090:0crwdne330090:0) crwdns330092:0``loop``crwdnd330092:0``True``crwdne330092:0 +:param clear: (crwdns330078:0crwdne330078:0) crwdns330080:0``clear``crwdnd330080:0``True``crwdne330080:0 - The ``wait``, ``loop`` and ``clear`` arguments must be specified using their keyword. - """ +The ``wait``, ``loop`` and ``clear`` arguments must be specified using their keyword.""" ... -def scroll( - text: Union[str, float, int], - delay: int = 150, - wait: bool = True, - loop: bool = False, - monospace: bool = False, -) -> None: - """Scrolls a number or text on the LED display. - - Example: ``display.scroll('micro:bit')`` - - :param text: The string to scroll. If ``text`` is an integer or float it is first converted to a string using ``str()``. - :param delay: The ``delay`` parameter controls how fast the text is scrolling. - :param wait: If ``wait`` is ``True``, this function will block until the animation is finished, otherwise the animation will happen in the background. - :param loop: If ``loop`` is ``True``, the animation will repeat forever. - :param monospace: 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. - - The ``wait``, ``loop`` and ``monospace`` arguments must be specified - using their keyword. - """ +def scroll(text: Union[str, float, int], delay: int=150, wait: bool=True, loop: bool=False, monospace: bool=False) -> None: + """crwdns330100:0crwdne330100:0 (crwdns330098:0crwdne330098:0) + +Example: ``display.scroll('micro:bit')`` + +:param text: (crwdns330114:0crwdne330114:0) crwdns330116:0``text``crwdnd330116:0``str()``crwdne330116:0 +:param delay: (crwdns330102:0crwdne330102:0) crwdns330104:0``delay``crwdne330104:0 +:param wait: (crwdns330118:0crwdne330118:0) crwdns330120:0``wait``crwdnd330120:0``True``crwdne330120:0 +:param loop: (crwdns330106:0crwdne330106:0) crwdns330108:0``loop``crwdnd330108:0``True``crwdne330108:0 +:param monospace: (crwdns330110:0crwdne330110:0) crwdns330112:0``monospace``crwdnd330112:0``True``crwdne330112:0 + +The ``wait``, ``loop`` and ``monospace`` arguments must be specified +using their keyword.""" ... def on() -> None: - """Turn on the LED display. + """crwdns330124:0crwdne330124:0 (crwdns330122:0crwdne330122:0) - Example: ``display.on()`` - """ +Example: ``display.on()``""" ... def off() -> None: - """Turn off the LED display (disabling the display allows you to re-use the GPIO pins for other purposes). + """crwdns330128:0crwdne330128:0 (crwdns330126:0crwdne330126:0) - Example: ``display.off()`` - """ +Example: ``display.off()``""" ... def is_on() -> bool: - """Check whether the LED display is enabled. + """crwdns330132:0crwdne330132:0 (crwdns330130:0crwdne330130:0) - Example: ``display.is_on()`` +Example: ``display.is_on()`` - :return: ``True`` if the display is on, otherwise returns ``False``. - """ +:return: ``True`` if the display is on, otherwise returns ``False``.""" ... def read_light_level() -> int: - """Read the light level. + """crwdns330136:0crwdne330136:0 (crwdns330134:0crwdne330134:0) - Example: ``display.read_light_level()`` +Example: ``display.read_light_level()`` - Uses the display's LEDs in reverse-bias mode to sense the amount of light - falling on the display. +Uses the display's LEDs in reverse-bias mode to sense the amount of light +falling on the display. - :return: An integer between 0 and 255 representing the light level, with larger meaning more light. - """ - ... +:return: An integer between 0 and 255 representing the light level, with larger meaning more light.""" + ... \ No newline at end of file diff --git a/lang/lol/typeshed/stdlib/microbit/i2c.pyi b/lang/lol/typeshed/stdlib/microbit/i2c.pyi index df26efa..c126204 100644 --- a/lang/lol/typeshed/stdlib/microbit/i2c.pyi +++ b/lang/lol/typeshed/stdlib/microbit/i2c.pyi @@ -1,57 +1,49 @@ -"""Communicate with devices using the I²C bus protocol. -""" - +"""crwdns330140:0crwdne330140:0 (crwdns330138:0crwdne330138:0)""" from _typeshed import ReadableBuffer from ..microbit import MicroBitDigitalPin, pin19, pin20 from typing import List -def init( - freq: int = 100000, sda: MicroBitDigitalPin = pin20, scl: MicroBitDigitalPin = pin19 -) -> None: - """Re-initialize a peripheral. +def init(freq: int=100000, sda: MicroBitDigitalPin=pin20, scl: MicroBitDigitalPin=pin19) -> None: + """crwdns330144:0crwdne330144:0 (crwdns330142:0crwdne330142:0) - Example: ``i2c.init()`` +Example: ``i2c.init()`` - :param freq: clock frequency - :param sda: ``sda`` pin (default 20) - :param scl: ``scl`` pin (default 19) +:param freq: (crwdns330146:0crwdne330146:0) crwdns330148:0crwdne330148:0 +:param sda: (crwdns330154:0crwdne330154:0) crwdns330156:0``sda``crwdne330156:0 +:param scl: (crwdns330150:0crwdne330150:0) crwdns330152:0``scl``crwdne330152:0 - On a micro:bit V1 board, changing the I²C pins from defaults will make - the accelerometer and compass stop working, as they are connected - internally to those pins. This warning does not apply to the **V2** - revision of the micro:bit as this has `separate I²C lines `_ - for the motion sensors and the edge connector. - """ +On a micro:bit V1 board, changing the I²C pins from defaults will make +the accelerometer and compass stop working, as they are connected +internally to those pins. This warning does not apply to the **V2** +revision of the micro:bit as this has `separate I²C lines `_ +for the motion sensors and the edge connector.""" ... def scan() -> List[int]: - """Scan the bus for devices. + """crwdns330160:0crwdne330160:0 (crwdns330158:0crwdne330158:0) - Example: ``i2c.scan()`` +Example: ``i2c.scan()`` - :return: A list of 7-bit addresses corresponding to those devices that responded to the scan. - """ +:return: A list of 7-bit addresses corresponding to those devices that responded to the scan.""" ... -def read(addr: int, n: int, repeat: bool = False) -> bytes: - """Read bytes from a device. +def read(addr: int, n: int, repeat: bool=False) -> bytes: + """crwdns330164:0crwdne330164:0 (crwdns330162:0crwdne330162:0) - Example: ``i2c.read(0x50, 64)`` +Example: ``i2c.read(0x50, 64)`` - :param addr: The 7-bit address of the device - :param n: The number of bytes to read - :param repeat: If ``True``, no stop bit will be sent - :return: The bytes read - """ +:param addr: (crwdns330166:0crwdne330166:0) crwdns330168:0crwdne330168:0 +:param n: (crwdns330170:0crwdne330170:0) crwdns330172:0crwdne330172:0 +:param repeat: (crwdns330174:0crwdne330174:0) crwdns330176:0``True``crwdne330176:0 +:return: The bytes read""" ... -def write(addr: int, buf: ReadableBuffer, repeat: bool = False) -> None: - """Write bytes to a device. +def write(addr: int, buf: ReadableBuffer, repeat: bool=False) -> None: + """crwdns330180:0crwdne330180:0 (crwdns330178:0crwdne330178:0) - Example: ``i2c.write(0x50, bytes([1, 2, 3]))`` +Example: ``i2c.write(0x50, bytes([1, 2, 3]))`` - :param addr: The 7-bit address of the device - :param buf: A buffer containing the bytes to write - :param repeat: If ``True``, no stop bit will be sent - """ - ... +:param addr: (crwdns330182:0crwdne330182:0) crwdns330184:0crwdne330184:0 +:param buf: (crwdns330186:0crwdne330186:0) crwdns330188:0crwdne330188:0 +:param repeat: (crwdns330190:0crwdne330190:0) crwdns330192:0``True``crwdne330192:0""" + ... \ No newline at end of file diff --git a/lang/lol/typeshed/stdlib/microbit/microphone.pyi b/lang/lol/typeshed/stdlib/microbit/microphone.pyi index 68e8f3a..bc5d3a3 100644 --- a/lang/lol/typeshed/stdlib/microbit/microphone.pyi +++ b/lang/lol/typeshed/stdlib/microbit/microphone.pyi @@ -1,70 +1,62 @@ -"""Respond to sound using the built-in microphone (V2 only). -""" - +"""crwdns330196:0crwdne330196:0 (crwdns330194:0crwdne330194:0)""" from typing import Optional, Tuple from ..microbit import SoundEvent def current_event() -> Optional[SoundEvent]: - """Get the last recorded sound event + """crwdns330200:0crwdne330200:0 (crwdns330198:0crwdne330198:0) - Example: ``microphone.current_event()`` +Example: ``microphone.current_event()`` - :return: The event, ``SoundEvent('loud')`` or ``SoundEvent('quiet')``. - """ +:return: The event, ``SoundEvent('loud')`` or ``SoundEvent('quiet')``.""" ... def was_event(event: SoundEvent) -> bool: - """Check if a sound was heard at least once since the last call. + """crwdns330204:0crwdne330204:0 (crwdns330202:0crwdne330202:0) - Example: ``microphone.was_event(SoundEvent.LOUD)`` +Example: ``microphone.was_event(SoundEvent.LOUD)`` - This call clears the sound history before returning. +This call clears the sound history before returning. - :param event: The event to check for, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET`` - :return: ``True`` if sound was heard at least once since the last call, otherwise ``False``. - """ +:param event: (crwdns330206:0crwdne330206:0) crwdns330208:0``SoundEvent.LOUD``crwdnd330208:0``SoundEvent.QUIET``crwdne330208:0 +:return: ``True`` if sound was heard at least once since the last call, otherwise ``False``.""" ... def is_event(event: SoundEvent) -> bool: - """Check the most recent sound event detected. + """crwdns330212:0crwdne330212:0 (crwdns330210:0crwdne330210:0) - Example: ``microphone.is_event(SoundEvent.LOUD)`` +Example: ``microphone.is_event(SoundEvent.LOUD)`` - This call does not clear the sound event history. +This call does not clear the sound event history. - :param event: The event to check for, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET`` - :return: ``True`` if sound was the most recent heard, ``False`` otherwise. - """ +:param event: (crwdns330214:0crwdne330214:0) crwdns330216:0``SoundEvent.LOUD``crwdnd330216:0``SoundEvent.QUIET``crwdne330216:0 +:return: ``True`` if sound was the most recent heard, ``False`` otherwise.""" ... def get_events() -> Tuple[SoundEvent, ...]: - """Get the sound event history as a tuple. + """crwdns330220:0crwdne330220:0 (crwdns330218:0crwdne330218:0) - Example: ``microphone.get_events()`` +Example: ``microphone.get_events()`` - This call clears the sound history before returning. +This call clears the sound history before returning. - :return: A tuple of the event history with the most recent event last. - """ +:return: A tuple of the event history with the most recent event last.""" ... def set_threshold(event: SoundEvent, value: int) -> None: - """Set the threshold for a sound event. + """crwdns330224:0crwdne330224:0 (crwdns330222:0crwdne330222:0) - Example: ``microphone.set_threshold(SoundEvent.LOUD, 250)`` +Example: ``microphone.set_threshold(SoundEvent.LOUD, 250)`` - A high threshold means the event will only trigger if the sound is very loud (>= 250 in the example). +A high threshold means the event will only trigger if the sound is very loud (>= 250 in the example). - :param event: A sound event, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET``. - :param value: The threshold level in the range 0-255. - """ +:param event: (crwdns330226:0crwdne330226:0) crwdns330228:0``SoundEvent.LOUD``crwdnd330228:0``SoundEvent.QUIET``crwdne330228:0 +:param value: (crwdns330230:0crwdne330230:0) crwdns330232:0crwdne330232:0""" ... def sound_level() -> int: - """Get the sound pressure level. + """crwdns330236:0crwdne330236:0 (crwdns330234:0crwdne330234:0) - Example: ``microphone.sound_level()`` +Example: ``microphone.sound_level()`` - :return: A representation of the sound pressure level in the range 0 to 255. - """ - ... +:return: A representation of the sound pressure level in the range 0 to 255.""" + ... \ No newline at end of file diff --git a/lang/lol/typeshed/stdlib/microbit/speaker.pyi b/lang/lol/typeshed/stdlib/microbit/speaker.pyi index 5a74a4d..b5c339e 100644 --- a/lang/lol/typeshed/stdlib/microbit/speaker.pyi +++ b/lang/lol/typeshed/stdlib/microbit/speaker.pyi @@ -1,18 +1,15 @@ -"""Control the built-in speaker (V2 only). -""" +"""crwdns330240:0crwdne330240:0 (crwdns330238:0crwdne330238:0)""" def off() -> None: - """Turn the speaker off. + """crwdns330244:0crwdne330244:0 (crwdns330242:0crwdne330242:0) - Example: ``speaker.off()`` +Example: ``speaker.off()`` - This does not disable sound output to an edge connector pin. - """ +This does not disable sound output to an edge connector pin.""" ... def on() -> None: - """Turn the speaker on. + """crwdns330248:0crwdne330248:0 (crwdns330246:0crwdne330246:0) - Example: ``speaker.on()`` - """ - ... +Example: ``speaker.on()``""" + ... \ No newline at end of file diff --git a/lang/lol/typeshed/stdlib/microbit/spi.pyi b/lang/lol/typeshed/stdlib/microbit/spi.pyi index 09c4046..d68ba4f 100644 --- a/lang/lol/typeshed/stdlib/microbit/spi.pyi +++ b/lang/lol/typeshed/stdlib/microbit/spi.pyi @@ -1,60 +1,47 @@ -"""Communicate with devices using the serial peripheral interface (SPI) bus. -""" - +"""crwdns330252:0crwdne330252:0 (crwdns330250:0crwdne330250:0)""" from _typeshed import ReadableBuffer, WriteableBuffer from ..microbit import pin13, pin14, pin15, MicroBitDigitalPin -def init( - baudrate: int = 1000000, - bits: int = 8, - mode: int = 0, - sclk: MicroBitDigitalPin = pin13, - mosi: MicroBitDigitalPin = pin15, - miso: MicroBitDigitalPin = pin14, -) -> None: - """Initialize SPI communication. - - Example: ``spi.init()`` - - For correct communication, the parameters have to be the same on both communicating devices. - - :param baudrate: The speed of communication. - :param bits: The width in bits of each transfer. Currently only ``bits=8`` is supported. However, this may change in the future. - :param mode: Determines the combination of clock polarity and phase - `see online table `_. - :param sclk: sclk pin (default 13) - :param mosi: mosi pin (default 15) - :param miso: miso pin (default 14) - """ +def init(baudrate: int=1000000, bits: int=8, mode: int=0, sclk: MicroBitDigitalPin=pin13, mosi: MicroBitDigitalPin=pin15, miso: MicroBitDigitalPin=pin14) -> None: + """crwdns330256:0crwdne330256:0 (crwdns330254:0crwdne330254:0) + +Example: ``spi.init()`` + +For correct communication, the parameters have to be the same on both communicating devices. + +:param baudrate: (crwdns330258:0crwdne330258:0) crwdns330260:0crwdne330260:0 +:param bits: (crwdns330262:0crwdne330262:0) crwdns334412:0crwdne334412:0 +:param mode: (crwdns330270:0crwdne330270:0) crwdns330272:0crwdne330272:0 +:param sclk: (crwdns330278:0crwdne330278:0) crwdns330280:0crwdne330280:0 +:param mosi: (crwdns330274:0crwdne330274:0) crwdns330276:0crwdne330276:0 +:param miso: (crwdns330266:0crwdne330266:0) crwdns330268:0crwdne330268:0""" ... -def read(nbytes: int, out: int = 0) -> bytes: - """Read at most ``nbytes`` while continuously writing the single byte given by ``out``. +def read(nbytes: int, out: int=0) -> bytes: + """crwdns330284:0``nbytes``crwdnd330284:0``out``crwdne330284:0 (crwdns330282:0crwdne330282:0) - Example: ``spi.read(64)`` +Example: ``spi.read(64)`` - :param nbytes: Maximum number of bytes to read. - :param out: The byte value to write (default 0). - :return: The bytes read. - """ +:param nbytes: (crwdns330286:0crwdne330286:0) crwdns330288:0crwdne330288:0 +:param out: (crwdns360362:0crwdne360362:0) crwdns360364:0crwdne360364:0 +:return: The bytes read.""" ... def write(buffer: ReadableBuffer) -> None: - """Write bytes to the bus. + """crwdns330292:0crwdne330292:0 (crwdns330290:0crwdne330290:0) - Example: ``spi.write(bytes([1, 2, 3]))`` +Example: ``spi.write(bytes([1, 2, 3]))`` - :param buffer: A buffer to read data from. - """ +:param buffer: (crwdns330294:0crwdne330294:0) crwdns330296:0crwdne330296:0""" ... def write_readinto(out: WriteableBuffer, in_: ReadableBuffer) -> None: - """Write the ``out`` buffer to the bus and read any response into the ``in_`` buffer. + """crwdns330300:0``out``crwdnd330300:0``in_``crwdne330300:0 (crwdns330298:0crwdne330298:0) - Example: ``spi.write_readinto(out_buffer, in_buffer)`` +Example: ``spi.write_readinto(out_buffer, in_buffer)`` - The length of the buffers should be the same. The buffers can be the same object. +The length of the buffers should be the same. The buffers can be the same object. - :param out: The buffer to write any response to. - :param in_: The buffer to read data from. - """ - ... +:param out: (crwdns330306:0crwdne330306:0) crwdns330308:0crwdne330308:0 +:param in_: (crwdns330302:0crwdne330302:0) crwdns330304:0crwdne330304:0""" + ... \ No newline at end of file diff --git a/lang/lol/typeshed/stdlib/microbit/uart.pyi b/lang/lol/typeshed/stdlib/microbit/uart.pyi index 2ab650f..3f791aa 100644 --- a/lang/lol/typeshed/stdlib/microbit/uart.pyi +++ b/lang/lol/typeshed/stdlib/microbit/uart.pyi @@ -1,96 +1,79 @@ -"""Communicate with a device using a serial interface. -""" - +"""crwdns330312:0crwdne330312:0 (crwdns330310:0crwdne330310:0)""" from _typeshed import WriteableBuffer from ..microbit import MicroBitDigitalPin from typing import Optional, Union - ODD: int -"""Odd parity""" - +"""crwdns330316:0crwdne330316:0 (crwdns330314:0crwdne330314:0)""" EVEN: int -"""Even parity""" - -def init( - baudrate: int = 9600, - bits: int = 8, - parity: Optional[int] = None, - stop: int = 1, - tx: Optional[MicroBitDigitalPin] = None, - rx: Optional[MicroBitDigitalPin] = None, -) -> None: - """Initialize serial communication. - - Example: ``uart.init(115200, tx=pin0, rx=pin1)`` - - :param baudrate: The speed of communication. - :param bits: The size of bytes being transmitted. micro:bit only supports 8. - :param parity: How parity is checked, ``None``, ``uart.ODD`` or ``uart.EVEN``. - :param stop: The number of stop bits, has to be 1 for micro:bit. - :param tx: Transmitting pin. - :param rx: Receiving pin. - - 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. - - For more details see `the online documentation `_. - """ +"""crwdns330320:0crwdne330320:0 (crwdns330318:0crwdne330318:0)""" + +def init(baudrate: int=9600, bits: int=8, parity: Optional[int]=None, stop: int=1, tx: Optional[MicroBitDigitalPin]=None, rx: Optional[MicroBitDigitalPin]=None) -> None: + """crwdns330324:0crwdne330324:0 (crwdns330322:0crwdne330322:0) + +Example: ``uart.init(115200, tx=pin0, rx=pin1)`` + +:param baudrate: (crwdns330326:0crwdne330326:0) crwdns330328:0crwdne330328:0 +:param bits: (crwdns330330:0crwdne330330:0) crwdns330332:0crwdne330332:0 +:param parity: (crwdns330334:0crwdne330334:0) crwdns330336:0``None``crwdnd330336:0``uart.ODD``crwdnd330336:0``uart.EVEN``crwdne330336:0 +:param stop: (crwdns330342:0crwdne330342:0) crwdns330344:0crwdne330344:0 +:param tx: (crwdns330346:0crwdne330346:0) crwdns330348:0crwdne330348:0 +:param rx: (crwdns330338:0crwdne330338:0) crwdns330340:0crwdne330340:0 + +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. + +For more details see `the online documentation `_.""" ... def any() -> bool: - """Check if any data is waiting. + """crwdns334688:0crwdne334688:0 (crwdns330350:0crwdne330350:0) - Example: ``uart.any()`` +Example: ``uart.any()`` - :return: ``True`` if any data is waiting, else ``False``. - """ +:return: ``True`` if any data is waiting, else ``False``.""" ... -def read(nbytes: Optional[int] = None) -> Optional[bytes]: - """Read bytes. +def read(nbytes: Optional[int]=None) -> Optional[bytes]: + """crwdns330356:0crwdne330356:0 (crwdns330354:0crwdne330354:0) - Example: ``uart.read()`` +Example: ``uart.read()`` - :param nbytes: If ``nbytes`` is specified then read at most that many bytes, otherwise read as many bytes as possible - :return: A bytes object or ``None`` on timeout - """ +:param nbytes: (crwdns330358:0crwdne330358:0) crwdns330360:0``nbytes``crwdne330360:0 +:return: A bytes object or ``None`` on timeout""" ... -def readinto(buf: WriteableBuffer, nbytes: Optional[int] = None) -> Optional[int]: - """Read bytes into the ``buf``. +def readinto(buf: WriteableBuffer, nbytes: Optional[int]=None) -> Optional[int]: + """crwdns330364:0``buf``crwdne330364:0 (crwdns330362:0crwdne330362:0) - Example: ``uart.readinto(input_buffer)`` +Example: ``uart.readinto(input_buffer)`` - :param buf: The buffer to write to. - :param nbytes: If ``nbytes`` is specified then read at most that many bytes, otherwise read ``len(buf)`` bytes. - :return: number of bytes read and stored into ``buf`` or ``None`` on timeout. - """ +:param buf: (crwdns330366:0crwdne330366:0) crwdns330368:0crwdne330368:0 +:param nbytes: (crwdns330370:0crwdne330370:0) crwdns330372:0``nbytes``crwdnd330372:0``len(buf)``crwdne330372:0 +:return: number of bytes read and stored into ``buf`` or ``None`` on timeout.""" ... def readline() -> Optional[bytes]: - """Read a line, ending in a newline character. + """crwdns330376:0crwdne330376:0 (crwdns330374:0crwdne330374:0) - Example: ``uart.readline()`` +Example: ``uart.readline()`` - :return: The line read or ``None`` on timeout. The newline character is included in the returned bytes. - """ +:return: The line read or ``None`` on timeout. The newline character is included in the returned bytes.""" ... def write(buf: Union[bytes, str]) -> Optional[int]: - """Write a buffer to the bus. + """crwdns330380:0crwdne330380:0 (crwdns330378:0crwdne330378:0) - Example: ``uart.write('hello world')`` +Example: ``uart.write('hello world')`` - :param buf: A bytes object or a string. - :return: The number of bytes written, or ``None`` on timeout. +:param buf: (crwdns330382:0crwdne330382:0) crwdns330384:0crwdne330384:0 +:return: The number of bytes written, or ``None`` on timeout. - Examples:: +Examples:: - uart.write('hello world') - uart.write(b'hello world') - uart.write(bytes([1, 2, 3])) - """ - ... + uart.write('hello world') + uart.write(b'hello world') + uart.write(bytes([1, 2, 3]))""" + ... \ No newline at end of file diff --git a/lang/lol/typeshed/stdlib/micropython.pyi b/lang/lol/typeshed/stdlib/micropython.pyi index 7a6079f..014befe 100644 --- a/lang/lol/typeshed/stdlib/micropython.pyi +++ b/lang/lol/typeshed/stdlib/micropython.pyi @@ -1,144 +1,131 @@ -"""MicroPython internals.""" - +"""crwdns330388:0crwdne330388:0 (crwdns330386:0crwdne330386:0)""" from typing import Any, TypeVar, overload - -_T = TypeVar("_T") +_T = TypeVar('_T') def const(expr: _T) -> _T: - """Used to declare that the expression is a constant so that the compiler can - optimise it. + """crwdns330392:0crwdne330392:0 (crwdns330390:0crwdne330390:0) - The use of this function should be as follows:: +The use of this function should be as follows:: - from micropython import const - CONST_X = const(123) - CONST_Y = const(2 * CONST_X + 1) + from micropython import const + CONST_X = const(123) + CONST_Y = const(2 * CONST_X + 1) - Constants declared this way are still accessible as global variables from - outside the module they are declared in. On the other hand, if a constant - begins with an underscore then it is hidden, it is not available as a - global variable, and does not take up any memory during execution. +Constants declared this way are still accessible as global variables from +outside the module they are declared in. On the other hand, if a constant +begins with an underscore then it is hidden, it is not available as a +global variable, and does not take up any memory during execution. - :param expr: A constant expression. - """ +:param expr: (crwdns330394:0crwdne330394:0) crwdns330396:0crwdne330396:0""" ... @overload def opt_level() -> int: - """Get the current optimisation level for the compilation of scripts. + """crwdns330400:0crwdne330400:0 (crwdns330398:0crwdne330398:0) - Example: ``micropython.opt_level()`` +Example: ``micropython.opt_level()`` - The optimisation level controls the following compilation features: +The optimisation level controls the following compilation features: - - Assertions: at level 0 assertion statements are enabled and compiled - into the bytecode; at levels 1 and higher assertions are not compiled. +- Assertions: at level 0 assertion statements are enabled and compiled + into the bytecode; at levels 1 and higher assertions are not compiled. - - Built-in ``__debug__`` variable: at level 0 this variable expands to - True; at levels 1 and higher it expands to False. +- Built-in ``__debug__`` variable: at level 0 this variable expands to + True; at levels 1 and higher it expands to False. - - Source-code line numbers: at levels 0, 1 and 2 source-code line number - are stored along with the bytecode so that exceptions can report the - line number they occurred at; at levels 3 and higher line numbers are - not stored. +- Source-code line numbers: at levels 0, 1 and 2 source-code line number + are stored along with the bytecode so that exceptions can report the + line number they occurred at; at levels 3 and higher line numbers are + not stored. - :return: An integer representing the current level. - """ +:return: An integer representing the current level.""" ... @overload def opt_level(level: int) -> None: - """Sets the optimisation level for subsequent compilation of scripts. + """crwdns330404:0crwdne330404:0 (crwdns330402:0crwdne330402:0) - Example: ``micropython.opt_level(1)`` +Example: ``micropython.opt_level(1)`` - The optimisation level controls the following compilation features: +The optimisation level controls the following compilation features: - - Assertions: at level 0 assertion statements are enabled and compiled - into the bytecode; at levels 1 and higher assertions are not compiled. +- Assertions: at level 0 assertion statements are enabled and compiled + into the bytecode; at levels 1 and higher assertions are not compiled. - - Built-in ``__debug__`` variable: at level 0 this variable expands to - True; at levels 1 and higher it expands to False. +- Built-in ``__debug__`` variable: at level 0 this variable expands to + True; at levels 1 and higher it expands to False. - - Source-code line numbers: at levels 0, 1 and 2 source-code line number - are stored along with the bytecode so that exceptions can report the - line number they occurred at; at levels 3 and higher line numbers are - not stored. +- Source-code line numbers: at levels 0, 1 and 2 source-code line number + are stored along with the bytecode so that exceptions can report the + line number they occurred at; at levels 3 and higher line numbers are + not stored. - The default optimisation level is usually level 0. +The default optimisation level is usually level 0. - :param level: An integer optimisation level. - """ +:param level: (crwdns330406:0crwdne330406:0) crwdns330408:0crwdne330408:0""" ... -def mem_info(verbose: Any = None) -> None: - """Print information about currently used memory. +def mem_info(verbose: Any=None) -> None: + """crwdns330412:0crwdne330412:0 (crwdns330410:0crwdne330410:0) - Example: ``micropython.mem_info()`` +Example: ``micropython.mem_info()`` - :param verbose: If the ``verbose`` argument is given then extra information is printed. - """ +:param verbose: (crwdns330414:0crwdne330414:0) crwdns330416:0``verbose``crwdne330416:0""" ... -def qstr_info(verbose: Any = None) -> None: - """Print information about currently interned strings. +def qstr_info(verbose: Any=None) -> None: + """crwdns330420:0crwdne330420:0 (crwdns330418:0crwdne330418:0) - Example: ``micropython.qstr_info()`` +Example: ``micropython.qstr_info()`` - :param verbose: If the ``verbose`` argument is given then extra information is printed. +:param verbose: (crwdns330422:0crwdne330422:0) crwdns330424:0``verbose``crwdne330424:0 - The information that is printed is implementation dependent, but currently - includes the number of interned strings and the amount of RAM they use. In - verbose mode it prints out the names of all RAM-interned strings. - """ +The information that is printed is implementation dependent, but currently +includes the number of interned strings and the amount of RAM they use. In +verbose mode it prints out the names of all RAM-interned strings.""" ... def stack_use() -> int: - """Return an integer representing the current amount of stack that is being - used. + """crwdns330428:0crwdne330428:0 (crwdns330426:0crwdne330426:0) - Example: ``micropython.stack_use()`` +Example: ``micropython.stack_use()`` - The absolute value of this is not particularly useful, rather it - should be used to compute differences in stack usage at different points. +The absolute value of this is not particularly useful, rather it +should be used to compute differences in stack usage at different points. - :return: An integer representing current stack use. - """ +:return: An integer representing current stack use.""" ... def heap_lock() -> None: - """Lock the heap. + """crwdns330432:0crwdne330432:0 (crwdns330430:0crwdne330430:0) - Example: ``micropython.heap_lock()`` +Example: ``micropython.heap_lock()`` - When locked no memory allocation can occur and a ``MemoryError`` will be - raised if any heap allocation is attempted. - """ +When locked no memory allocation can occur and a ``MemoryError`` will be +raised if any heap allocation is attempted.""" ... def heap_unlock() -> None: - """Unlock the heap. + """crwdns330436:0crwdne330436:0 (crwdns330434:0crwdne330434:0) - Example: ``micropython.heap_unlock()`` +Example: ``micropython.heap_unlock()`` - When locked no memory allocation can occur and a ``MemoryError`` will be - raised if any heap allocation is attempted. - """ +When locked no memory allocation can occur and a ``MemoryError`` will be +raised if any heap allocation is attempted.""" ... def kbd_intr(chr: int) -> None: - """Set the character that will raise a ``KeyboardInterrupt`` exception. + """crwdns330440:0``KeyboardInterrupt``crwdne330440:0 (crwdns330438:0crwdne330438:0) - Example: ``micropython.kbd_intr(-1)`` +Example: ``micropython.kbd_intr(-1)`` - :param chr: Character code to raise the interrupt or -1 to disable capture of Ctrl-C. +:param chr: (crwdns330442:0crwdne330442:0) crwdns330444:0crwdne330444:0 - By default this is set to 3 during script execution, corresponding to Ctrl-C. - Passing -1 to this function will disable capture of Ctrl-C, and passing 3 - will restore it. +By default this is set to 3 during script execution, corresponding to Ctrl-C. +Passing -1 to this function will disable capture of Ctrl-C, and passing 3 +will restore it. - This function can be used to prevent the capturing of Ctrl-C on the - incoming stream of characters that is usually used for the REPL, in case - that stream is used for other purposes. - """ - ... +This function can be used to prevent the capturing of Ctrl-C on the +incoming stream of characters that is usually used for the REPL, in case +that stream is used for other purposes.""" + ... \ No newline at end of file diff --git a/lang/lol/typeshed/stdlib/music.pyi b/lang/lol/typeshed/stdlib/music.pyi index 5f4778b..e432421 100644 --- a/lang/lol/typeshed/stdlib/music.pyi +++ b/lang/lol/typeshed/stdlib/music.pyi @@ -1,167 +1,128 @@ -"""Create and play melodies. -""" +"""crwdns330448:0crwdne330448:0 (crwdns330446:0crwdne330446:0)""" from typing import Optional, Tuple, Union, List - from .microbit import MicroBitDigitalPin, pin0 - DADADADUM: Tuple[str, ...] -"""Melody: the opening to Beethoven’s 5th Symphony in C minor.""" - +"""crwdns330452:0crwdne330452:0 (crwdns330450:0crwdne330450:0)""" ENTERTAINER: Tuple[str, ...] -"""Melody: the opening fragment of Scott Joplin’s Ragtime classic “The Entertainer”.""" - +"""crwdns330456:0crwdne330456:0 (crwdns330454:0crwdne330454:0)""" PRELUDE: Tuple[str, ...] -"""Melody: the opening of the first Prelude in C Major of J.S.Bach’s 48 Preludes and Fugues.""" - +"""crwdns330460:0crwdne330460:0 (crwdns330458:0crwdne330458:0)""" ODE: Tuple[str, ...] -"""Melody: the “Ode to Joy” theme from Beethoven’s 9th Symphony in D minor.""" - +"""crwdns330464:0crwdne330464:0 (crwdns330462:0crwdne330462:0)""" NYAN: Tuple[str, ...] -"""Melody: the Nyan Cat theme (http://www.nyan.cat/). +"""crwdns330468:0crwdne330468:0 (crwdns330466:0crwdne330466:0) The composer is unknown. This is fair use for educational porpoises (as they say in New York).""" - RINGTONE: Tuple[str, ...] -"""Melody: something that sounds like a mobile phone ringtone. +"""crwdns330472:0crwdne330472:0 (crwdns330470:0crwdne330470:0) To be used to indicate an incoming message. """ - FUNK: Tuple[str, ...] -"""Melody: a funky bass line for secret agents and criminal masterminds.""" - +"""crwdns330476:0crwdne330476:0 (crwdns330474:0crwdne330474:0)""" BLUES: Tuple[str, ...] -"""Melody: a boogie-woogie 12-bar blues walking bass.""" - +"""crwdns330480:0crwdne330480:0 (crwdns330478:0crwdne330478:0)""" BIRTHDAY: Tuple[str, ...] -"""Melody: “Happy Birthday to You…” +"""crwdns330484:0crwdne330484:0 (crwdns330482:0crwdne330482:0) For copyright status see: http://www.bbc.co.uk/news/world-us-canada-34332853 """ - WEDDING: Tuple[str, ...] -"""Melody: the bridal chorus from Wagner’s opera “Lohengrin”.""" - +"""crwdns330488:0crwdne330488:0 (crwdns330486:0crwdne330486:0)""" FUNERAL: Tuple[str, ...] -"""Melody: the “funeral march” otherwise known as Frédéric Chopin’s Piano Sonata No. 2 in B♭ minor, Op. 35.""" - +"""crwdns330492:0crwdne330492:0 (crwdns330490:0crwdne330490:0)""" PUNCHLINE: Tuple[str, ...] -"""Melody: a fun fragment that signifies a joke has been made.""" - +"""crwdns330496:0crwdne330496:0 (crwdns330494:0crwdne330494:0)""" PYTHON: Tuple[str, ...] -"""Melody: John Philip Sousa’s march “Liberty Bell” aka, the theme for “Monty Python’s Flying Circus” (after which the Python programming language is named).""" - +"""crwdns330500:0crwdne330500:0 (crwdns330498:0crwdne330498:0)""" BADDY: Tuple[str, ...] -"""Melody: silent movie era entrance of a baddy.""" - +"""crwdns330504:0crwdne330504:0 (crwdns330502:0crwdne330502:0)""" CHASE: Tuple[str, ...] -"""Melody: silent movie era chase scene.""" - +"""crwdns330508:0crwdne330508:0 (crwdns330506:0crwdne330506:0)""" BA_DING: Tuple[str, ...] -"""Melody: a short signal to indicate something has happened.""" - +"""crwdns330512:0crwdne330512:0 (crwdns330510:0crwdne330510:0)""" WAWAWAWAA: Tuple[str, ...] -"""Melody: a very sad trombone.""" - +"""crwdns330516:0crwdne330516:0 (crwdns330514:0crwdne330514:0)""" JUMP_UP: Tuple[str, ...] -"""Melody: for use in a game, indicating upward movement.""" - +"""crwdns330520:0crwdne330520:0 (crwdns330518:0crwdne330518:0)""" JUMP_DOWN: Tuple[str, ...] -"""Melody: for use in a game, indicating downward movement.""" - +"""crwdns330524:0crwdne330524:0 (crwdns330522:0crwdne330522:0)""" POWER_UP: Tuple[str, ...] -"""Melody: a fanfare to indicate an achievement unlocked.""" - +"""crwdns330528:0crwdne330528:0 (crwdns330526:0crwdne330526:0)""" POWER_DOWN: Tuple[str, ...] -"""Melody: a sad fanfare to indicate an achievement lost.""" +"""crwdns330532:0crwdne330532:0 (crwdns330530:0crwdne330530:0)""" -def set_tempo(ticks: int = 4, bpm: int = 120) -> None: - """Sets the approximate tempo for playback. +def set_tempo(ticks: int=4, bpm: int=120) -> None: + """crwdns330536:0crwdne330536:0 (crwdns330534:0crwdne330534:0) - Example: ``music.set_tempo(bpm=120)`` +Example: ``music.set_tempo(bpm=120)`` - :param ticks: The number of ticks constituting a beat. - :param bpm: An integer determining how many beats per minute. +:param ticks: (crwdns330542:0crwdne330542:0) crwdns330544:0crwdne330544:0 +:param bpm: (crwdns330538:0crwdne330538:0) crwdns330540:0crwdne330540:0 - Suggested default values allow the following useful behaviour: +Suggested default values allow the following useful behaviour: - - music.set_tempo() – reset the tempo to default of ticks = 4, bpm = 120 - - music.set_tempo(ticks=8) – change the “definition” of a beat - - music.set_tempo(bpm=180) – just change the tempo +- music.set_tempo() – reset the tempo to default of ticks = 4, bpm = 120 +- music.set_tempo(ticks=8) – change the “definition” of a beat +- music.set_tempo(bpm=180) – just change the tempo - To work out the length of a tick in milliseconds is very simple arithmetic: - 60000/bpm/ticks_per_beat. For the default values that’s - 60000/120/4 = 125 milliseconds or 1 beat = 500 milliseconds. - """ +To work out the length of a tick in milliseconds is very simple arithmetic: +60000/bpm/ticks_per_beat. For the default values that’s +60000/120/4 = 125 milliseconds or 1 beat = 500 milliseconds.""" ... def get_tempo() -> Tuple[int, int]: - """Gets the current tempo as a tuple of integers: ``(ticks, bpm)``. + """crwdns330548:0``(ticks, bpm)``crwdne330548:0 (crwdns330546:0crwdne330546:0) - Example: ``ticks, beats = music.get_tempo()`` +Example: ``ticks, beats = music.get_tempo()`` - :return: The temp as a tuple with two integer values, the ticks then the beats per minute. - """ +:return: The temp as a tuple with two integer values, the ticks then the beats per minute.""" ... -def play( - music: Union[str, List[str], Tuple[str, ...]], - pin: Optional[MicroBitDigitalPin] = pin0, - wait: bool = True, - loop: bool = False, -) -> None: - """Plays music. +def play(music: Union[str, List[str], Tuple[str, ...]], pin: Optional[MicroBitDigitalPin]=pin0, wait: bool=True, loop: bool=False) -> None: + """crwdns330552:0crwdne330552:0 (crwdns330550:0crwdne330550:0) - Example: ``music.play(music.NYAN)`` +Example: ``music.play(music.NYAN)`` - :param music: music specified in `a special notation `_ - :param pin: the output pin for use with an external speaker (default ``pin0``), ``None`` for no sound. - :param wait: If ``wait`` is set to ``True``, this function is blocking. - :param loop: If ``loop`` is set to ``True``, the tune repeats until ``stop`` is called or the blocking call is interrupted. +:param music: (crwdns330558:0crwdne330558:0) crwdns330560:0crwdne330560:0 +:param pin: (crwdns330562:0crwdne330562:0) crwdns330564:0``pin0``crwdnd330564:0``None``crwdne330564:0 +:param wait: (crwdns330566:0crwdne330566:0) crwdns330568:0``wait``crwdnd330568:0``True``crwdne330568:0 +:param loop: (crwdns330554:0crwdne330554:0) crwdns330556:0``loop``crwdnd330556:0``True``crwdnd330556:0``stop``crwdne330556:0 - Many built-in melodies are defined in this module. - """ +Many built-in melodies are defined in this module.""" ... -def pitch( - frequency: int, - duration: int = -1, - pin: Optional[MicroBitDigitalPin] = pin0, - wait: bool = True, -) -> None: - """Play a note. +def pitch(frequency: int, duration: int=-1, pin: Optional[MicroBitDigitalPin]=pin0, wait: bool=True) -> None: + """crwdns330572:0crwdne330572:0 (crwdns330570:0crwdne330570:0) - Example: ``music.pitch(185, 1000)`` +Example: ``music.pitch(185, 1000)`` - :param frequency: An integer frequency - :param duration: A millisecond duration. If negative then sound is continuous until the next call or a call to ``stop``. - :param pin: Optional output pin (default ``pin0``). - :param wait: If ``wait`` is set to ``True``, this function is blocking. +:param frequency: (crwdns330578:0crwdne330578:0) crwdns330580:0crwdne330580:0 +:param duration: (crwdns330574:0crwdne330574:0) crwdns330576:0``stop``crwdne330576:0 +:param pin: (crwdns330582:0crwdne330582:0) crwdns330584:0``pin0``crwdne330584:0 +:param wait: (crwdns330586:0crwdne330586:0) crwdns330588:0``wait``crwdnd330588:0``True``crwdne330588:0 - For example, if the frequency is set to 440 and the length to - 1000 then we hear a standard concert A for one second. +For example, if the frequency is set to 440 and the length to +1000 then we hear a standard concert A for one second. - You can only play one pitch on one pin at any one time. - """ +You can only play one pitch on one pin at any one time.""" ... -def stop(pin: Optional[MicroBitDigitalPin] = pin0) -> None: - """Stops all music playback on the built-in speaker and any pin outputting sound. +def stop(pin: Optional[MicroBitDigitalPin]=pin0) -> None: + """crwdns330592:0crwdne330592:0 (crwdns330590:0crwdne330590:0) - Example: ``music.stop()`` +Example: ``music.stop()`` - :param pin: An optional argument can be provided to specify a pin, e.g. ``music.stop(pin1)``. - """ +:param pin: (crwdns330594:0crwdne330594:0) crwdns330596:0``music.stop(pin1)``crwdne330596:0""" def reset() -> None: - """Resets ticks, bpm, duration and octave to their default values. + """crwdns330600:0crwdne330600:0 (crwdns330598:0crwdne330598:0) - Example: ``music.reset()`` +Example: ``music.reset()`` - Values: - - ``ticks = 4`` - - ``bpm = 120`` - - ``duration = 4`` - - ``octave = 4`` - """ - ... +Values: +- ``ticks = 4`` +- ``bpm = 120`` +- ``duration = 4`` +- ``octave = 4``""" + ... \ No newline at end of file diff --git a/lang/lol/typeshed/stdlib/neopixel.pyi b/lang/lol/typeshed/stdlib/neopixel.pyi index 2d5a749..5ef04a8 100644 --- a/lang/lol/typeshed/stdlib/neopixel.pyi +++ b/lang/lol/typeshed/stdlib/neopixel.pyi @@ -1,82 +1,81 @@ -"""Individually addressable RGB and RGBW LED strips. -""" +"""crwdns330604:0crwdne330604:0 (crwdns330602:0crwdne330602:0)""" from .microbit import MicroBitDigitalPin from typing import Tuple class NeoPixel: - def __init__(self, pin: MicroBitDigitalPin, n: int, bpp: int = 3) -> None: - """Initialise a new strip of neopixel LEDs controlled via a pin. - Example: ``np = neopixel.NeoPixel(pin0, 8)`` + def __init__(self, pin: MicroBitDigitalPin, n: int, bpp: int=3) -> None: + """crwdns330608:0crwdne330608:0 (crwdns330606:0crwdne330606:0) - To support RGBW neopixels, a third argument can be passed to - ``NeoPixel`` to indicate the number of bytes per pixel (``bpp``). - For RGBW, this is is 4 rather than the default of 3 for RGB and GRB. +Example: ``np = neopixel.NeoPixel(pin0, 8)`` - Each pixel is addressed by a position (starting from 0). Neopixels are - given RGB (red, green, blue) / RGBW (red, green, blue, white) values - between 0-255 as a tuple. For example, in RGB, ``(255,255,255)`` is - white. In RGBW, ``(255,255,255,0)`` or ``(0,0,0,255)`` is white. +To support RGBW neopixels, a third argument can be passed to +``NeoPixel`` to indicate the number of bytes per pixel (``bpp``). +For RGBW, this is is 4 rather than the default of 3 for RGB and GRB. - See `the online docs `_ for warnings and other advice. +Each pixel is addressed by a position (starting from 0). Neopixels are +given RGB (red, green, blue) / RGBW (red, green, blue, white) values +between 0-255 as a tuple. For example, in RGB, ``(255,255,255)`` is +white. In RGBW, ``(255,255,255,0)`` or ``(0,0,0,255)`` is white. - :param pin: The pin controlling the neopixel strip. - :param n: The number of neopixels in the strip. - :param bpp: Bytes per pixel. For RGBW neopixel support, pass 4 rather than the default of 3 for RGB and GRB. - """ +See `the online docs `_ for warnings and other advice. + +:param pin: (crwdns330618:0crwdne330618:0) crwdns330620:0crwdne330620:0 +:param n: (crwdns330614:0crwdne330614:0) crwdns330616:0crwdne330616:0 +:param bpp: (crwdns330610:0crwdne330610:0) crwdns355240:0crwdne355240:0""" ... + def clear(self) -> None: - """Clear all the pixels. + """crwdns330624:0crwdne330624:0 (crwdns330622:0crwdne330622:0) - Example: ``np.clear()`` - """ +Example: ``np.clear()``""" ... + def show(self) -> None: - """Show the pixels. + """crwdns330628:0crwdne330628:0 (crwdns330626:0crwdne330626:0) - Example: ``np.show()`` +Example: ``np.show()`` - Must be called for any updates to become visible. - """ +Must be called for any updates to become visible.""" ... + def write(self) -> None: - """Show the pixels (micro:bit V2 only). + """crwdns330632:0crwdne330632:0 (crwdns330630:0crwdne330630:0) - Example: ``np.write()`` +Example: ``np.write()`` - Must be called for any updates to become visible. +Must be called for any updates to become visible. - Equivalent to ``show``. - """ +Equivalent to ``show``.""" ... + def fill(self, colour: Tuple[int, ...]) -> None: - """Colour all pixels a given RGB/RGBW value (micro:bit V2 only). + """crwdns330636:0crwdne330636:0 (crwdns330634:0crwdne330634:0) - Example: ``np.fill((0, 0, 255))`` +Example: ``np.fill((0, 0, 255))`` - :param colour: A tuple of the same length as the number of bytes per pixel (bpp). +:param colour: (crwdns330638:0crwdne330638:0) crwdns330640:0crwdne330640:0 - Use in conjunction with ``show()`` to update the neopixels. - """ +Use in conjunction with ``show()`` to update the neopixels.""" ... + def __setitem__(self, key: int, value: Tuple[int, ...]) -> None: - """Set a pixel colour. + """crwdns330644:0crwdne330644:0 (crwdns330642:0crwdne330642:0) - Example: ``np[0] = (255, 0, 0)`` +Example: ``np[0] = (255, 0, 0)`` + +:param key: (crwdns330646:0crwdne330646:0) crwdns330648:0crwdne330648:0 +:param value: (crwdns330650:0crwdne330650:0) crwdns330652:0crwdne330652:0""" - :param key: The pixel number. - :param value: The colour. - """ def __getitem__(self, key: int) -> Tuple[int, ...]: - """Get a pixel colour. + """crwdns330656:0crwdne330656:0 (crwdns330654:0crwdne330654:0) + +Example: ``r, g, b = np[0]`` - Example: ``r, g, b = np[0]`` +:param key: (crwdns330658:0crwdne330658:0) crwdns330660:0crwdne330660:0 +:return: The colour tuple.""" - :param key: The pixel number. - :return: The colour tuple. - """ def __len__(self) -> int: - """Get length of this pixel strip. + """crwdns330664:0crwdne330664:0 (crwdns330662:0crwdne330662:0) - Example: ``len(np)`` - """ +Example: ``len(np)``""" \ No newline at end of file diff --git a/lang/lol/typeshed/stdlib/os.pyi b/lang/lol/typeshed/stdlib/os.pyi index 2f2db77..24170cf 100644 --- a/lang/lol/typeshed/stdlib/os.pyi +++ b/lang/lol/typeshed/stdlib/os.pyi @@ -1,73 +1,63 @@ -"""Access the file system. -""" - +"""crwdns330668:0crwdne330668:0 (crwdns330666:0crwdne330666:0)""" from typing import Tuple from typing import List def listdir() -> List[str]: - """List files. + """crwdns330672:0crwdne330672:0 (crwdns330670:0crwdne330670:0) - Example: ``os.listdir()`` +Example: ``os.listdir()`` - :return: A list of the names of all the files contained within the local - persistent on-device file system. - """ +:return: A list of the names of all the files contained within the local +persistent on-device file system.""" ... def remove(filename: str) -> None: - """Remove (delete) a file. + """crwdns330676:0crwdne330676:0 (crwdns330674:0crwdne330674:0) - Example: ``os.remove('data.txt')`` +Example: ``os.remove('data.txt')`` - :param filename: The file to delete. +:param filename: (crwdns330678:0crwdne330678:0) crwdns330680:0crwdne330680:0 - If the file does not exist an ``OSError`` exception will occur. - """ +If the file does not exist an ``OSError`` exception will occur.""" ... def size(filename: str) -> int: - """Returns the size of a file. + """crwdns330684:0crwdne330684:0 (crwdns330682:0crwdne330682:0) - Example: ``os.size('data.txt')`` +Example: ``os.size('data.txt')`` - :param filename: The file - :return: The size in bytes. +:param filename: (crwdns330686:0crwdne330686:0) crwdns330688:0crwdne330688:0 +:return: The size in bytes. - If the file does not exist an ``OSError`` exception will occur. - """ +If the file does not exist an ``OSError`` exception will occur.""" class uname_result(Tuple[str, str, str, str, str]): - """Result of ``os.uname()``""" + """crwdns330692:0``os.uname()``crwdne330692:0 (crwdns330690:0crwdne330690:0)""" sysname: str - """Operating system name.""" - + """crwdns330696:0crwdne330696:0 (crwdns330694:0crwdne330694:0)""" nodename: str - """Name of machine on network (implementation-defined).""" - + """crwdns330700:0crwdne330700:0 (crwdns330698:0crwdne330698:0)""" release: str - """Operating system release.""" - + """crwdns330704:0crwdne330704:0 (crwdns330702:0crwdne330702:0)""" version: str - """Operating system version.""" - + """crwdns330708:0crwdne330708:0 (crwdns330706:0crwdne330706:0)""" machine: str - """Hardware identifier.""" + """crwdns330712:0crwdne330712:0 (crwdns330710:0crwdne330710:0)""" def uname() -> uname_result: - """Returns information identifying the current operating system. + """crwdns330716:0crwdne330716:0 (crwdns330714:0crwdne330714:0) - Example: ``os.uname()`` +Example: ``os.uname()`` - The return value is an object with five attributes: +The return value is an object with five attributes: - - ``sysname`` - operating system name - - ``nodename`` - name of machine on network (implementation-defined) - - ``release`` - operating system release - - ``version`` - operating system version - - ``machine`` - hardware identifier +- ``sysname`` - operating system name +- ``nodename`` - name of machine on network (implementation-defined) +- ``release`` - operating system release +- ``version`` - operating system version +- ``machine`` - hardware identifier - There is no underlying operating system in MicroPython. As a result the - information returned by the ``uname`` function is mostly useful for - versioning details. - """ - ... +There is no underlying operating system in MicroPython. As a result the +information returned by the ``uname`` function is mostly useful for +versioning details.""" + ... \ No newline at end of file diff --git a/lang/lol/typeshed/stdlib/radio.pyi b/lang/lol/typeshed/stdlib/radio.pyi index 8dd0267..079f747 100644 --- a/lang/lol/typeshed/stdlib/radio.pyi +++ b/lang/lol/typeshed/stdlib/radio.pyi @@ -1,152 +1,123 @@ -"""Communicate between micro:bits with the built-in radio. -""" - +"""crwdns330720:0crwdne330720:0 (crwdns330718:0crwdne330718:0)""" from _typeshed import WriteableBuffer from typing import Optional, Tuple - RATE_1MBIT: int -"""Constant used to indicate a throughput of 1 MBit a second.""" - +"""crwdns330724:0crwdne330724:0 (crwdns330722:0crwdne330722:0)""" RATE_2MBIT: int -"""Constant used to indicate a throughput of 2 MBit a second.""" +"""crwdns330728:0crwdne330728:0 (crwdns330726:0crwdne330726:0)""" def on() -> None: - """Turns the radio on. + """crwdns330732:0crwdne330732:0 (crwdns330730:0crwdne330730:0) - Example: ``radio.on()`` +Example: ``radio.on()`` - This needs to be explicitly called since the radio draws power and takes - up memory that you may otherwise need. - """ +This needs to be explicitly called since the radio draws power and takes +up memory that you may otherwise need.""" ... def off() -> None: - """Turns off the radio, saving power and memory. + """crwdns330736:0crwdne330736:0 (crwdns330734:0crwdne330734:0) - Example: ``radio.off()`` - """ +Example: ``radio.off()``""" ... -def config( - length: int = 32, - queue: int = 3, - channel: int = 7, - power: int = 6, - address: int = 0x75626974, - group: int = 0, - data_rate: int = RATE_1MBIT, -) -> None: - """Configures the radio. - - Example: ``radio.config(group=42)`` - - The default configuration is suitable for most use. - - :param length: (default=32) defines the maximum length, in bytes, of a message sent via the radio. - It can be up to 251 bytes long (254 - 3 bytes for S0, LENGTH and S1 preamble). - :param queue: (default=3) specifies the number of messages that can be stored on the incoming message queue. - If there are no spaces left on the queue for incoming messages, then the incoming message is dropped. - :param channel: (default=7) an integer value from 0 to 83 (inclusive) that defines an arbitrary "channel" to which the radio is tuned. - Messages will be sent via this channel and only messages received via this channel will be put onto the incoming message queue. Each step is 1MHz wide, based at 2400MHz. - :param power: (default=6) is an integer value from 0 to 7 (inclusive) to indicate the strength of signal used when broadcasting a message. - The higher the value the stronger the signal, but the more power is consumed by the device. The numbering translates to positions in the following list of dBm (decibel milliwatt) values: -30, -20, -16, -12, -8, -4, 0, 4. - :param address: (default=0x75626974) an arbitrary name, expressed as a 32-bit address, that's used to filter incoming packets at the hardware level, keeping only those that match the address you set. - The default used by other micro:bit related platforms is the default setting used here. - :param group: (default=0) an 8-bit value (0-255) used with the ``address`` when filtering messages. - Conceptually, "address" is like a house/office address and "group" is like the person at that address to which you want to send your message. - :param data_rate: (default=``radio.RATE_1MBIT``) indicates the speed at which data throughput takes place. - Can be one of the following constants defined in the ``radio`` module: ``RATE_250KBIT``, ``RATE_1MBIT`` or ``RATE_2MBIT``. - - If ``config`` is not called then the defaults described above are assumed. - """ +def config(length: int=32, queue: int=3, channel: int=7, power: int=6, address: int=1969383796, group: int=0, data_rate: int=RATE_1MBIT) -> None: + """crwdns330740:0crwdne330740:0 (crwdns330738:0crwdne330738:0) + +Example: ``radio.config(group=42)`` + +The default configuration is suitable for most use. + +:param length: (crwdns330758:0crwdne330758:0) crwdns330760:0crwdne330760:0 +:param queue: (crwdns330766:0crwdne330766:0) crwdns330768:0crwdne330768:0 +:param channel: (crwdns330746:0crwdne330746:0) crwdns330748:0crwdne330748:0 +:param power: (crwdns330762:0crwdne330762:0) crwdns330764:0crwdne330764:0 +:param address: (crwdns330742:0crwdne330742:0) crwdns330744:0crwdne330744:0 +:param group: (crwdns330754:0crwdne330754:0) crwdns330756:0``address``crwdne330756:0 +:param data_rate: (crwdns330750:0crwdne330750:0) crwdns330752:0``radio.RATE_1MBIT``crwdnd330752:0``radio``crwdnd330752:0``RATE_250KBIT``crwdnd330752:0``RATE_1MBIT``crwdnd330752:0``RATE_2MBIT``crwdne330752:0 + +If ``config`` is not called then the defaults described above are assumed.""" ... def reset() -> None: - """Reset the settings to their default values. + """crwdns330772:0crwdne330772:0 (crwdns330770:0crwdne330770:0) - Example: ``radio.reset()`` +Example: ``radio.reset()`` - The defaults as as per the ``config`` function above. - """ +The defaults as as per the ``config`` function above.""" ... def send_bytes(message: bytes) -> None: - """Sends a message containing bytes. + """crwdns330776:0crwdne330776:0 (crwdns330774:0crwdne330774:0) - Example: ``radio.send_bytes(b'hello')`` +Example: ``radio.send_bytes(b'hello')`` - :param message: The bytes to send. - """ +:param message: (crwdns330778:0crwdne330778:0) crwdns330780:0crwdne330780:0""" ... def receive_bytes() -> Optional[bytes]: - """Receive the next incoming message on the message queue. + """crwdns330784:0crwdne330784:0 (crwdns330782:0crwdne330782:0) - Example: ``radio.receive_bytes()`` +Example: ``radio.receive_bytes()`` - :return: The message bytes if any, otherwise ``None``. - """ +:return: The message bytes if any, otherwise ``None``.""" ... def receive_bytes_into(buffer: WriteableBuffer) -> Optional[int]: - """Copy the next incoming message on the message queue into a buffer. + """crwdns330788:0crwdne330788:0 (crwdns330786:0crwdne330786:0) - Example: ``radio.receive_bytes_info(buffer)`` +Example: ``radio.receive_bytes_info(buffer)`` - :param buffer: The target buffer. The message is truncated if larger than the buffer. - :return: ``None`` if there are no pending messages, otherwise it returns the length of the message (which might be more than the length of the buffer). - """ +:param buffer: (crwdns330790:0crwdne330790:0) crwdns330792:0crwdne330792:0 +:return: ``None`` if there are no pending messages, otherwise it returns the length of the message (which might be more than the length of the buffer).""" ... def send(message: str) -> None: - """Sends a message string. + """crwdns330796:0crwdne330796:0 (crwdns330794:0crwdne330794:0) - Example: ``radio.send('hello')`` +Example: ``radio.send('hello')`` - This is the equivalent of ``radio.send_bytes(bytes(message, 'utf8'))`` but with ``b'\x01\x00\x01'`` - prepended to the front (to make it compatible with other platforms that target the micro:bit). +This is the equivalent of ``radio.send_bytes(bytes(message, 'utf8'))`` but with ``b'\x01\x00\x01'`` +prepended to the front (to make it compatible with other platforms that target the micro:bit). - :param message: The string to send. - """ +:param message: (crwdns330798:0crwdne330798:0) crwdns330800:0crwdne330800:0""" ... def receive() -> Optional[str]: - """Works in exactly the same way as ``receive_bytes`` but returns whatever was sent. + """crwdns330804:0``receive_bytes``crwdne330804:0 (crwdns330802:0crwdne330802:0) - Example: ``radio.receive()`` +Example: ``radio.receive()`` - Equivalent to ``str(receive_bytes(), 'utf8')`` but with a check that the the first - three bytes are ``b'\x01\x00\x01'`` (to make it compatible with other platforms that - may target the micro:bit). +Equivalent to ``str(receive_bytes(), 'utf8')`` but with a check that the the first +three bytes are ``b'\x01\x00\x01'`` (to make it compatible with other platforms that +may target the micro:bit). - :return: The message with the prepended bytes stripped and converted to a string. +:return: The message with the prepended bytes stripped and converted to a string. - A ``ValueError`` exception is raised if conversion to string fails. - """ +A ``ValueError`` exception is raised if conversion to string fails.""" ... def receive_full() -> Optional[Tuple[bytes, int, int]]: - """Returns a tuple containing three values representing the next incoming message on the message queue. + """crwdns330808:0crwdne330808:0 (crwdns330806:0crwdne330806:0) - Example: ``radio.receive_full()`` +Example: ``radio.receive_full()`` - If there are no pending messages then ``None`` is returned. +If there are no pending messages then ``None`` is returned. - The three values in the tuple represent: +The three values in the tuple represent: - - the next incoming message on the message queue as bytes. - - the RSSI (signal strength): a value between 0 (strongest) and -255 (weakest) as measured in dBm. - - a microsecond timestamp: the value returned by ``time.ticks_us()`` when the message was received. +- the next incoming message on the message queue as bytes. +- the RSSI (signal strength): a value between 0 (strongest) and -255 (weakest) as measured in dBm. +- a microsecond timestamp: the value returned by ``time.ticks_us()`` when the message was received. - For example:: +For example:: - details = radio.receive_full() - if details: - msg, rssi, timestamp = details + details = radio.receive_full() + if details: + msg, rssi, timestamp = details - This function is useful for providing information needed for triangulation - and/or trilateration with other micro:bit devices. +This function is useful for providing information needed for triangulation +and/or trilateration with other micro:bit devices. - :return: ``None`` if there is no message, otherwise a tuple of length three with the bytes, strength and timestamp values. - """ - ... +:return: ``None`` if there is no message, otherwise a tuple of length three with the bytes, strength and timestamp values.""" + ... \ No newline at end of file diff --git a/lang/lol/typeshed/stdlib/random.pyi b/lang/lol/typeshed/stdlib/random.pyi index a2c2ef3..319aa4d 100644 --- a/lang/lol/typeshed/stdlib/random.pyi +++ b/lang/lol/typeshed/stdlib/random.pyi @@ -1,93 +1,80 @@ -"""Generate random numbers. -""" +"""crwdns330812:0crwdne330812:0 (crwdns330810:0crwdne330810:0)""" from typing import TypeVar, Sequence, Union, overload def getrandbits(n: int) -> int: - """Generate an integer with ``n`` random bits. + """crwdns330816:0``n``crwdne330816:0 (crwdns330814:0crwdne330814:0) - Example: ``random.getrandbits(1)`` +Example: ``random.getrandbits(1)`` - :param n: A value between 1-30 (inclusive). - """ +:param n: (crwdns330818:0crwdne330818:0) crwdns330820:0crwdne330820:0""" ... def seed(n: int) -> None: - """Initialize the random number generator. + """crwdns330824:0crwdne330824:0 (crwdns330822:0crwdne330822:0) - Example: ``random.seed(0)`` +Example: ``random.seed(0)`` - :param n: The integer seed +:param n: (crwdns330826:0crwdne330826:0) crwdns330828:0crwdne330828:0 - This will give you reproducibly deterministic randomness from a given starting - state (``n``). - """ +This will give you reproducibly deterministic randomness from a given starting +state (``n``).""" ... def randint(a: int, b: int) -> int: - """Choose a random integer between ``a`` and ``b`` inclusive. + """crwdns330832:0``a``crwdnd330832:0``b``crwdne330832:0 (crwdns330830:0crwdne330830:0) - Example: ``random.randint(0, 9)`` +Example: ``random.randint(0, 9)`` - :param a: Start value for the range (inclusive) - :param b: End value for the range (inclusive) +:param a: (crwdns330834:0crwdne330834:0) crwdns330836:0crwdne330836:0 +:param b: (crwdns330838:0crwdne330838:0) crwdns330840:0crwdne330840:0 - Alias for ``randrange(a, b + 1)``. - """ +Alias for ``randrange(a, b + 1)``.""" ... @overload def randrange(stop: int) -> int: - """Choose a randomly selected integer between zero and up to (but not - including) ``stop``. + """crwdns330844:0``stop``crwdne330844:0 (crwdns330842:0crwdne330842:0) - Example: ``random.randrange(10)`` +Example: ``random.randrange(10)`` - :param stop: End value for the range (exclusive) - """ +:param stop: (crwdns330846:0crwdne330846:0) crwdns330848:0crwdne330848:0""" ... @overload -def randrange(start: int, stop: int, step: int = 1) -> int: - """ - Choose a randomly selected element from ``range(start, stop, step)``. +def randrange(start: int, stop: int, step: int=1) -> int: + """crwdns330852:0``range(start, stop, step)``crwdne330852:0 (crwdns330850:0crwdne330850:0) - Example: ``random.randrange(0, 10)`` +Example: ``random.randrange(0, 10)`` - :param start: The start of the range (inclusive) - :param stop: The end of the range (exclusive) - :param step: The step. - """ +:param start: (crwdns330854:0crwdne330854:0) crwdns330856:0crwdne330856:0 +:param stop: (crwdns330862:0crwdne330862:0) crwdns330864:0crwdne330864:0 +:param step: (crwdns330858:0crwdne330858:0) crwdns330860:0crwdne330860:0""" ... - -_T = TypeVar("_T") +_T = TypeVar('_T') def choice(seq: Sequence[_T]) -> _T: - """Choose a random element from the non-empty sequence ``seq``. + """crwdns330868:0``seq``crwdne330868:0 (crwdns330866:0crwdne330866:0) - Example: ``random.choice([Image.HAPPY, Image.SAD])`` +Example: ``random.choice([Image.HAPPY, Image.SAD])`` - :param seq: A sequence. +:param seq: (crwdns330870:0crwdne330870:0) crwdns330872:0crwdne330872:0 - If ``seq`` is empty, raises ``IndexError``. - """ +If ``seq`` is empty, raises ``IndexError``.""" ... def random() -> float: - """Generate a random floating point number in the range [0.0, 1.0). + """crwdns330876:0crwdne330876:0 (crwdns330874:0crwdne330874:0) - Example: ``random.random()`` +Example: ``random.random()`` - :return: The random floating point number - """ +:return: The random floating point number""" ... def uniform(a: float, b: float) -> float: - """ - Return a random floating point number between ``a`` and ``b`` inclusive. + """crwdns330880:0``a``crwdnd330880:0``b``crwdne330880:0 (crwdns330878:0crwdne330878:0) - Example: ``random.uniform(0, 9)`` +Example: ``random.uniform(0, 9)`` - :param a: Start value for the range (inclusive) - :param b: End value for the range (inclusive) - """ - ... +:param a: (crwdns330882:0crwdne330882:0) crwdns330884:0crwdne330884:0 +:param b: (crwdns330886:0crwdne330886:0) crwdns330888:0crwdne330888:0""" + ... \ No newline at end of file diff --git a/lang/lol/typeshed/stdlib/speech.pyi b/lang/lol/typeshed/stdlib/speech.pyi index 349d188..bbd286f 100644 --- a/lang/lol/typeshed/stdlib/speech.pyi +++ b/lang/lol/typeshed/stdlib/speech.pyi @@ -1,106 +1,76 @@ -"""Make the micro:bit talk, sing and make other speech like sounds. -""" - +"""crwdns330892:0crwdne330892:0 (crwdns330890:0crwdne330890:0)""" from typing import Optional from .microbit import MicroBitDigitalPin, pin0 def translate(words: str) -> str: - """Translate English words to phonemes. + """crwdns330896:0crwdne330896:0 (crwdns330894:0crwdne330894:0) - Example: ``speech.translate('hello world')`` +Example: ``speech.translate('hello world')`` - :param words: A string of English words. - :return: A string containing a best guess at the appropriate phonemes to pronounce. - The output is generated from this `text to phoneme translation table `_. +:param words: (crwdns330898:0crwdne330898:0) crwdns330900:0crwdne330900:0 +:return: A string containing a best guess at the appropriate phonemes to pronounce. +The output is generated from this `text to phoneme translation table `_. - This function should be used to generate a first approximation of phonemes - that can be further hand-edited to improve accuracy, inflection and - emphasis. +This function should be used to generate a first approximation of phonemes +that can be further hand-edited to improve accuracy, inflection and +emphasis. - See `the online documentation `_ for detailed information. - """ +See `the online documentation `_ for detailed information.""" ... -def pronounce( - phonemes: str, - pitch: int = 64, - speed: int = 72, - mouth: int = 128, - throat: int = 128, - pin: Optional[MicroBitDigitalPin] = pin0, -) -> None: - """Pronounce phonemes. - - Example: ``speech.pronounce(' /HEHLOW WERLD')`` - - :param phonemes: The string of phonemes to pronounce - :param pitch: A number representing the pitch of the voice - :param speed: A number representing the speed of the voice - :param mouth: A number representing the mouth of the voice - :param throat: A number representing the throat of the voice - :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. - If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. - - Override the optional pitch, speed, mouth and throat settings to change the - timbre (quality) of the voice. - - See `the online documentation `_ for detailed information. - """ - ... +def pronounce(phonemes: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: Optional[MicroBitDigitalPin]=pin0) -> None: + """crwdns330904:0crwdne330904:0 (crwdns330902:0crwdne330902:0) + +Example: ``speech.pronounce(' /HEHLOW WERLD')`` + +:param phonemes: (crwdns330910:0crwdne330910:0) crwdns330912:0crwdne330912:0 +:param pitch: (crwdns330918:0crwdne330918:0) crwdns330920:0crwdne330920:0 +:param speed: (crwdns330922:0crwdne330922:0) crwdns330924:0crwdne330924:0 +:param mouth: (crwdns330906:0crwdne330906:0) crwdns330908:0crwdne330908:0 +:param throat: (crwdns330926:0crwdne330926:0) crwdns330928:0crwdne330928:0 +:param pin: (crwdns330914:0crwdne330914:0) crwdns330916:0``pin0``crwdne330916:0 -def say( - words: str, - pitch: int = 64, - speed: int = 72, - mouth: int = 128, - throat: int = 128, - pin: MicroBitDigitalPin = pin0, -) -> None: - """Say English words. - - Example: ``speech.say('hello world')`` - - :param words: The string of words to say. - :param pitch: A number representing the pitch of the voice - :param speed: A number representing the speed of the voice - :param mouth: A number representing the mouth of the voice - :param throat: A number representing the throat of the voice - :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. - If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. - - The result is semi-accurate for English. Override the optional pitch, speed, - mouth and throat settings to change the timbre (quality) of the voice. - - This is a short-hand equivalent of: - ``speech.pronounce(speech.translate(words))`` - - See `the online documentation `_ for detailed information. - """ +Override the optional pitch, speed, mouth and throat settings to change the +timbre (quality) of the voice. + +See `the online documentation `_ for detailed information.""" ... -def sing( - phonemes: str, - pitch: int = 64, - speed: int = 72, - mouth: int = 128, - throat: int = 128, - pin: MicroBitDigitalPin = pin0, -) -> None: - """Sing phonemes. - - Example: ``speech.sing(' /HEHLOW WERLD')`` - - :param phonemes: The string of words to sing. - :param pitch: A number representing the pitch of the voice - :param speed: A number representing the speed of the voice - :param mouth: A number representing the mouth of the voice - :param throat: A number representing the throat of the voice - :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. - If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. - - Override the optional pitch, speed, mouth and throat settings to change - the timbre (quality) of the voice. - - See `the online documentation `_ for detailed information. - """ +def say(words: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: MicroBitDigitalPin=pin0) -> None: + """crwdns330932:0crwdne330932:0 (crwdns330930:0crwdne330930:0) + +Example: ``speech.say('hello world')`` + +:param words: (crwdns330954:0crwdne330954:0) crwdns330956:0crwdne330956:0 +:param pitch: (crwdns330942:0crwdne330942:0) crwdns330944:0crwdne330944:0 +:param speed: (crwdns330946:0crwdne330946:0) crwdns330948:0crwdne330948:0 +:param mouth: (crwdns330934:0crwdne330934:0) crwdns330936:0crwdne330936:0 +:param throat: (crwdns330950:0crwdne330950:0) crwdns330952:0crwdne330952:0 +:param pin: (crwdns330938:0crwdne330938:0) crwdns330940:0``pin0``crwdne330940:0 + +The result is semi-accurate for English. Override the optional pitch, speed, +mouth and throat settings to change the timbre (quality) of the voice. + +This is a short-hand equivalent of: +``speech.pronounce(speech.translate(words))`` + +See `the online documentation `_ for detailed information.""" ... + +def sing(phonemes: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: MicroBitDigitalPin=pin0) -> None: + """crwdns330960:0crwdne330960:0 (crwdns330958:0crwdne330958:0) + +Example: ``speech.sing(' /HEHLOW WERLD')`` + +:param phonemes: (crwdns330966:0crwdne330966:0) crwdns330968:0crwdne330968:0 +:param pitch: (crwdns330974:0crwdne330974:0) crwdns330976:0crwdne330976:0 +:param speed: (crwdns330978:0crwdne330978:0) crwdns330980:0crwdne330980:0 +:param mouth: (crwdns330962:0crwdne330962:0) crwdns330964:0crwdne330964:0 +:param throat: (crwdns330982:0crwdne330982:0) crwdns330984:0crwdne330984:0 +:param pin: (crwdns330970:0crwdne330970:0) crwdns330972:0``pin0``crwdne330972:0 + +Override the optional pitch, speed, mouth and throat settings to change +the timbre (quality) of the voice. + +See `the online documentation `_ for detailed information.""" + ... \ No newline at end of file diff --git a/lang/lol/typeshed/stdlib/struct.pyi b/lang/lol/typeshed/stdlib/struct.pyi index 53b3e0b..8725186 100644 --- a/lang/lol/typeshed/stdlib/struct.pyi +++ b/lang/lol/typeshed/stdlib/struct.pyi @@ -1,65 +1,56 @@ -"""Pack and unpack primitive data types. -""" - +"""crwdns330988:0crwdne330988:0 (crwdns330986:0crwdne330986:0)""" from _typeshed import ReadableBuffer, WriteableBuffer from typing import Any, Tuple, Union def calcsize(fmt: str) -> int: - """Get the number of bytes needed to store the given ``fmt``. + """crwdns330992:0``fmt``crwdne330992:0 (crwdns330990:0crwdne330990:0) - Example: ``struct.calcsize('hf')`` +Example: ``struct.calcsize('hf')`` - :param fmt: A format string. - :return The number of bytes needed to store such a value. - """ +:param fmt: (crwdns330994:0crwdne330994:0) crwdns330996:0crwdne330996:0 +:return The number of bytes needed to store such a value.""" ... def pack(fmt: str, v1: Any, *vn: Any) -> bytes: - """Pack values according to a format string. + """crwdns331000:0crwdne331000:0 (crwdns330998:0crwdne330998:0) - Example: ``struct.pack('hf', 1, 3.1415)`` +Example: ``struct.pack('hf', 1, 3.1415)`` - :param fmt: The format string. - :param v1: The first value. - :param *vn: The remaining values. - :return A bytes object encoding the values. - """ +:param fmt: (crwdns331006:0crwdne331006:0) crwdns331008:0crwdne331008:0 +:param v1: (crwdns331010:0crwdne331010:0) crwdns331012:0crwdne331012:0 +:param *vn: (crwdns331002:0crwdne331002:0) crwdns331004:0crwdne331004:0 +:return A bytes object encoding the values.""" ... -def pack_into( - fmt: str, buffer: WriteableBuffer, offset: int, v1: Any, *vn: Any -) -> None: - """Pack values according to a format string. +def pack_into(fmt: str, buffer: WriteableBuffer, offset: int, v1: Any, *vn: Any) -> None: + """crwdns331016:0crwdne331016:0 (crwdns331014:0crwdne331014:0) - Example: ``struct.pack_info('hf', buffer, 1, 3.1415)`` +Example: ``struct.pack_info('hf', buffer, 1, 3.1415)`` - :param fmt: The format string. - :param buffer: The target buffer to write into. - :param offset: The offset into the buffer. May be negative to count from the end of the buffer. - :param v1: The first value. - :param *vn: The remaining values. - """ +:param fmt: (crwdns331026:0crwdne331026:0) crwdns331028:0crwdne331028:0 +:param buffer: (crwdns331022:0crwdne331022:0) crwdns331024:0crwdne331024:0 +:param offset: (crwdns331030:0crwdne331030:0) crwdns331032:0crwdne331032:0 +:param v1: (crwdns331034:0crwdne331034:0) crwdns331036:0crwdne331036:0 +:param *vn: (crwdns331018:0crwdne331018:0) crwdns331020:0crwdne331020:0""" ... def unpack(fmt: str, data: ReadableBuffer) -> Tuple[Any, ...]: - """Unpack data according to a format string. + """crwdns331040:0crwdne331040:0 (crwdns331038:0crwdne331038:0) - Example: ``v1, v2 = struct.unpack('hf', buffer)`` +Example: ``v1, v2 = struct.unpack('hf', buffer)`` - :param fmt: The format string. - :param data: The data. - :return: A tuple of the unpacked values. - """ +:param fmt: (crwdns331046:0crwdne331046:0) crwdns331048:0crwdne331048:0 +:param data: (crwdns331042:0crwdne331042:0) crwdns331044:0crwdne331044:0 +:return: A tuple of the unpacked values.""" ... -def unpack_from(fmt: str, buffer: ReadableBuffer, offset: int = 0) -> Tuple: - """Unpack data from a buffer according to a format string. +def unpack_from(fmt: str, buffer: ReadableBuffer, offset: int=0) -> Tuple: + """crwdns331052:0crwdne331052:0 (crwdns331050:0crwdne331050:0) - Example: ``v1, v2 = struct.unpack_from('hf', buffer)`` +Example: ``v1, v2 = struct.unpack_from('hf', buffer)`` - :param fmt: The format string. - :param buffer: The source buffer to read from. - :param offset: The offset into the buffer. May be negative to count from the end of the buffer. - :return: A tuple of the unpacked values. - """ - ... +:param fmt: (crwdns331058:0crwdne331058:0) crwdns331060:0crwdne331060:0 +:param buffer: (crwdns331054:0crwdne331054:0) crwdns331056:0crwdne331056:0 +:param offset: (crwdns331062:0crwdne331062:0) crwdns331064:0crwdne331064:0 +:return: A tuple of the unpacked values.""" + ... \ No newline at end of file diff --git a/lang/lol/typeshed/stdlib/sys.pyi b/lang/lol/typeshed/stdlib/sys.pyi index 320bac9..9459fb9 100644 --- a/lang/lol/typeshed/stdlib/sys.pyi +++ b/lang/lol/typeshed/stdlib/sys.pyi @@ -1,43 +1,36 @@ -"""System specific functions""" - +"""crwdns331068:0crwdne331068:0 (crwdns331066:0crwdne331066:0)""" from typing import Any, Dict, List, NoReturn, TextIO, Tuple -def exit(retval: object = ...) -> NoReturn: - """Terminate current program with a given exit code. +def exit(retval: object=...) -> NoReturn: + """crwdns331072:0crwdne331072:0 (crwdns331070:0crwdne331070:0) - Example: ``sys.exit(1)`` +Example: ``sys.exit(1)`` - This function raises a ``SystemExit`` exception. If an argument is given, its - value given as an argument to ``SystemExit``. +This function raises a ``SystemExit`` exception. If an argument is given, its +value given as an argument to ``SystemExit``. - :param retval: The exit code or message. - """ +:param retval: (crwdns331074:0crwdne331074:0) crwdns331076:0crwdne331076:0""" ... def print_exception(exc: Exception) -> None: - """ - Print an exception with a traceback. - - Example: ``sys.print_exception(e)`` + """crwdns331080:0crwdne331080:0 (crwdns331078:0crwdne331078:0) - :param exc: The exception to print +Example: ``sys.print_exception(e)`` - This is simplified version of a function which appears in the - ``traceback`` module in CPython. - """ +:param exc: (crwdns331082:0crwdne331082:0) crwdns331084:0crwdne331084:0 +This is simplified version of a function which appears in the +``traceback`` module in CPython.""" argv: List[str] -"""A mutable list of arguments the current program was started with.""" - +"""crwdns331088:0crwdne331088:0 (crwdns331086:0crwdne331086:0)""" byteorder: str -"""The byte order of the system (``"little"`` or ``"big"``).""" +"""crwdns331092:0``"little"``crwdnd331092:0``"big"``crwdne331092:0 (crwdns331090:0crwdne331090:0)""" class _implementation: name: str version: Tuple[int, int, int] - implementation: _implementation -"""Object with information about the current Python implementation. +"""crwdns331096:0crwdne331096:0 (crwdns331094:0crwdne331094:0) For MicroPython, it has following attributes: @@ -51,13 +44,9 @@ minimal ports). CPython mandates more attributes for this object, but the actual useful bare minimum is implemented in MicroPython. """ - maxsize: int """ -Maximum value which a native integer type can hold on the current platform, -or maximum value representable by MicroPython integer type, if it's smaller -than platform max value (that is the case for MicroPython ports without -long int support). +crwdns331100:0crwdne331100:0 (crwdns331098:0crwdne331098:0) This attribute is useful for detecting "bitness" of a platform (32-bit vs 64-bit, etc.). It's recommended to not compare this attribute to some @@ -77,17 +66,14 @@ value directly, but instead count number of bits in it:: # (e.g. 31) due to peculiarities described above, so use "> 16", # "> 32", "> 64" style of comparisons. """ - modules: Dict[str, Any] -"""Dictionary of loaded modules. +"""crwdns331104:0crwdne331104:0 (crwdns331102:0crwdne331102:0) On some ports, it may not include builtin modules.""" - path: List[str] -"""A mutable list of directories to search for imported modules.""" - +"""crwdns331108:0crwdne331108:0 (crwdns331106:0crwdne331106:0)""" platform: str -"""The platform that MicroPython is running on. +"""crwdns331112:0crwdne331112:0 (crwdns331110:0crwdne331110:0) For OS/RTOS ports, this is usually an identifier of the OS, e.g. ``"linux"``. For baremetal ports it is an identifier of a board, e.g. ``"pyboard"`` for @@ -97,13 +83,11 @@ distinguish one board from another. If you need to check whether your program runs on MicroPython (vs other Python implementation), use ``sys.implementation`` instead. """ - version: str -"""Python language version that this implementation conforms to, as a string.""" - +"""crwdns331116:0crwdne331116:0 (crwdns331114:0crwdne331114:0)""" version_info: Tuple[int, int, int] -"""Python language version that this implementation conforms to, as a tuple of ints. +"""crwdns331120:0crwdne331120:0 (crwdns331118:0crwdne331118:0) Only the first three version numbers (major, minor, micro) are supported and they can be referenced only by index, not by name. -""" +""" \ No newline at end of file diff --git a/lang/lol/typeshed/stdlib/time.pyi b/lang/lol/typeshed/stdlib/time.pyi index 598c483..f2c472d 100644 --- a/lang/lol/typeshed/stdlib/time.pyi +++ b/lang/lol/typeshed/stdlib/time.pyi @@ -1,132 +1,110 @@ -"""Measure time and add delays to programs. -""" - +"""crwdns331124:0crwdne331124:0 (crwdns331122:0crwdne331122:0)""" from typing import Union def sleep(seconds: Union[int, float]) -> None: - """ - Delay a number of seconds. + """crwdns331128:0crwdne331128:0 (crwdns331126:0crwdne331126:0) - Example: ``time.sleep(1)`` +Example: ``time.sleep(1)`` - :param seconds: The number of seconds to sleep for. - Use a floating-point number to sleep for a fractional number of seconds. - """ +:param seconds: (crwdns331130:0crwdne331130:0) crwdns331132:0crwdne331132:0""" ... def sleep_ms(ms: int) -> None: - """ - Delay for given number of milliseconds. + """crwdns331136:0crwdne331136:0 (crwdns331134:0crwdne331134:0) - Example: ``time.sleep_ms(1_000_000)`` +Example: ``time.sleep_ms(1_000_000)`` - :param ms: The number of milliseconds delay (>= 0). - """ +:param ms: (crwdns331138:0crwdne331138:0) crwdns331140:0crwdne331140:0""" ... def sleep_us(us: int) -> None: - """ - Delay for given number of microseconds. + """crwdns331144:0crwdne331144:0 (crwdns331142:0crwdne331142:0) - Example: ``time.sleep_us(1000)`` +Example: ``time.sleep_us(1000)`` - :param us: The number of microseconds delay (>= 0). - """ +:param us: (crwdns331146:0crwdne331146:0) crwdns331148:0crwdne331148:0""" ... def ticks_ms() -> int: - """ - Get an increasing, millisecond counter with an arbitrary reference point, - that wraps around after some value. + """crwdns331152:0crwdne331152:0 (crwdns331150:0crwdne331150:0) - Example: ``time.ticks_ms()`` +Example: ``time.ticks_ms()`` - :return: The counter value in milliseconds. - """ +:return: The counter value in milliseconds.""" ... def ticks_us() -> int: - """ - Get an increasing, microsecond counter with an arbitrary reference point, - that wraps around after some value. + """crwdns331156:0crwdne331156:0 (crwdns331154:0crwdne331154:0) - Example: ``time.ticks_us()`` +Example: ``time.ticks_us()`` - :return: The counter value in microseconds. - """ +:return: The counter value in microseconds.""" ... def ticks_add(ticks: int, delta: int) -> int: - """ - Offset ticks value by a given number, which can be either positive or - negative. + """crwdns331160:0crwdne331160:0 (crwdns331158:0crwdne331158:0) - Example: ``time.ticks_add(time.ticks_ms(), 200)`` +Example: ``time.ticks_add(time.ticks_ms(), 200)`` - Given a ticks value, this function allows to calculate ticks - value delta ticks before or after it, following modular-arithmetic - definition of tick values. +Given a ticks value, this function allows to calculate ticks +value delta ticks before or after it, following modular-arithmetic +definition of tick values. - :param ticks: A ticks value - :param delta: An integer offset +:param ticks: (crwdns331166:0crwdne331166:0) crwdns331168:0crwdne331168:0 +:param delta: (crwdns331162:0crwdne331162:0) crwdns331164:0crwdne331164:0 - Example:: +Example:: - # Find out what ticks value there was 100ms ago - print(ticks_add(time.ticks_ms(), -100)) + # Find out what ticks value there was 100ms ago + print(ticks_add(time.ticks_ms(), -100)) - # Calculate deadline for operation and test for it - deadline = ticks_add(time.ticks_ms(), 200) - while ticks_diff(deadline, time.ticks_ms()) > 0: - do_a_little_of_something() + # Calculate deadline for operation and test for it + deadline = ticks_add(time.ticks_ms(), 200) + while ticks_diff(deadline, time.ticks_ms()) > 0: + do_a_little_of_something() - # Find out TICKS_MAX used by this port - print(ticks_add(0, -1)) - """ + # Find out TICKS_MAX used by this port + print(ticks_add(0, -1))""" ... def ticks_diff(ticks1: int, ticks2: int) -> int: - """ - Measure ticks difference between values returned from - ``time.ticks_ms()`` or ``ticks_us()``, as a signed value - which may wrap around. - - Example: ``time.ticks_diff(scheduled_time, now)`` - - :param ticks1: The value to subtract from - :param ticks2: The value to subtract - - The argument order is the same as for subtraction operator, - ``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. - - ``ticks_diff()`` is designed to accommodate various usage - patterns, among them: - - Polling with timeout. In this case, the order of events is known, and you - will deal only with positive results of :func:`time.ticks_diff()`:: - - # Wait for GPIO pin to be asserted, but at most 500us - start = time.ticks_us() - while pin.value() == 0: - if time.ticks_diff(time.ticks_us(), start) > 500: - raise TimeoutError - - - Scheduling events. In this case, :func:`time.ticks_diff()` result may be - negative if an event is overdue:: - - # This code snippet is not optimized - now = time.ticks_ms() - scheduled_time = task.scheduled_time() - if ticks_diff(scheduled_time, now) > 0: - print("Too early, let's nap") - sleep_ms(ticks_diff(scheduled_time, now)) - task.run() - elif ticks_diff(scheduled_time, now) == 0: - print("Right at time!") - task.run() - elif ticks_diff(scheduled_time, now) < 0: - print("Oops, running late, tell task to run faster!") - task.run(run_faster=True) - """ - ... + """crwdns331172:0``time.ticks_ms()``crwdnd331172:0``ticks_us()``crwdne331172:0 (crwdns331170:0crwdne331170:0) + +Example: ``time.ticks_diff(scheduled_time, now)`` + +:param ticks1: (crwdns331174:0crwdne331174:0) crwdns331176:0crwdne331176:0 +:param ticks2: (crwdns331178:0crwdne331178:0) crwdns331180:0crwdne331180:0 + +The argument order is the same as for subtraction operator, +``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. + +``ticks_diff()`` is designed to accommodate various usage +patterns, among them: + +Polling with timeout. In this case, the order of events is known, and you +will deal only with positive results of :func:`time.ticks_diff()`:: + + # Wait for GPIO pin to be asserted, but at most 500us + start = time.ticks_us() + while pin.value() == 0: + if time.ticks_diff(time.ticks_us(), start) > 500: + raise TimeoutError + + +Scheduling events. In this case, :func:`time.ticks_diff()` result may be +negative if an event is overdue:: + + # This code snippet is not optimized + now = time.ticks_ms() + scheduled_time = task.scheduled_time() + if ticks_diff(scheduled_time, now) > 0: + print("Too early, let's nap") + sleep_ms(ticks_diff(scheduled_time, now)) + task.run() + elif ticks_diff(scheduled_time, now) == 0: + print("Right at time!") + task.run() + elif ticks_diff(scheduled_time, now) < 0: + print("Oops, running late, tell task to run faster!") + task.run(run_faster=True)""" + ... \ No newline at end of file diff --git a/lang/nl/typeshed/stdlib/gc.pyi b/lang/nl/typeshed/stdlib/gc.pyi index 1370abf..b306502 100644 --- a/lang/nl/typeshed/stdlib/gc.pyi +++ b/lang/nl/typeshed/stdlib/gc.pyi @@ -1,73 +1,68 @@ -"""Control the garbage collector""" - +"""Beheer de garbagecollector""" from typing import overload def enable() -> None: - """Enable automatic garbage collection.""" + """Automatische afvalcollectie inschakelen. (inschakelen)""" ... def disable() -> None: - """Disable automatic garbage collection. + """Automatische afvalinzameling uitschakelen. (uitschakelen) - Heap memory can still be allocated, - and garbage collection can still be initiated manually using ``gc.collect``.""" +Heap memory can still be allocated, +and garbage collection can still be initiated manually using ``gc.collect``.""" def collect() -> None: - """Run a garbage collection.""" + """Voer een garbagecollectie uit. (verzamel)""" ... def mem_alloc() -> int: - """Get the number of bytes of heap RAM that are allocated. + """Krijg het aantal bytes van heap RAM die toegewezen zijn. - :return: The number of bytes allocated. +:return: The number of bytes allocated. - This function is MicroPython extension. - """ +This function is MicroPython extension.""" ... def mem_free() -> int: - """Get the number of bytes of available heap RAM, or -1 if this amount is not known. + """Krijg het aantal bytes van beschikbare heap RAM, of -1 als dit bedrag niet bekend is. - :return: The number of bytes free. +:return: The number of bytes free. - This function is MicroPython extension. - """ +This function is MicroPython extension.""" ... @overload def threshold() -> int: - """Query the additional GC allocation threshold. + """Vraag de extra GC toewijzingsdrempel op. (drempelwaarde) - :return: The GC allocation threshold. +:return: The GC allocation threshold. - This function is a MicroPython extension. CPython has a similar - function - ``set_threshold()``, but due to different GC - implementations, its signature and semantics are different. - """ +This function is a MicroPython extension. CPython has a similar +function - ``set_threshold()``, but due to different GC +implementations, its signature and semantics are different.""" ... @overload def threshold(amount: int) -> None: - """Set the additional GC allocation threshold. - - Normally, a collection is triggered only when a new allocation - cannot be satisfied, i.e. on an out-of-memory (OOM) condition. - If this function is called, in addition to OOM, a collection - will be triggered each time after ``amount`` bytes have been - allocated (in total, since the previous time such an amount of bytes - have been allocated). ``amount`` is usually specified as less than the - full heap size, with the intention to trigger a collection earlier than when the - heap becomes exhausted, and in the hope that an early collection will prevent - excessive memory fragmentation. This is a heuristic measure, the effect - of which will vary from application to application, as well as - the optimal value of the ``amount`` parameter. - - A value of -1 means a disabled allocation threshold. - - This function is a MicroPython extension. CPython has a similar - function - ``set_threshold()``, but due to different GC - implementations, its signature and semantics are different. - - :param amount: The number of bytes after which a garbage collection should be triggered. - """ - ... + """Stel de extra GC toewijzingsdrempel in. (drempelwaarde) + +Normally, a collection is triggered only when a new allocation +cannot be satisfied, i.e. on an out-of-memory (OOM) condition. +If this function is called, in addition to OOM, a collection +will be triggered each time after ``amount`` bytes have been +allocated (in total, since the previous time such an amount of bytes +have been allocated). ``amount`` is usually specified as less than the +full heap size, with the intention to trigger a collection earlier than when the +heap becomes exhausted, and in the hope that an early collection will prevent +excessive memory fragmentation. This is a heuristic measure, the effect +of which will vary from application to application, as well as +the optimal value of the ``amount`` parameter. + +A value of -1 means a disabled allocation threshold. + +This function is a MicroPython extension. CPython has a similar +function - ``set_threshold()``, but due to different GC +implementations, its signature and semantics are different. + +:param amount: (bedrag) Het aantal bytes waarna een garbage collectie moet worden geactiveerd.""" + ... \ No newline at end of file diff --git a/lang/nl/typeshed/stdlib/log.pyi b/lang/nl/typeshed/stdlib/log.pyi index c9870fa..b204500 100644 --- a/lang/nl/typeshed/stdlib/log.pyi +++ b/lang/nl/typeshed/stdlib/log.pyi @@ -1,104 +1,89 @@ -"""Log data to your micro:bit V2.""" - +"""Log gegevens in op je micro:bit V2.""" from typing import Literal, Mapping, Optional, Union, overload - MILLISECONDS = 1 -"""Milliseconds timestamp format.""" - +"""Milliseconden tijdstempel formaat. (milliseconden)""" SECONDS = 10 -"""Seconds timestamp format.""" - +"""Seconden tijdstempel formaat. (seconden)""" MINUTES = 600 -"""Minutes timestamp format.""" - +"""Minuten tijdstempel formaat. (minuten)""" HOURS = 36000 -"""Hours timestamp format.""" - +"""Uren tijdstempel formaat. (uren)""" DAYS = 864000 -"""Days timestamp format.""" +"""Dagen tijdstempel formaat. (dagen)""" -def set_labels( - *labels: str, timestamp: Optional[Literal[1, 10, 36000, 864000]] = SECONDS -) -> None: - """Set up the log file header. +def set_labels(*labels: str, timestamp: Optional[Literal[1, 10, 36000, 864000]]=SECONDS) -> None: + """Stel de logbestandheader in. (kies labels) - Example: ``log.set_labels('X', 'Y', 'Z', timestamp=log.MINUTES)`` +Example: ``log.set_labels('X', 'Y', 'Z', timestamp=log.MINUTES)`` - Ideally this function should be called a single time, before any data is - logged, to configure the data table header once. +Ideally this function should be called a single time, before any data is +logged, to configure the data table header once. - If a log file already exists when the program starts, or if this function - is called multiple times, it will check the labels already defined in the - log file. If this function call contains any new labels not already - present, it will generate a new header row with the additional columns. +If a log file already exists when the program starts, or if this function +is called multiple times, it will check the labels already defined in the +log file. If this function call contains any new labels not already +present, it will generate a new header row with the additional columns. - By default the first column contains a timestamp for each row. The time - unit can be selected via the timestamp argument. +By default the first column contains a timestamp for each row. The time +unit can be selected via the timestamp argument. - :param *labels: Any number of positional arguments, each corresponding to an entry in the log header. - :param timestamp: Select the timestamp unit that will be automatically added as the first column in every row. Timestamp values can be one of ``log.MILLISECONDS``, ``log.SECONDS``, ``log.MINUTES``, ``log.HOURS``, ``log.DAYS`` or ``None`` to disable the timestamp. The default value is ``log.SECONDS``. - """ +:param *labels: Een willekeurig aantal positionele argumenten, elk corresponderend aan een vermelding in de log header. +:param timestamp: (tijdstempel) Selecteer de eenheid van de tijdsaanduiding die automatisch als eerste kolom in elke rij wordt toegevoegd. Tijdstempel waarden kunnen een van ``log.MILLISECONDS``, ``log.SECONDS``, ``log.MINUTES``, , , ``log.HOURS``, ``log.DAYS`` of ``None`` om de tijdstempel uit te schakelen. De standaardwaarde is ``log.SECONDS``.""" ... @overload -def add( - data_dictionary: Optional[Mapping[str, Union[str, int, float]]], -) -> None: - """Add a data row to the log by passing a dictionary of headers and values. +def add(data_dictionary: Optional[Mapping[str, Union[str, int, float]]]) -> None: + """Voeg een gegevensrij toe aan de log door een woordenboek van koppen en waarden te passeren. (toevoegen) - Example: ``log.add({ 'temp': temperature() })`` +Example: ``log.add({ 'temp': temperature() })`` - Each call to this function adds a row to the log. +Each call to this function adds a row to the log. - New labels not previously specified via the set_labels function, or by a - previous call to this function, will trigger a new header entry to be added - to the log with the extra labels. +New labels not previously specified via the set_labels function, or by a +previous call to this function, will trigger a new header entry to be added +to the log with the extra labels. - Labels previously specified and not present in a call to this function will - be skipped with an empty value in the log row. +Labels previously specified and not present in a call to this function will +be skipped with an empty value in the log row. - :param data_dictionary: The data to log as a dictionary with a key for each header. - """ +:param data_dictionary: (gegevenswoordenboek) De gegevens die moeten worden geregistreerd als woordenboek met een sleutel voor elke header.""" ... @overload def add(**kwargs: Union[str, int, float]) -> None: - """Add a data row to the log using keyword arguments. + """Voeg een gegevensrij toe aan het logboek met behulp van trefwoordargumenten. (toevoegen) - Example: ``log.add(temp=temperature())`` +Example: ``log.add(temp=temperature())`` - Each call to this function adds a row to the log. +Each call to this function adds a row to the log. - New labels not previously specified via the set_labels function, or by a - previous call to this function, will trigger a new header entry to be added - to the log with the extra labels. +New labels not previously specified via the set_labels function, or by a +previous call to this function, will trigger a new header entry to be added +to the log with the extra labels. - Labels previously specified and not present in a call to this function will - be skipped with an empty value in the log row. - """ +Labels previously specified and not present in a call to this function will +be skipped with an empty value in the log row.""" ... def delete(full=False): - """Deletes the contents of the log, including headers. + """Verwijdert de inhoud van het log, inclusief headers. (verwijderen) - Example: ``log.delete()`` +Example: ``log.delete()`` - To add the log headers again the ``set_labels`` function should to be called after this function. +To add the log headers again the ``set_labels`` function should to be called after this function. - There are two erase modes; “full” completely removes the data from the physical storage, - and “fast” invalidates the data without removing it. +There are two erase modes; “full” completely removes the data from the physical storage, +and “fast” invalidates the data without removing it. - :param full: ``True`` selects a “full” erase and ``False`` selects the “fast” erase method. - """ +:param full: (volledig) ``True`` selecteert een "volledige" wissen en ``False`` selecteert de "snel" wis methode.""" ... def set_mirroring(serial: bool): - """Configure mirroring of the data logging activity to the serial output. + """Configureer het spiegelen van de data logging activiteit naar de seriële uitgang. (stel spiegelen in) - Example: ``log.set_mirroring(True)`` +Example: ``log.set_mirroring(True)`` - Serial mirroring is disabled by default. When enabled, it will print to serial each row logged into the log file. +Serial mirroring is disabled by default. When enabled, it will print to serial each row logged into the log file. - :param serial: ``True`` enables mirroring data to the serial output. - """ - ... +:param serial: (serieel) ``True`` maakt het spiegelen van gegevens naar de seriële uitvoer mogelijk.""" + ... \ No newline at end of file diff --git a/lang/nl/typeshed/stdlib/machine.pyi b/lang/nl/typeshed/stdlib/machine.pyi index 2e82f5b..d5d2568 100644 --- a/lang/nl/typeshed/stdlib/machine.pyi +++ b/lang/nl/typeshed/stdlib/machine.pyi @@ -1,97 +1,84 @@ -"""Low-level utilities. -""" +"""Hulpprogramma's op laag niveau.""" from typing import Any from .microbit import MicroBitDigitalPin def unique_id() -> bytes: - """Get a byte string with a unique identifier of a board. + """Krijg een byte string met een uniek id van een bord. (uniek id) - Example: ``machine.unique_id()`` +Example: ``machine.unique_id()`` - :return: An identifier that varies from one board instance to another. - """ +:return: An identifier that varies from one board instance to another.""" ... def reset() -> None: - """Reset the device in a manner similar to pushing the external RESET button. + """Reset het apparaat op een manier die lijkt op de externe RESET knop. - Example: ``machine.reset()`` - """ +Example: ``machine.reset()``""" ... def freq() -> int: - """Get the CPU frequency in hertz. + """Krijg de CPU frequentie in Hertz. (frequentie) - Example: ``machine.freq()`` +Example: ``machine.freq()`` - :return: The CPU frequency. - """ +:return: The CPU frequency.""" ... def disable_irq() -> Any: - """Disable interrupt requests. + """Interruptie verzoeken uitschakelen. (irq uitschakelen) - Example: ``interrupt_state = machine.disable_irq()`` +Example: ``interrupt_state = machine.disable_irq()`` - :return: the previous IRQ state which should be considered an opaque value +:return: the previous IRQ state which should be considered an opaque value - The return value should be passed to the ``enable_irq`` function to restore - interrupts to their original state. - """ +The return value should be passed to the ``enable_irq`` function to restore +interrupts to their original state.""" ... def enable_irq(state: Any) -> None: - """Re-enable interrupt requests. + """Zet interruptie verzoeken opnieuw aan. (irq inschakelen) - Example: ``machine.enable_irq(interrupt_state)`` +Example: ``machine.enable_irq(interrupt_state)`` - :param state: The value that was returned from the most recent call to the ``disable_irq`` function. - """ +:param state: (staat) De waarde die is teruggestuurd van de meest recente oproep naar de ``disable_irq`` functie.""" ... -def time_pulse_us( - pin: MicroBitDigitalPin, pulse_level: int, timeout_us: int = 1000000 -) -> int: - """Time a pulse on a pin. +def time_pulse_us(pin: MicroBitDigitalPin, pulse_level: int, timeout_us: int=1000000) -> int: + """Time een puls op een pin. (tijd pulse us) - Example: ``time_pulse_us(pin0, 1)`` +Example: ``time_pulse_us(pin0, 1)`` - If the current input value of the pin is different to ``pulse_level``, the - function first waits until the pin input becomes equal to - ``pulse_level``, then times the duration that the pin is equal to - ``pulse_level``. If the pin is already equal to ``pulse_level`` then timing - starts straight away. +If the current input value of the pin is different to ``pulse_level``, the +function first waits until the pin input becomes equal to +``pulse_level``, then times the duration that the pin is equal to +``pulse_level``. If the pin is already equal to ``pulse_level`` then timing +starts straight away. - :param pin: The pin to use - :param pulse_level: 0 to time a low pulse or 1 to time a high pulse - :param timeout_us: A microsecond timeout - :return: The duration of the pulse in microseconds, or -1 for a timeout waiting for the level to match ``pulse_level``, or -2 on timeout waiting for the pulse to end - """ +:param pin: De pin om te gebruiken +:param pulse_level: (puls niveau) 0 om een lage puls te tikken of 1 om een hoge puls te tikken +:param timeout_us: Een microseconde time-out +:return: The duration of the pulse in microseconds, or -1 for a timeout waiting for the level to match ``pulse_level``, or -2 on timeout waiting for the pulse to end""" ... class mem: - """The class for the ``mem8``, ``mem16`` and ``mem32`` memory views.""" + """De klasse van de ``mem8``, ``mem16`` en ``mem32`` geheugenweergaven.""" def __getitem__(self, address: int) -> int: - """Access a value from memory. + """Toegang tot een waarde uit het geheugen. - :param address: The memory address. - :return: The value at that address as an integer. - """ +:param address: (adres) Het geheugenadres. +:return: The value at that address as an integer.""" ... + def __setitem__(self, address: int, value: int) -> None: - """Set a value at the given address. + """Stel een waarde in op het opgegeven adres. - :param address: The memory address. - :param value: The integer value to set. - """ +:param address: (adres) Het geheugen adres. +:param value: (waarde) De integerwaarde die moet worden ingesteld.""" ... - mem8: mem -"""8-bit (byte) view of memory.""" - +"""8-bit (byte) weergave van het geheugen.""" mem16: mem -"""16-bit view of memory.""" - +"""16-bit (byte) weergave van het geheugen.""" mem32: mem -"""32-bit view of memory.""" +"""32-bit (byte) weergave van het geheugen.""" \ No newline at end of file diff --git a/lang/nl/typeshed/stdlib/math.pyi b/lang/nl/typeshed/stdlib/math.pyi index f82d4de..38397fc 100644 --- a/lang/nl/typeshed/stdlib/math.pyi +++ b/lang/nl/typeshed/stdlib/math.pyi @@ -1,273 +1,246 @@ -"""Mathematical functions. -""" - +"""Wiskundige functies. (wiskunde)""" from typing import Tuple def acos(x: float) -> float: - """Calculate the inverse cosine. + """Bereken de inverse cosinus. - Example: ``math.acos(1)`` +Example: ``math.acos(1)`` - :param x: A number - :return: The inverse cosine of ``x`` - """ +:param x: (х) Een getal +:return: The inverse cosine of ``x``""" ... def asin(x: float) -> float: - """Calculate the inverse sine. + """Bereken de inverse sinus. - Example: ``math.asin(0)`` +Example: ``math.asin(0)`` - :param x: A number - :return: The inverse sine of ``x`` - """ +:param x: (х) Een getal +:return: The inverse sine of ``x``""" ... def atan(x: float) -> float: - """Calculate the inverse tangent. + """Bereken de inverse tangens. - Example: ``math.atan(0)`` +Example: ``math.atan(0)`` - :param x: A number - :return: The inverse tangent of ``x`` - """ +:param x: (х) Een getal +:return: The inverse tangent of ``x``""" ... def atan2(y: float, x: float) -> float: - """Calculate the principal value of the inverse tangent of ``y/x``. + """Bereken de hoofdwaarde van de inverse tangens van ``y/x``. - Example: ``math.atan2(0, -1)`` +Example: ``math.atan2(0, -1)`` - :param y: A number - :param x: A number - :return: The principal value of the inverse tangent of ``y/x`` - """ +:param y: (х) Een getal +:param x: (х) Een getal +:return: The principal value of the inverse tangent of ``y/x``""" ... def ceil(x: float) -> float: - """Round a number towards positive infinity. + """Rond een getal af op een positief oneindig. (plafond) - Example: ``math.ceil(0.1)`` +Example: ``math.ceil(0.1)`` - :param x: A number - :return: ``x`` rounded towards positive infinity. - """ +:param x: (х) Een getal +:return: ``x`` rounded towards positive infinity.""" ... def copysign(x: float, y: float) -> float: - """Calculate ``x`` with the sign of ``y``. + """Bereken ``x`` met de teken van ``y``. - Example: ``math.copysign(1, -1)`` +Example: ``math.copysign(1, -1)`` - :param x: A number - :param y: The source of the sign for the return value - :return: ``x`` with the sign of ``y`` - """ +:param x: (х) Een getal +:param y: De bron van het teken voor de retourwaarde +:return: ``x`` with the sign of ``y``""" ... def cos(x: float) -> float: - """Calculate the cosine of ``x``. + """Bereken de cosinus van ``x``. - Example: ``math.cos(0)`` +Example: ``math.cos(0)`` - :param x: A number - :return: The cosine of ``x`` - """ +:param x: (х) Een getal +:return: The cosine of ``x``""" ... def degrees(x: float) -> float: - """Convert radians to degrees. + """radialen converteren naar graden: (graden) - Example: ``math.degrees(2 * math.pi)`` +Example: ``math.degrees(2 * math.pi)`` - :param x: A value in radians - :return: The value converted to degrees""" +:param x: (х) Een waarde in radialen +:return: The value converted to degrees""" ... def exp(x: float) -> float: - """Calculate the exponential of ``x``. + """Bereken de exponentiële van ``x``. - Example: ``math.exp(1)`` +Example: ``math.exp(1)`` - :param x: A number - :return: The exponential of ``x``. - """ +:param x: (х) Een getal +:return: The exponential of ``x``.""" ... def fabs(x: float) -> float: - """Return the absolute value of ``x``. + """Geeft de absolute waarde van ``x``. - Example: ``math.fabs(-0.1)`` +Example: ``math.fabs(-0.1)`` - :param x: A number - :return: The absolute value of ``x`` - """ +:param x: (х) Een getal +:return: The absolute value of ``x``""" ... def floor(x: float) -> int: - """Round a number towards negative infinity. + """Rond een getal af op een negatief oneindig. - Example: ``math.floor(0.9)`` +Example: ``math.floor(0.9)`` - :param x: A number - :return: ``x`` rounded towards negative infinity. - """ +:param x: (х) Een getal +:return: ``x`` rounded towards negative infinity.""" ... def fmod(x: float, y: float) -> float: - """Calculate the remainder of ``x/y``. + """Bereken de rest van ``x/y``. - Example: ``math.fmod(10, 3)`` +Example: ``math.fmod(10, 3)`` - :param x: The numerator - :param y: The denominator - """ +:param x: (х) De nummeraar +:param y: De noemer""" ... def frexp(x: float) -> Tuple[float, int]: - """Decomposes a floating-point number into its mantissa and exponent. + """Ontleedt een getal met drijvende komma in zijn mantisse en exponent. - Example: ``mantissa, exponent = math.frexp(2)`` +Example: ``mantissa, exponent = math.frexp(2)`` - The returned value is the tuple ``(m, e)`` such that ``x == m * 2**e`` - exactly. If ``x == 0`` then the function returns ``(0.0, 0)``, otherwise - the relation ``0.5 <= abs(m) < 1`` holds. +The returned value is the tuple ``(m, e)`` such that ``x == m * 2**e`` +exactly. If ``x == 0`` then the function returns ``(0.0, 0)``, otherwise +the relation ``0.5 <= abs(m) < 1`` holds. - :param x: A floating-point number - :return: A tuple of length two containing its mantissa then exponent - """ +:param x: (х) Getal met drijvende komma +:return: A tuple of length two containing its mantissa then exponent""" ... def isfinite(x: float) -> bool: - """Check if a value is finite. + """Controleer of een waarde eindig is. (is eindig) - Example: ``math.isfinite(float('inf'))`` +Example: ``math.isfinite(float('inf'))`` - :param x: A number. - :return: ``True`` if ``x`` is finite, ``False`` otherwise. - """ +:param x: (х) Een getal. +:return: ``True`` if ``x`` is finite, ``False`` otherwise.""" ... def isinf(x: float) -> bool: - """Check if a value is infinite. + """Controleer of een waarde oneindig is. - Example: ``math.isinf(float('-inf'))`` +Example: ``math.isinf(float('-inf'))`` - :param x: A number. - :return: ``True`` if ``x`` is infinite, ``False`` otherwise. - """ +:param x: (х) Een getal. +:return: ``True`` if ``x`` is infinite, ``False`` otherwise.""" ... def isnan(x: float) -> bool: - """Check if a value is not-a-number (NaN). + """Check if is een waarde is geen getal (NaN). - Example: ``math.isnan(float('nan'))`` +Example: ``math.isnan(float('nan'))`` - :param x: A number - :return: ``True`` if ``x`` is not-a-number (NaN), ``False`` otherwise.""" +:param x: (х) Een getal +:return: ``True`` if ``x`` is not-a-number (NaN), ``False`` otherwise.""" ... def ldexp(x: float, exp: int) -> float: - """Calculate ``x * (2**exp)``. + """Bereken ``x * (2**exp)``. - Example: ``math.ldexp(0.5, 2)`` +Example: ``math.ldexp(0.5, 2)`` - :param x: A number - :param exp: Integer exponent - :return: ``x * (2**exp)`` - """ +:param x: (х) Een getal +:param exp: Integer exponent +:return: ``x * (2**exp)``""" ... -def log(x: float, base: float = e) -> float: - """Calculate the logarithm of ``x`` to the given base (defaults to natural logorithm). +def log(x: float, base: float=e) -> float: + """Bereken het logaritme van ``x`` naar de opgegeven basis (standaard is het natuurlijke logalgoritme). - Example: ``math.log(math.e)`` +Example: ``math.log(math.e)`` - With one argument, return the natural logarithm of x (to base e). +With one argument, return the natural logarithm of x (to base e). - With two arguments, return the logarithm of x to the given base, calculated as ``log(x)/log(base)``. +With two arguments, return the logarithm of x to the given base, calculated as ``log(x)/log(base)``. - :param x: A number - :param base: The base to use - :return: The natural logarithm of ``x`` - """ +:param x: (х) Een getal +:param base: (grondtal) Het grondtal om te gebruiken +:return: The natural logarithm of ``x``""" ... def modf(x: float) -> Tuple[float, float]: - """Calculate the fractional and integral parts of ``x``. + """Bereken de fractionele en integrale onderdelen van ``x``. - Example: ``fractional, integral = math.modf(1.5)`` +Example: ``fractional, integral = math.modf(1.5)`` - :param x: A number - :return: A tuple of two floats representing the fractional then integral parts of ``x``. +:param x: (х) Een getal +:return: A tuple of two floats representing the fractional then integral parts of ``x``. - Both the fractional and integral values have the same sign as ``x``. - """ +Both the fractional and integral values have the same sign as ``x``.""" ... def pow(x: float, y: float) -> float: - """Returns ``x`` to the power of ``y``. + """Retourneert ``x`` naar de kracht van ``y``. - Example: ``math.pow(4, 0.5)`` +Example: ``math.pow(4, 0.5)`` - :param x: A number - :param y: The exponent - :return: ``x`` to the power of ``y`` - """ +:param x: (х) Een getal +:param y: De exponent +:return: ``x`` to the power of ``y``""" ... def radians(x: float) -> float: - """Convert a degrees to radians. + """Converteer graden naar radialen. (radialen) - Example: ``math.radians(360)`` +Example: ``math.radians(360)`` - :param x: A value in degrees - :return: The value converted to radians - """ +:param x: (х) Een waarde in graden +:return: The value converted to radians""" ... def sin(x: float) -> float: - """Calculate the sine of ``x``. + """Bereken de sinus van ``x``. - Example: ``math.sin(math.pi/2)`` +Example: ``math.sin(math.pi/2)`` - :param x: A number - :return: The sine of ``x`` - """ +:param x: (х) Een getal +:return: The sine of ``x``""" ... def sqrt(x: float) -> float: - """Calculate the square root of ``x``. + """Bereken de wortel van ``x``. (wortel) - Example: ``math.sqrt(4)`` +Example: ``math.sqrt(4)`` - :param x: A number - :return: The square root of ``x`` - """ +:param x: (х) Een getal +:return: The square root of ``x``""" ... def tan(x: float) -> float: - """Calculate the tangent of ``x``. + """Bereken de tangens van ``x``. - Example: ``math.tan(0)`` +Example: ``math.tan(0)`` - :param x: A number - :return: The tangent of ``x``. - """ +:param x: (х) Een getal +:return: The tangent of ``x``.""" ... def trunc(x: float) -> int: - """Round a number towards 0. + """Rond een getal af naar 0. - Example: ``math.trunc(-0.9)`` +Example: ``math.trunc(-0.9)`` - :param x: A number - :return: ``x`` rounded towards zero. - """ +:param x: (х) Een getal +:return: ``x`` rounded towards zero.""" ... - e: float -"""Base of the natural logarithm""" - +"""Basis van het natuurlijke logaritme""" pi: float -"""The ratio of a circle's circumference to its diameter""" +"""De omtrek van een cirkel tot de diameter""" \ No newline at end of file diff --git a/lang/nl/typeshed/stdlib/microbit/__init__.pyi b/lang/nl/typeshed/stdlib/microbit/__init__.pyi index f12158f..aa650d8 100644 --- a/lang/nl/typeshed/stdlib/microbit/__init__.pyi +++ b/lang/nl/typeshed/stdlib/microbit/__init__.pyi @@ -1,11 +1,6 @@ -"""Pins, images, sounds, temperature and volume. -""" - +"""Pinnen, afbeeldingen, geluiden, temperatuur en volume.""" from typing import Any, Callable, List, Optional, Tuple, Union, overload - from _typeshed import ReadableBuffer - -# V2 only from . import accelerometer as accelerometer from . import audio as audio from . import compass as compass @@ -16,831 +11,701 @@ from . import speaker as speaker from . import spi as spi from . import uart as uart -def run_every( - callback: Optional[Callable[[], None]] = None, - days: int = 0, - h: int = 0, - min: int = 0, - s: int = 0, - ms: int = 0, -) -> Callable[[Callable[[], None]], Callable[[], None]]: - """Schedule to run a function at the interval specified by the time arguments **V2 only**. +def run_every(callback: Optional[Callable[[], None]]=None, days: int=0, h: int=0, min: int=0, s: int=0, ms: int=0) -> Callable[[Callable[[], None]], Callable[[], None]]: + """Plan om een functie uit te voeren volgens het interval dat gespecificeerd is door het time argument **V2 alleen**. (draai elke) - Example: ``run_every(my_logging, min=5)`` +Example: ``run_every(my_logging, min=5)`` - ``run_every`` can be used in two ways: +``run_every`` can be used in two ways: - As a Decorator - placed on top of the function to schedule. For example:: +As a Decorator - placed on top of the function to schedule. For example:: - @run_every(h=1, min=20, s=30, ms=50) - def my_function(): - # Do something here + @run_every(h=1, min=20, s=30, ms=50) + def my_function(): + # Do something here - As a Function - passing the callback as a positional argument. For example:: +As a Function - passing the callback as a positional argument. For example:: - def my_function(): - # Do something here - run_every(my_function, s=30) + def my_function(): + # Do something here + run_every(my_function, s=30) - Each argument corresponds to a different time unit and they are additive. - So ``run_every(min=1, s=30)`` schedules the callback every minute and a half. +Each argument corresponds to a different time unit and they are additive. +So ``run_every(min=1, s=30)`` schedules the callback every minute and a half. - When an exception is thrown inside the callback function it deschedules the - function. To avoid this you can catch exceptions with ``try/except``. +When an exception is thrown inside the callback function it deschedules the +function. To avoid this you can catch exceptions with ``try/except``. - :param callback: Function to call at the provided interval. Omit when using as a decorator. - :param days: Sets the day mark for the scheduling. - :param h: Sets the hour mark for the scheduling. - :param min: Sets the minute mark for the scheduling. - :param s: Sets the second mark for the scheduling. - :param ms: Sets the millisecond mark for the scheduling. - """ +:param callback: Functie om op te roepen bij de meegeleverde interval. Weglaten wanneer je als decorator gebruikt. +:param days: (dagen) Stelt de dag markering in voor de planning. +:param h: (uur) Stelt de urenmarkering in voor de planning. +:param min: Stelt de minuut markering in voor de planning. +:param s: Stelt de seconde markering in voor de planning. +:param ms: Stelt de milliseconde markering in voor de planning.""" def panic(n: int) -> None: - """Enter a panic mode. + """Voer een paniekmodus in. (paniek) - Example: ``panic(127)`` +Example: ``panic(127)`` - :param n: An arbitrary integer <= 255 to indicate a status. +:param n: Een willekeurig geheel getal <= 255 om een status aan te geven. - Requires restart. - """ +Requires restart.""" def reset() -> None: - """Restart the board.""" - + """Herstart het bord.""" @overload def scale(value: float, from_: Tuple[float, float], to: Tuple[int, int]) -> int: - """Converts a value from a range to an integer range. + """Zet een waarde om van een bereik naar een ander bereik van natuurlijke getallen. (schaal) - Example: ``volume = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255))`` +Example: ``volume = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255))`` - For example, to convert an accelerometer X value to a speaker volume. +For example, to convert an accelerometer X value to a speaker volume. - If one of the numbers in the ``to`` parameter is a floating point - (i.e a decimal number like ``10.0``), this function will return a - floating point number. +If one of the numbers in the ``to`` parameter is a floating point +(i.e a decimal number like ``10.0``), this function will return a +floating point number. - temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0)) + temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0)) - :param value: A number to convert. - :param from_: A tuple to define the range to convert from. - :param to: A tuple to define the range to convert to. - :return: The ``value`` converted to the ``to`` range. - """ +:param value: (waarde) Een getal om te converteren +:param from_: (van) Een getallen paar wat het bereik aangeeft vanwaar je wilt converteren +:param to: (naar) Een getallen paar om het bereik te definiëren waar je naar wilt converteren. +:return: The ``value`` converted to the ``to`` range.""" @overload def scale(value: float, from_: Tuple[float, float], to: Tuple[float, float]) -> float: - """Converts a value from a range to a floating point range. + """Zet een waarde om van een bereik naar een ander bereik van decimale getallen. (schaal) - Example: ``temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0))`` +Example: ``temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0))`` - For example, to convert temperature from a Celsius scale to Fahrenheit. +For example, to convert temperature from a Celsius scale to Fahrenheit. - If one of the numbers in the ``to`` parameter is a floating point - (i.e a decimal number like ``10.0``), this function will return a - floating point number. - If they are both integers (i.e ``10``), it will return an integer:: +If one of the numbers in the ``to`` parameter is a floating point +(i.e a decimal number like ``10.0``), this function will return a +floating point number. +If they are both integers (i.e ``10``), it will return an integer:: - returns_int = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255)) + returns_int = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255)) - :param value: A number to convert. - :param from_: A tuple to define the range to convert from. - :param to: A tuple to define the range to convert to. - :return: The ``value`` converted to the ``to`` range. - """ +:param value: (waarde) Een getal om te converteren +:param from_: (van) Een getallen paar wat het bereik aangeeft vanwaar je wilt converteren +:param to: (naar) Een getallen paar om het bereik te definiëren waar je naar wilt converteren. +:return: The ``value`` converted to the ``to`` range.""" def sleep(n: float) -> None: - """Wait for ``n`` milliseconds. + """Wacht op ``n`` milliseconden. (slapen) - Example: ``sleep(1000)`` +Example: ``sleep(1000)`` - :param n: The number of milliseconds to wait +:param n: Het aantal milliseconden te wachten - One second is 1000 milliseconds, so:: +One second is 1000 milliseconds, so:: - microbit.sleep(1000) + microbit.sleep(1000) - will pause the execution for one second. - """ +will pause the execution for one second.""" def running_time() -> int: - """Get the running time of the board. + """Bekijk de looptijd van het bord. (looptijd) - :return: The number of milliseconds since the board was switched on or restarted. - """ +:return: The number of milliseconds since the board was switched on or restarted.""" def temperature() -> int: - """Get the temperature of the micro:bit in degrees Celsius.""" + """Krijg de temperatuur van de micro:bit in graden Celsius. (temperatuur)""" def set_volume(v: int) -> None: - """Sets the volume. + """Stelt het volume in. (stel volume in) - Example: ``set_volume(127)`` +Example: ``set_volume(127)`` - :param v: a value between 0 (low) and 255 (high). +:param v: een waarde tussen 0 (laag) en 255 (hoog). - Out of range values will be clamped to 0 or 255. +Out of range values will be clamped to 0 or 255. - **V2** only. - """ +**V2** only.""" ... class Button: - """The class for the buttons ``button_a`` and ``button_b``.""" + """De klasse voor de knoppen ``button_a`` en ``button_b``. (knop)""" def is_pressed(self) -> bool: - """Check if the button is pressed. + """Controleer of op de knop wordt gedrukt. (is ingedrukt) - :return: ``True`` if the specified button ``button`` is pressed, and ``False`` otherwise. - """ +:return: ``True`` if the specified button ``button`` is pressed, and ``False`` otherwise.""" ... + def was_pressed(self) -> bool: - """Check if the button was pressed since the device started or the last time this method was called. + """Controleer of de knop was ingedrukt sinds het apparaat is gestart of de laatste keer dat deze methode is gebruikt. (was ingedrukt) - Calling this method will clear the press state so - that the button must be pressed again before this method will return - ``True`` again. +Calling this method will clear the press state so +that the button must be pressed again before this method will return +``True`` again. - :return: ``True`` if the specified button ``button`` was pressed, and ``False`` otherwise - """ +:return: ``True`` if the specified button ``button`` was pressed, and ``False`` otherwise""" ... + def get_presses(self) -> int: - """Get the running total of button presses, and resets this total - to zero before returning. + """Krijg het totale aantal ingedrukte knoppen en reset dit totaal +naar nul voordat u terugkeert. (zie knop acties) - :return: The number of presses since the device started or the last time this method was called - """ +:return: The number of presses since the device started or the last time this method was called""" ... - button_a: Button -"""The left button ``Button`` object.""" - +"""Het object van de linker knop ``Button``. (knop a)""" button_b: Button -"""The right button ``Button`` object.""" +"""Het object van de rechter knop ``Button``. (knop b)""" class MicroBitDigitalPin: - """A digital pin. - - Some pins support analog and touch features using the ``MicroBitAnalogDigitalPin`` and ``MicroBitTouchPin`` subclasses. - """ + """Een digitale pin +Some pins support analog and touch features using the ``MicroBitAnalogDigitalPin`` and ``MicroBitTouchPin`` subclasses.""" NO_PULL: int PULL_UP: int PULL_DOWN: int + def read_digital(self) -> int: - """Get the digital value of the pin. + """Haal de digitale waarde van de pincode op. (digitaal lezen) - Example: ``value = pin0.read_digital()`` +Example: ``value = pin0.read_digital()`` - :return: 1 if the pin is high, and 0 if it's low. - """ +:return: 1 if the pin is high, and 0 if it's low.""" ... + def write_digital(self, value: int) -> None: - """Set the digital value of the pin. + """Stel de digitale waarde van de pin in. (digitaal schrijven) - Example: ``pin0.write_digital(1)`` +Example: ``pin0.write_digital(1)`` - :param value: 1 to set the pin high or 0 to set the pin low""" +:param value: (waarde) 1 om de pin hoog of 0 om de pin laag in te stellen""" ... + def set_pull(self, value: int) -> None: - """Set the pull state to one of three possible values: ``PULL_UP``, ``PULL_DOWN`` or ``NO_PULL``. + """Zet de pull-status op een van de drie mogelijke waarden: ``PULL_UP``, ``PULL_DOWN`` of ``NO_PULL``. (pull instellen) - Example: ``pin0.set_pull(pin0.PULL_UP)`` +Example: ``pin0.set_pull(pin0.PULL_UP)`` - :param value: The pull state from the relevant pin, e.g. ``pin0.PULL_UP``. - """ +:param value: (waarde) De pull-status van de relevante pincode, bijvoorbeeld ``pin0.PULL_UP``.""" ... + def get_pull(self) -> int: - """Get the pull state on a pin. + """Bekijk de pull status van een pin. (pull instellen) - Example: ``pin0.get_pull()`` +Example: ``pin0.get_pull()`` - :return: ``NO_PULL``, ``PULL_DOWN``, or ``PULL_UP`` +:return: ``NO_PULL``, ``PULL_DOWN``, or ``PULL_UP`` - These are set using the ``set_pull()`` method or automatically configured - when a pin mode requires it. - """ +These are set using the ``set_pull()`` method or automatically configured +when a pin mode requires it.""" ... + def get_mode(self) -> str: - """Returns the pin mode. + """Geeft de pinmodus weer. (Bekijk modus) - Example: ``pin0.get_mode()`` +Example: ``pin0.get_mode()`` - When a pin is used for a specific function, like - writing a digital value, or reading an analog value, the pin mode - changes. +When a pin is used for a specific function, like +writing a digital value, or reading an analog value, the pin mode +changes. - :return: ``"unused"``, ``"analog"``, ``"read_digital"``, ``"write_digital"``, ``"display"``, ``"button"``, ``"music"``, ``"audio"``, ``"touch"``, ``"i2c"``, or ``"spi"`` - """ +:return: ``"unused"``, ``"analog"``, ``"read_digital"``, ``"write_digital"``, ``"display"``, ``"button"``, ``"music"``, ``"audio"``, ``"touch"``, ``"i2c"``, or ``"spi"``""" ... + def write_analog(self, value: int) -> None: - """Output a PWM signal on the pin, with the duty cycle proportional to ``value``. + """Voer een PWM-signaal uit op de pin, waarbij de taakcyclus proportioneel is aan ``value``. (analoge schrijven) + +Example: ``pin0.write_analog(254)`` - Example: ``pin0.write_analog(254)`` +:param value: (waarde) Een geheel getal of een zwevend punt getal tussen 0 (0% tariefcyclus) en 1023 (100% belasting).""" - :param value: 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. + """Stel de periode in van het PWM-signaal dat uitgevoerd wordt naar ``period`` in milliseconden. (gebruik analoge periode) - Example: ``pin0.set_analog_period(10)`` +Example: ``pin0.set_analog_period(10)`` + +:param period: (periode) De periode in milliseconden met een minimale geldige waarde van 1 ms.""" - :param period: The period in milliseconds with a minimum valid value of 1ms. - """ def set_analog_period_microseconds(self, period: int) -> None: - """Set the period of the PWM signal being output to ``period`` in microseconds. + """Stel de periode in van het PWM-signaal dat uitgevoerd wordt naar ``period`` in milliseconden. (microseconden analoge periode instellen) - Example: ``pin0.set_analog_period_microseconds(512)`` +Example: ``pin0.set_analog_period_microseconds(512)`` - :param period: The period in microseconds with a minimum valid value of 256µs. - """ +:param period: (periode) De periode in microseconden met een minimumwaarde van 256 mres.""" class MicroBitAnalogDigitalPin(MicroBitDigitalPin): - """A pin with analog and digital features.""" + """Een pin met analoge en digitale functies.""" def read_analog(self) -> int: - """Read the voltage applied to the pin. + """Lees de spanning op de pin. (lees analoge) - Example: ``pin0.read_analog()`` +Example: ``pin0.read_analog()`` - :return: An integer between 0 (meaning 0V) and 1023 (meaning 3.3V). - """ +:return: An integer between 0 (meaning 0V) and 1023 (meaning 3.3V).""" class MicroBitTouchPin(MicroBitAnalogDigitalPin): - """A pin with analog, digital and touch features.""" - + """Een pin met analoge, digitale en touch functies.""" CAPACITIVE: int RESISTIVE: int + def is_touched(self) -> bool: - """Check if the pin is being touched. + """Controleer of de pin aangeraakt wordt. (is aangeraakt) - Example: ``pin0.is_touched()`` +Example: ``pin0.is_touched()`` - The default touch mode for the pins on the edge connector is ``resistive``. - The default for the logo pin **V2** is ``capacitive``. +The default touch mode for the pins on the edge connector is ``resistive``. +The default for the logo pin **V2** is ``capacitive``. - **Resistive touch** - This test is done by measuring how much resistance there is between the - pin and ground. A low resistance gives a reading of ``True``. To get - a reliable reading using a finger you may need to touch the ground pin - with another part of your body, for example your other hand. +**Resistive touch** +This test is done by measuring how much resistance there is between the +pin and ground. A low resistance gives a reading of ``True``. To get +a reliable reading using a finger you may need to touch the ground pin +with another part of your body, for example your other hand. - **Capacitive touch** - This test is done by interacting with the electric field of a capacitor - using a finger as a conductor. `Capacitive touch - `_ - does not require you to make a ground connection as part of a circuit. +**Capacitive touch** +This test is done by interacting with the electric field of a capacitor +using a finger as a conductor. `Capacitive touch +`_ +does not require you to make a ground connection as part of a circuit. - :return: ``True`` if the pin is being touched with a finger, otherwise return ``False``. - """ +:return: ``True`` if the pin is being touched with a finger, otherwise return ``False``.""" ... + def set_touch_mode(self, value: int) -> None: - """Set the touch mode for the pin. + """Stel de aanraakmodus voor de pin in. (aanraakmodus instellen) - Example: ``pin0.set_touch_mode(pin0.CAPACITIVE)`` +Example: ``pin0.set_touch_mode(pin0.CAPACITIVE)`` - The default touch mode for the pins on the edge connector is - ``resistive``. The default for the logo pin **V2** is ``capacitive``. +The default touch mode for the pins on the edge connector is +``resistive``. The default for the logo pin **V2** is ``capacitive``. - :param value: ``CAPACITIVE`` or ``RESISTIVE`` from the relevant pin. - """ +:param value: (waarde) ``CAPACITIVE`` of ``RESISTIVE`` van de relevante speler.""" ... - pin0: MicroBitTouchPin -"""Pin with digital, analog and touch features.""" - +"""Pin met digitale, analoge en touch functies.""" pin1: MicroBitTouchPin -"""Pin with digital, analog and touch features.""" - +"""Pin met digitale, analoge en aanraak functies.""" pin2: MicroBitTouchPin -"""Pin with digital, analog and touch features.""" - +"""Pin met digitale, analoge en aanraak functies.""" pin3: MicroBitAnalogDigitalPin -"""Pin with digital and analog features.""" - +"""Pin met digitale, analoge en aanraak functies.""" pin4: MicroBitAnalogDigitalPin -"""Pin with digital and analog features.""" - +"""Pin met digitale, analoge en aanraak functies.""" pin5: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin met digitale, analoge en aanraak functies.""" pin6: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin met digitale functies.""" pin7: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin met digitale functies.""" pin8: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin met digitale functies.""" pin9: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin met digitale functies.""" pin10: MicroBitAnalogDigitalPin -"""Pin with digital and analog features.""" - +"""Pin met digitale, analoge en aanraak functies.""" pin11: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin met digitale, analoge en aanraak functies.""" pin12: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin met digitale, analoge en aanraak functies.""" pin13: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin met digitale, analoge en aanraak functies.""" pin14: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin met digitale, analoge en aanraak functies.""" pin15: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin met digitale, analoge en aanraak functies.""" pin16: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin met digitale, analoge en aanraak functies.""" pin19: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin met digitale, analoge en aanraak functies.""" pin20: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin met digitale, analoge en aanraak functies.""" pin_logo: MicroBitTouchPin -"""A touch sensitive logo pin on the front of the micro:bit, which by default is set to capacitive touch mode.""" - +"""Een aanraak gevoelige logo pin op de voorkant van de micro:bit, die standaard is ingesteld op capacitieve aanraking modus.""" pin_speaker: MicroBitAnalogDigitalPin -"""A pin to address the micro:bit speaker. +"""Een pin om de micro:bit luidspreker aan te spreken. (pin luidspreker) This API is intended only for use in Pulse-Width Modulation pin operations e.g. pin_speaker.write_analog(128). """ class Image: - """An image to show on the micro:bit LED display. + """Een afbeelding om te laten zien op het micro:bit LED display. (afbeelding) - Given an image object it's possible to display it via the ``display`` API:: - - display.show(Image.HAPPY) - """ +Given an image object it's possible to display it via the ``display`` API:: + display.show(Image.HAPPY)""" HEART: Image - """Heart image.""" - + """Hart afbeelding (hart)""" HEART_SMALL: Image - """Small heart image.""" - + """Klein hart afbeelding. (hart klein)""" HAPPY: Image - """Happy face image.""" - + """Blije gezichtsafbeelding. (blij)""" SMILE: Image - """Smiling mouth image.""" - + """Glimlach gezicht afbeelding. (glimlach)""" SAD: Image - """Sad face image.""" - + """Droevige gezichtsafbeelding. (verdrietig)""" CONFUSED: Image - """Confused face image.""" - + """Verward gezichtsafbeelding. (verward)""" ANGRY: Image - """Angry face image.""" - + """Boos gezichtsafbeelding. (kwaad)""" ASLEEP: Image - """Sleeping face image.""" - + """Slapend gezicht afbeelding. (in slaap)""" SURPRISED: Image - """Surprised face image.""" - + """Verraste gezichtsafbeelding. (verrast)""" SILLY: Image - """Silly face image.""" - + """Gek gezichtsafbeelding. (gek)""" FABULOUS: Image - """Sunglasses face image.""" - + """Zonnebril gezichtsafbeelding. (fantastisch)""" MEH: Image - """Unimpressed face image.""" - + """Niet onder de indruk gezichtsafbeelding.""" YES: Image - """Tick image.""" - + """Aanvinken afbeelding. (ja)""" NO: Image - """Cross image.""" - + """Kruis afbeelding. (nee)""" CLOCK12: Image - """Image with line pointing to 12 o'clock.""" - + """Afbeelding met lijn die naar 12.00 uur wijst. (klok 12)""" CLOCK11: Image - """Image with line pointing to 11 o'clock.""" - + """Afbeelding met lijn die naar 11.00 uur wijst. (klok 11)""" CLOCK10: Image - """Image with line pointing to 10 o'clock.""" - + """Afbeelding met lijn die naar 10.00 uur wijst. (klok 10)""" CLOCK9: Image - """Image with line pointing to 9 o'clock.""" - + """Afbeelding met lijn die naar 9.00 uur wijst. (klok 9)""" CLOCK8: Image - """Image with line pointing to 8 o'clock.""" - + """Afbeelding met lijn die naar 8.00 uur wijst. (klok 8)""" CLOCK7: Image - """Image with line pointing to 7 o'clock.""" - + """Afbeelding met lijn die naar 7.00 uur wijst. (klok 7)""" CLOCK6: Image - """Image with line pointing to 6 o'clock.""" - + """Afbeelding met lijn die naar 6.00 uur wijst. (klok 6)""" CLOCK5: Image - """Image with line pointing to 5 o'clock.""" - + """Afbeelding met lijn die naar 5.00 uur wijst. (klok 5)""" CLOCK4: Image - """Image with line pointing to 4 o'clock.""" - + """Afbeelding met lijn die naar 4.00 uur wijst. (klok 4)""" CLOCK3: Image - """Image with line pointing to 3 o'clock.""" - + """Afbeelding met lijn die naar 3.00 uur wijst. (klok 3)""" CLOCK2: Image - """Image with line pointing to 2 o'clock.""" - + """Afbeelding met lijn die naar 2 uur wijst. (klok2)""" CLOCK1: Image - """Image with line pointing to 1 o'clock.""" - + """Afbeelding met lijn die naar 1 uur wijst. (klok1)""" ARROW_N: Image - """Image of arrow pointing north.""" - + """Afbeelding van pijl richting het noorden. (pijl n)""" ARROW_NE: Image - """Image of arrow pointing north east.""" - + """Afbeelding van pijl richting het noord oosten. (pijl NO)""" ARROW_E: Image - """Image of arrow pointing east.""" - + """Afbeelding van pijl richting het oosten. (pijl e)""" ARROW_SE: Image - """Image of arrow pointing south east.""" - + """Afbeelding van pijl richting het zuid-oosten. (pijl ZO)""" ARROW_S: Image - """Image of arrow pointing south.""" - + """Afbeelding van pijltje richting het zuiden. (pijl z)""" ARROW_SW: Image - """Image of arrow pointing south west.""" - + """Afbeelding van pijl richting het zuid-westen. (pijl ZW)""" ARROW_W: Image - """Image of arrow pointing west.""" - + """Afbeelding van pijl richting het westen. (pijl w)""" ARROW_NW: Image - """Image of arrow pointing north west.""" - + """Afbeelding van pijl richting het noord-westen. (pijl NW)""" TRIANGLE: Image - """Image of a triangle pointing up.""" - + """Afbeelding van een driehoek die naar boven wijst. (driehoek)""" TRIANGLE_LEFT: Image - """Image of a triangle in the left corner.""" - + """Afbeelding van een driehoek in de linker hoek. (Driehoek links)""" CHESSBOARD: Image - """Alternate LEDs lit in a chessboard pattern.""" - + """Alternatieve LED's verlichten in een schaakbord patroon. (schaakbord)""" DIAMOND: Image - """Diamond image.""" - + """Diamanten afbeelding. (diamant)""" DIAMOND_SMALL: Image - """Small diamond image.""" - + """Kleine diamanten afbeelding. (diamant klein)""" SQUARE: Image - """Square image.""" - + """Vierkante afbeelding (vierkant)""" SQUARE_SMALL: Image - """Small square image.""" - + """Kleine vierkante afbeelding. (vierkant klein)""" RABBIT: Image - """Rabbit image.""" - + """Konijn afbeelding. (konijn)""" COW: Image - """Cow image.""" - + """Koe afbeelding. (koe)""" MUSIC_CROTCHET: Image - """Crotchet note image.""" - + """Kwartnoot afbeelding. (muziek kwartnoot)""" MUSIC_QUAVER: Image - """Quaver note image.""" - + """Kwartnoot afbeelding. (muziek kwartnoot)""" MUSIC_QUAVERS: Image - """Pair of quavers note image.""" - + """Koppel van kwartnoten afbeelding. (muziek kwartnoten)""" PITCHFORK: Image - """Pitchfork image.""" - + """Stemvork afbeelding. (stemvork)""" XMAS: Image - """Christmas tree image.""" - + """Kerstboom afbeelding. (kerstmis)""" PACMAN: Image - """Pac-Man arcade character image.""" - + """Pac-Man arcade karakterafbeelding. (Pacman)""" TARGET: Image - """Target image.""" - + """Doel afbeelding. (doel)""" TSHIRT: Image - """T-shirt image.""" - + """T-shirt afbeelding.""" ROLLERSKATE: Image - """Rollerskate image.""" - + """Rolschaats afbeelding. (rolschaatsen)""" DUCK: Image - """Duck image.""" - + """Eend afbeelding. (eend)""" HOUSE: Image - """House image.""" - + """Huis afbeelding. (huis)""" TORTOISE: Image - """Tortoise image.""" - + """Schildpad afbeelding. (schildpad)""" BUTTERFLY: Image - """Butterfly image.""" - + """Vlinder afbeelding. (vlinder)""" STICKFIGURE: Image - """Stick figure image.""" - + """Stok figuur afbeelding. (stok figuur)""" GHOST: Image - """Ghost image.""" - + """Spook afbeelding. (spook)""" SWORD: Image - """Sword image.""" - + """Zwaard afbeelding. (zwaard)""" GIRAFFE: Image - """Giraffe image.""" - + """Giraffe afbeelding.""" SKULL: Image - """Skull image.""" - + """Schedel afbeelding. (doodshoofd)""" UMBRELLA: Image - """Umbrella image.""" - + """Paraplu afbeelding. (paraplu)""" SNAKE: Image - """Snake image.""" - + """Slang afbeelding. (slang)""" SCISSORS: Image - """Scissors image.""" - + """Schaar afbeelding. (schaar)""" ALL_CLOCKS: List[Image] - """A list containing all the CLOCK_ images in sequence.""" - + """Een lijst met alle CLOCK_ afbeeldingen achter elkaar. (alle klokken)""" ALL_ARROWS: List[Image] - """A list containing all the ARROW_ images in sequence.""" + """Een lijst met alle ARROW_ afbeeldingen in reeks. (alle pijlen)""" + @overload def __init__(self, string: str) -> None: - """Create an image from a string describing which LEDs are lit. + """Maak een afbeelding van een tekenreeks die beschrijft welke LED's zijn. (initialiseren) - ``string`` has to consist of digits 0-9 arranged into lines, - describing the image, for example:: +``string`` has to consist of digits 0-9 arranged into lines, +describing the image, for example:: - image = Image("90009:" - "09090:" - "00900:" - "09090:" - "90009") + 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 newlines (\\n) insead of the colons. +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 newlines (\\n) insead of the colons. - :param string: The string describing the image. - """ +:param string: (tekenreeks) De tekenreeks die de afbeelding beschrijft.""" ... + @overload - def __init__( - self, width: int = 5, height: int = 5, buffer: ReadableBuffer = None - ) -> None: - """Create an empty image with ``width`` columns and ``height`` rows. + def __init__(self, width: int=5, height: int=5, buffer: ReadableBuffer=None) -> None: + """Maak een lege afbeelding met ``width`` kolommen en ``height`` rijen. (initialiseren) - :param width: Optional width of the image - :param height: Optional height of the image - :param buffer: Optional array or bytes of ``width``×``height`` integers in range 0-9 to initialize the image +:param width: (breedte) Optionele breedte van de afbeelding +:param height: (hoogte) Optionele hoogte van de afbeelding +:param buffer: Optionele array of bytes van ``width``×``height`` integers in bereik 0-9 om de afbeelding te initialiseren - Examples:: +Examples:: - Image(2, 2, b'\x08\x08\x08\x08') - Image(2, 2, bytearray([9,9,9,9])) + Image(2, 2, b'\x08\x08\x08\x08') + Image(2, 2, bytearray([9,9,9,9])) - These create 2 x 2 pixel images at full brightness. - """ +These create 2 x 2 pixel images at full brightness.""" ... + def width(self) -> int: - """Get the number of columns. + """Haal het aantal kolommen op. (breedte) - :return: The number of columns in the image - """ +:return: The number of columns in the image""" ... + def height(self) -> int: - """Get the number of rows. + """Krijg het aantal rijen. (hoogte) - :return: The number of rows in the image - """ +:return: The number of rows in the image""" ... + def set_pixel(self, x: int, y: int, value: int) -> None: - """Set the brightness of a pixel. + """Stel de helderheid van een pixel in. (pixel instellen) - Example: ``my_image.set_pixel(0, 0, 9)`` +Example: ``my_image.set_pixel(0, 0, 9)`` - :param x: The column number - :param y: The row number - :param value: The brightness as an integer between 0 (dark) and 9 (bright) +:param x: (х) Het kolom nummer +:param y: Het rij nummer +:param value: (waarde) De helderheid als een geheel getal tussen 0 (donker) en 9 (helder) - This method will raise an exception when called on any of the built-in - read-only images, like ``Image.HEART``. - """ +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: - """Get the brightness of a pixel. + """Krijg de helderheid van een pixel. (verkrijg pixel) - Example: ``my_image.get_pixel(0, 0)`` +Example: ``my_image.get_pixel(0, 0)`` - :param x: The column number - :param y: The row number - :return: The brightness as an integer between 0 and 9. - """ +:param x: (х) Het kolom nummer +:param y: Het rij nummer +:return: The brightness as an integer between 0 and 9.""" ... + def shift_left(self, n: int) -> Image: - """Create a new image by shifting the picture left. + """Maak een nieuwe afbeelding door de afbeelding naar links te verschuiven. (verschuiving naar links) - Example: ``Image.HEART_SMALL.shift_left(1)`` +Example: ``Image.HEART_SMALL.shift_left(1)`` - :param n: The number of columns to shift by - :return: The shifted image - """ +:param n: Het aantal te verschuiven kolommen +:return: The shifted image""" ... + def shift_right(self, n: int) -> Image: - """Create a new image by shifting the picture right. + """Maak een nieuwe afbeelding door de afbeelding rechts te verschuiven. (verschuif Rechts) - Example: ``Image.HEART_SMALL.shift_right(1)`` +Example: ``Image.HEART_SMALL.shift_right(1)`` - :param n: The number of columns to shift by - :return: The shifted image - """ +:param n: Het aantal te verschuiven kolommen +:return: The shifted image""" ... + def shift_up(self, n: int) -> Image: - """Create a new image by shifting the picture up. + """Maak een nieuwe afbeelding door de afbeelding omhoog te schuiven. (verschuiving omhoog) - Example: ``Image.HEART_SMALL.shift_up(1)`` +Example: ``Image.HEART_SMALL.shift_up(1)`` - :param n: The number of rows to shift by - :return: The shifted image - """ +:param n: Het aantal rijen om te verschuiven met +:return: The shifted image""" ... + def shift_down(self, n: int) -> Image: - """Create a new image by shifting the picture down. + """Maak een nieuwe afbeelding door de afbeelding omlaag te verschuiven. (verschuif omlaag) - Example: ``Image.HEART_SMALL.shift_down(1)`` +Example: ``Image.HEART_SMALL.shift_down(1)`` - :param n: The number of rows to shift by - :return: The shifted image - """ +:param n: Het aantal rijen om te verschuiven met +:return: The shifted image""" ... + def crop(self, x: int, y: int, w: int, h: int) -> Image: - """Create a new image by cropping the picture. + """Maak een nieuwe afbeelding door de afbeelding bij te snijden. (bij snijden) - Example: ``Image.HEART.crop(1, 1, 3, 3)`` +Example: ``Image.HEART.crop(1, 1, 3, 3)`` - :param x: The crop offset column - :param y: The crop offset row - :param w: The crop width - :param h: The crop height - :return: The new image - """ +:param x: (х) De kolom verschuiving +:param y: De rij verschuiving +:param w: De bij snij breedte +:param h: (uur) Hoogte bijsnijden +:return: The new image""" ... + def copy(self) -> Image: - """Create an exact copy of the image. + """Maak een exacte kopie van de afbeelding. (kopiëer) - Example: ``Image.HEART.copy()`` +Example: ``Image.HEART.copy()`` - :return: The new image - """ +:return: The new image""" ... + def invert(self) -> Image: - """Create a new image by inverting the brightness of the pixels in the - source image. + """Maak een nieuwe afbeelding door de helderheid van de pixels in de +bronafbeelding om te draaien. (omkeren) - Example: ``Image.SMALL_HEART.invert()`` +Example: ``Image.SMALL_HEART.invert()`` - :return: The new image. - """ +:return: The new image.""" ... + def fill(self, value: int) -> None: - """Set the brightness of all the pixels in the image. + """Stel de helderheid van alle pixels in de afbeelding in. (opvullen) - Example: ``my_image.fill(5)`` +Example: ``my_image.fill(5)`` - :param value: The new brightness as a number between 0 (dark) and 9 (bright). +:param value: (waarde) De nieuwe helderheid als een getal tussen 0 (donker) en 9 (helder). - This method will raise an exception when called on any of the built-in - read-only images, like ``Image.HEART``. - """ +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 an area from another image into this image. - - Example: ``my_image.blit(Image.HEART, 1, 1, 3, 3, 1, 1)`` - - :param src: The source image - :param x: The starting column offset in the source image - :param y: The starting row offset in the source image - :param w: The number of columns to copy - :param h: The number of rows to copy - :param xdest: The column offset to modify in this image - :param ydest: The row offset to modify in this image - - Pixels outside the source image are treated as having a brightness 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 blit(self, src: Image, x: int, y: int, w: int, h: int, xdest: int=0, ydest: int=0) -> None: + """Kopieer een gebied van een andere afbeelding naar deze afbeelding. + +Example: ``my_image.blit(Image.HEART, 1, 1, 3, 3, 1, 1)`` + +:param src: De bron afbeelding +:param x: (х) De begin kolom offset in de bron afbeelding +:param y: De beginkolom offset in de bronafbeelding +:param w: Het aantal te kopiëren kolommen +:param h: (uur) Het aantal te kopiëren rijen +:param xdest: De kolomverschuiving om aan te passen in deze afbeelding +:param ydest: De kolomverschuiving om aan te passen in deze afbeelding + +Pixels outside the source image are treated as having a brightness 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.""" + """Krijg een compacte tekenreeks die de afbeelding vertegenwoordigt.""" ... + def __str__(self) -> str: - """Get a readable string representation of the image.""" + """Krijg een leesbare tekenreeks die de afbeelding vertegenwoordigt.""" ... + def __add__(self, other: Image) -> Image: - """Create a new image by adding the brightness values from the two - images for each pixel. + """Maak een nieuwe afbeelding door de helderheidswaarden van de twee +afbeeldingen voor elke pixel toe te voegen. (toevoegen) - Example: ``Image.HEART + Image.HAPPY`` +Example: ``Image.HEART + Image.HAPPY`` - :param other: The image to add. - """ +:param other: (overige) De afbeelding om toe te voegen.""" ... + def __sub__(self, other: Image) -> Image: - """Create a new image by subtracting the brightness values of the - other image from this image. + """Maak een nieuw beeld door de helderheidswaarden van de andere afbeelding van deze afbeelding af te trekken. - Example: ``Image.HEART - Image.HEART_SMALL`` +Example: ``Image.HEART - Image.HEART_SMALL`` - :param other: The image to subtract. - """ +:param other: (overige) De afbeelding om af te trekken.""" ... + def __mul__(self, n: float) -> Image: - """Create a new image by multiplying the brightness of each pixel by - ``n``. + """Maak een nieuwe afbeelding door de helderheid van elke pixel te vermenigvuldigen met +``n``. - Example: ``Image.HEART * 0.5`` +Example: ``Image.HEART * 0.5`` - :param n: The value to multiply by. - """ +:param n: De waarde om te vermenigvuldigen.""" ... + def __truediv__(self, n: float) -> Image: - """Create a new image by dividing the brightness of each pixel by - ``n``. + """Maak een nieuwe afbeelding door de helderheid van elke pixel te delen door +``n``. - Example: ``Image.HEART / 2`` +Example: ``Image.HEART / 2`` - :param n: The value to divide by. - """ +:param n: De waarde om mee te delen.""" ... class SoundEvent: LOUD: SoundEvent - """Represents the transition of sound events, from ``quiet`` to ``loud`` like clapping or shouting.""" - + """Vertegenwoordigt de transitie van geluidsgebeurtenissen, van ``quiet`` tot ``loud`` zoals klappen of roepen. (luid)""" QUIET: SoundEvent - """Represents the transition of sound events, from ``loud`` to ``quiet`` like speaking or background music.""" + """Vertegenwoordigt de transitie van geluidsgebeurtenissen, van ``loud`` tot ``quiet`` zoals spreken of achtergrondmuziek. (stil)""" class Sound: - """The built-in sounds can be called using ``audio.play(Sound.NAME)``.""" - + """De ingebouwde geluiden kunnen worden aangeroepen met ``audio.play(Sound.NAME)``. (geluid)""" GIGGLE: Sound - """Giggling sound.""" - + """Giechelgeluidjes (giechelen)""" HAPPY: Sound - """Happy sound.""" - + """Blij geluid. (blij)""" HELLO: Sound - """Greeting sound.""" - + """Groet geluid. (hallo)""" MYSTERIOUS: Sound - """Mysterious sound.""" - + """Mysterieus geluid. (mysterieus)""" SAD: Sound - """Sad sound.""" - + """Droevig geluid. (verdrietig)""" SLIDE: Sound - """Sliding sound.""" - + """Glij geluid. (Veeg)""" SOARING: Sound - """Soaring sound.""" - + """Zweef geluid. (stijgend)""" SPRING: Sound - """Spring sound.""" - + """Spring geluid. (veer)""" TWINKLE: Sound - """Twinkling sound.""" - + """Twinkel geluid. (twinkeling)""" YAWN: Sound - """Yawning sound.""" + """Geeuwgeluiden (geeuw)""" \ No newline at end of file diff --git a/lang/nl/typeshed/stdlib/microbit/accelerometer.pyi b/lang/nl/typeshed/stdlib/microbit/accelerometer.pyi index bac82c0..85a1426 100644 --- a/lang/nl/typeshed/stdlib/microbit/accelerometer.pyi +++ b/lang/nl/typeshed/stdlib/microbit/accelerometer.pyi @@ -1,115 +1,103 @@ -"""Measure the acceleration of the micro:bit and recognise gestures. -""" - +"""Meet de versnelling van de micro:bit en herken gebaren. (acceleratiemeter)""" from typing import Tuple def get_x() -> int: - """Get the acceleration measurement in the ``x`` axis in milli-g. + """Krijg de acceleratiemeting in de ``x`` as in milli-g. (krijg x) - Example: ``accelerometer.get_x()`` +Example: ``accelerometer.get_x()`` - :return: A positive or negative integer depending on direction in the range +/- 2000mg. - """ +:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" ... def get_y() -> int: - """Get the acceleration measurement in the ``y`` axis in milli-g. + """Krijg de acceleratiemeting in de ``y`` as in milli-g. (krijg y) - Example: ``accelerometer.get_y()`` +Example: ``accelerometer.get_y()`` - :return: A positive or negative integer depending on direction in the range +/- 2000mg. - """ +:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" ... def get_z() -> int: - """Get the acceleration measurement in the ``z`` axis in milli-g. + """Krijg de acceleratiemeter meting in de ``z`` as in milli-g. (krijg z) - Example: ``accelerometer.get_z()`` +Example: ``accelerometer.get_z()`` - :return: A positive or negative integer depending on direction in the range +/- 2000mg. - """ +:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" ... def get_values() -> Tuple[int, int, int]: - """Get the acceleration measurements in all axes at once as a tuple. + """Verkrijg de acceleratiemeter metingen in alle assen tegelijk als een tupel. (krijg waarden) - Example: ``x, y, z = accelerometer.get_values()`` +Example: ``x, y, z = accelerometer.get_values()`` - :return: a three-element tuple of integers ordered as X, Y, Z, each value a positive or negative integer depending on direction in the range +/- 2000mg - """ +:return: a three-element tuple of integers ordered as X, Y, Z, each value a positive or negative integer depending on direction in the range +/- 2000mg""" ... def get_strength() -> int: - """Get the acceleration measurement of all axes combined, as a positive integer. This is the Pythagorean sum of the X, Y and Z axes. + """Krijg de versnelling meting van alle assen gecombineerd, als een positief getal. Dit is de Pythagorische som van de X, Y en Z assen. (krijg sterkte) - Example: ``accelerometer.get_strength()`` +Example: ``accelerometer.get_strength()`` - :return: The combined acceleration strength of all the axes, in milli-g. - """ +:return: The combined acceleration strength of all the axes, in milli-g.""" ... def current_gesture() -> str: - """Get the name of the current gesture. + """Verkrijg de naam van het huidige gebaar. (huidig gebaar) - Example: ``accelerometer.current_gesture()`` +Example: ``accelerometer.current_gesture()`` - 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. +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. - :return: The current gesture - """ +:return: The current gesture""" ... def is_gesture(name: str) -> bool: - """Check if the named gesture is currently active. + """Controleer of het benoemde gebaar momenteel actief is. (is gebaren) - Example: ``accelerometer.is_gesture('shake')`` +Example: ``accelerometer.is_gesture('shake')`` - 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. +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. - :param name: The gesture name. - :return: ``True`` if the gesture is active, ``False`` otherwise. - """ +:param name: (naam) De naam van het gebaar. +:return: ``True`` if the gesture is active, ``False`` otherwise.""" ... def was_gesture(name: str) -> bool: - """Check if the named gesture was active since the last call. + """Controleer of het benoemde gebaar actief was sinds het laatste gesprek. (was gebaren) - Example: ``accelerometer.was_gesture('shake')`` +Example: ``accelerometer.was_gesture('shake')`` - 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. +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. - :param name: The gesture name. - :return: ``True`` if the gesture was active since the last call, ``False`` otherwise. - """ +:param name: (naam) De naam van het gebaar. +:return: ``True`` if the gesture was active since the last call, ``False`` otherwise.""" def get_gestures() -> Tuple[str, ...]: - """Return a tuple of the gesture history. + """Geeft als resultaat een reeks van de gebaren geschiedenis. (verkrijg gebaren) - Example: ``accelerometer.get_gestures()`` +Example: ``accelerometer.get_gestures()`` - Clears the gesture history before returning. +Clears the gesture history before returning. - Gestures are not updated in the background so there needs to be constant - calls to some accelerometer method to do the gesture detection. Usually - gestures can be detected using a loop with a small :func:`microbit.sleep` delay. +Gestures are not updated in the background so there needs to be constant +calls to some accelerometer method to do the gesture detection. Usually +gestures can be detected using a loop with a small :func:`microbit.sleep` delay. - :return: The history as a tuple, most recent last. - """ +:return: The history as a tuple, most recent last.""" ... def set_range(value: int) -> None: - """Set the accelerometer sensitivity range, in g (standard gravity), to the closest values supported by the hardware, so it rounds to either ``2``, ``4``, or ``8`` g. + """Stel het gevoeligheidsbereik van de acceleratiemeter, in g (standaard zwaartekracht), in op de dichtstbijzijnde waarden die door de hardware worden ondersteund, zodat het wordt afgerond op ``2``, ``4`` of ``8`` g. (kies bereik) - Example: ``accelerometer.set_range(8)`` +Example: ``accelerometer.set_range(8)`` - :param value: New range for the accelerometer, an integer in ``g``. - """ +:param value: (waarde) Nieuwe bereik voor de acceleratiemeter, een geheel getal in ``g``.""" \ No newline at end of file diff --git a/lang/nl/typeshed/stdlib/microbit/audio.pyi b/lang/nl/typeshed/stdlib/microbit/audio.pyi index 3b1e327..ee2c412 100644 --- a/lang/nl/typeshed/stdlib/microbit/audio.pyi +++ b/lang/nl/typeshed/stdlib/microbit/audio.pyi @@ -1,160 +1,124 @@ -"""Play sounds using the micro:bit (import ``audio`` for V1 compatibility). -""" - +"""Geluid afspelen met behulp van de micro:bit (importeer ``audio`` voor V1 compatibiliteit).""" from ..microbit import MicroBitDigitalPin, Sound, pin0 from typing import ClassVar, Iterable, Union -def play( - source: Union[Iterable[AudioFrame], Sound, SoundEffect], - wait: bool = True, - pin: MicroBitDigitalPin = pin0, - return_pin: Union[MicroBitDigitalPin, None] = None, -) -> None: - """Play a built-in sound, sound effect or custom audio frames. +def play(source: Union[Iterable[AudioFrame], Sound, SoundEffect], wait: bool=True, pin: MicroBitDigitalPin=pin0, return_pin: Union[MicroBitDigitalPin, None]=None) -> None: + """Een ingebouwde geluid, geluids effect of aangepaste audio frames afspelen. (afspelen) - Example: ``audio.play(Sound.GIGGLE)`` +Example: ``audio.play(Sound.GIGGLE)`` - :param source: A built-in ``Sound`` such as ``Sound.GIGGLE``, a ``SoundEffect`` or sample data as an iterable of ``AudioFrame`` objects. - :param wait: If ``wait`` is ``True``, this function will block until the sound is complete. - :param pin: An optional argument to specify the output pin can be used to override the default of ``pin0``. If we do not want any sound to play we can use ``pin=None``. - :param return_pin: Specifies a differential edge connector pin to connect to an external speaker instead of ground. This is ignored for the **V2** revision. - """ +:param source: (bron) Een ingebouwde ``Sound`` zoals ``Sound.GIGGLE``, een ``SoundEffect`` of voorbeeldgegevens als een iteratie van ``AudioFrame`` objecten. +:param wait: (wacht) Als ``wait`` ``True``is, wordt deze functie geblokkeerd totdat het geluid is voltooid. +:param pin: Een optioneel argument om de uitvoerpin op te geven kan worden gebruikt om de standaard van ``pin0``te overschrijven. Als we geen geluid willen afspelen, kunnen we ``pin=None`` gebruiken. +:param return_pin: (retourneer pin) Specificeert een differentiële rand connector pin om verbinding te maken met een externe luidspreker in plaats van de grond. Dit wordt genegeerd voor de **V2** herziening.""" def is_playing() -> bool: - """Check whether a sound is playing. + """Controleer of een geluid wordt gespeeld. (speelt af) - Example: ``audio.is_playing()`` +Example: ``audio.is_playing()`` - :return: ``True`` if audio is playing, otherwise ``False``.""" +:return: ``True`` if audio is playing, otherwise ``False``.""" ... def stop() -> None: - """Stop all audio playback. + """Stop het afspelen van de audio. - Example: ``audio.stop()`` - """ +Example: ``audio.stop()``""" ... class SoundEffect: - """A sound effect, composed by a set of parameters configured via the constructor or attributes.""" - + """Een geluidseffect, bestaande uit een set parameters geconfigureerd via de constructor of attributen.""" WAVEFORM_SINE: ClassVar[int] - """Sine wave option used for the ``waveform`` parameter.""" - + """De sinusgolf optie gebruikt voor de ``waveform`` parameter. (golfvorm sinus)""" WAVEFORM_SAWTOOTH: ClassVar[int] - """Sawtooth wave option used for the ``waveform`` parameter.""" - + """Zaag golf optie gebruikt voor de ``waveform`` parameter. (golfvorm zaagtand)""" WAVEFORM_TRIANGLE: ClassVar[int] - """Triangle wave option used for the ``waveform`` parameter.""" - + """De drie hoeks golf optie gebruikt voor de ``waveform`` parameter. (golfvorm driehoek)""" WAVEFORM_SQUARE: ClassVar[int] - """Square wave option used for the ``waveform`` parameter.""" - + """Blok golf optie die wordt gebruikt voor de parameter ``waveform``. (golfvorm vierkant)""" WAVEFORM_NOISE: ClassVar[int] - """Noise option used for the ``waveform`` parameter.""" - + """Noise optie gebruikt voor de ``waveform`` parameter. (golfvormig geluid)""" SHAPE_LINEAR: ClassVar[int] - """Linear interpolation option used for the ``shape`` parameter.""" - + """Lineaire interpolatie optie die wordt gebruikt voor de ``shape`` parameter. (vorm lineair)""" SHAPE_CURVE: ClassVar[int] - """Curve interpolation option used for the ``shape`` parameter.""" - + """Curve interpolatie optie gebruikt voor de ``shape`` parameter. (vorm curve)""" SHAPE_LOG: ClassVar[int] - """Logarithmic interpolation option used for the ``shape`` parameter.""" - + """Logaritmische interpolatie optie gebruikt voor de ``shape`` parameter. (vorm log)""" FX_NONE: ClassVar[int] - """No effect option used for the ``fx`` parameter.""" - + """Geen effectoptie gebruikt voor de ``fx`` parameter. (geen fx)""" FX_TREMOLO: ClassVar[int] - """Tremolo effect option used for the ``fx`` parameter.""" - + """Tremolo effect optie die wordt gebruikt voor de ``fx`` parameter.""" FX_VIBRATO: ClassVar[int] - """Vibrato effect option used for the ``fx`` parameter.""" - + """Vibrato effect optie die wordt gebruikt voor de ``fx`` parameter.""" FX_WARBLE: ClassVar[int] - """Warble effect option used for the ``fx`` parameter.""" - + """Warble effect optie die wordt gebruikt voor de ``fx`` parameter .""" freq_start: int - """Start frequency in Hertz (Hz), a number between ``0`` and ``9999``""" - + """Start frequentie in Hertz (Hz), een getal tussen ``0`` en ``9999`` (frequentie start)""" freq_end: int - """End frequency in Hertz (Hz), a number between ``0`` and ``9999``""" - + """Eind frequentie in Hertz (Hz), een getal tussen ``0`` en ``9999`` (frequentie einde)""" duration: int - """Duration of the sound in milliseconds, a number between ``0`` and ``9999``""" - + """Duur van het geluid in milliseconden, een getal tussen ``0`` en ``9999`` (Duur)""" vol_start: int - """Start volume value, a number between ``0`` and ``255``""" - + """Start volume waarde, een getal tussen ``0`` en ``255``""" vol_end: int - """End volume value, a number between ``0`` and ``255``""" - + """Eind volume waarde, een getal tussen ``0`` en ``255`` (vol einde)""" waveform: int - """Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise)""" - + """Type van golfvorm, één van deze waarden: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (willekeurig gegenereerde lawaai) (golfvorm)""" fx: int - """Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``""" - + """Effect om aan het geluid toe te voegen, een van de volgende waarden: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``of ``FX_NONE``""" shape: int - """The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``""" - - def __init__( - self, - freq_start: int = 500, - freq_end: int = 2500, - duration: int = 500, - vol_start: int = 255, - vol_end: int = 0, - waveform: int = WAVEFORM_SQUARE, - fx: int = FX_NONE, - shape: int = SHAPE_LOG, - ): - """Create a new sound effect. - - Example: ``my_effect = SoundEffect(duration=1000)`` - - All the parameters are optional, with default values as shown above, and - they can all be modified via attributes of the same name. For example, we - can first create an effect ``my_effect = SoundEffect(duration=1000)``, - and then change its attributes ``my_effect.duration = 500``. - - :param freq_start: Start frequency in Hertz (Hz), a number between ``0`` and ``9999``. - :param freq_end: End frequency in Hertz (Hz), a number between ``0`` and ``9999``. - :param duration: Duration of the sound in milliseconds, a number between ``0`` and ``9999``. - :param vol_start: Start volume value, a number between ``0`` and ``255``. - :param vol_end: End volume value, a number between ``0`` and ``255``. - :param waveform: Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise). - :param fx: Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``. - :param shape: The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``. - """ + """Het type van de interpolatie curve tussen de begin- en eind frequenties, verschillende golfvormen hebben verschillende snelheid bij het wijzigen van de frequentie. Een van de volgende waarden: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG`` (vorm)""" + + def __init__(self, freq_start: int=500, freq_end: int=2500, duration: int=500, vol_start: int=255, vol_end: int=0, waveform: int=WAVEFORM_SQUARE, fx: int=FX_NONE, shape: int=SHAPE_LOG): + """Maak een nieuw geluidseffect. (initialiseren) + +Example: ``my_effect = SoundEffect(duration=1000)`` + +All the parameters are optional, with default values as shown above, and +they can all be modified via attributes of the same name. For example, we +can first create an effect ``my_effect = SoundEffect(duration=1000)``, +and then change its attributes ``my_effect.duration = 500``. + +:param freq_start: (frequentie start) Start frequentie in Hertz (Hz), een getal tussen ``0`` en ``9999``. +:param freq_end: (frequentie einde) Eind frequentie in Hertz (Hz), een getal tussen ``0`` en ``9999``. +:param duration: (duur) Duur van het geluid in milliseconden, een getal tussen ``0`` en ``9999``. +:param vol_start: Startvolumewaarde, een getal tussen ``0`` en ``255``. +:param vol_end: (vol einde) Eindvolumewaarde, een getal tussen ``0`` en ``255``. +:param waveform: (golfvorm) Type golfvorm, één van deze waarden: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (willekeurig gegenereerde geluid). +:param fx: Effect om het geluid toe te voegen, een van de volgende waarden: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``of ``FX_NONE``. +:param shape: (vorm) Het type van de interpolatie curve tussen de begin- en eind frequenties, verschillende golfvormen hebben verschillende snelheid bij het wijzigen van de frequentie. Een van de volgende waarden: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``.""" + def copy(self) -> SoundEffect: - """Create a copy of this ``SoundEffect``. + """Maak een kopie van dit ``SoundEffect``. (kopiëer) - Example: ``sound_2 = sound_1.copy()`` +Example: ``sound_2 = sound_1.copy()`` - :return: A copy of the SoundEffect. - """ +:return: A copy of the SoundEffect.""" class AudioFrame: - """An ``AudioFrame`` object is a list of 32 samples each of which is a unsigned byte - (whole number between 0 and 255). + """Een ``AudioFrame`` object is een lijst van 32 samples elk een niet-ondertekende byte +(geheel getal tussen 0 en 255). - It takes just over 4 ms to play a single frame. +It takes just over 4 ms to play a single frame. - Example:: +Example:: - frame = AudioFrame() - for i in range(len(frame)): - frame[i] = 252 - i * 8 - """ + frame = AudioFrame() + for i in range(len(frame)): + frame[i] = 252 - i * 8""" def copyfrom(self, other: AudioFrame) -> None: - """Overwrite the data in this ``AudioFrame`` with the data from another ``AudioFrame`` instance. + """Overschrijf de gegevens in deze ``AudioFrame`` met de gegevens van een andere ``AudioFrame`` instantie. (kopieer van) + +Example: ``my_frame.copyfrom(source_frame)`` + +:param other: (overige) ``AudioFrame`` exemplaar van waar de gegevens worden gekopieerd.""" + + def __len__(self) -> int: + ... - Example: ``my_frame.copyfrom(source_frame)`` + def __setitem__(self, key: int, value: int) -> None: + ... - :param other: ``AudioFrame`` instance from which to copy the data. - """ - def __len__(self) -> int: ... - def __setitem__(self, key: int, value: int) -> None: ... - def __getitem__(self, key: int) -> int: ... + def __getitem__(self, key: int) -> int: + ... \ No newline at end of file diff --git a/lang/nl/typeshed/stdlib/microbit/compass.pyi b/lang/nl/typeshed/stdlib/microbit/compass.pyi index c74a47b..06c6d48 100644 --- a/lang/nl/typeshed/stdlib/microbit/compass.pyi +++ b/lang/nl/typeshed/stdlib/microbit/compass.pyi @@ -1,78 +1,70 @@ -"""Use the built-in compass. -""" +"""Gebruik het ingebouwde kompas. (kompas)""" def calibrate() -> None: - """Starts the calibration process. + """Start het kalibratieproces. (Kalibreren) - Example: ``compass.calibrate()`` +Example: ``compass.calibrate()`` - 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. - """ +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: - """Check is the compass is calibrated. + """Controleer of het kompas is gekalibreerd. (gekalibreerd) - Example: ``compass.is_calibrated()`` +Example: ``compass.is_calibrated()`` - :return: ``True`` if the compass has been successfully calibrated, ``False`` otherwise. - """ +:return: ``True`` if the compass has been successfully calibrated, ``False`` otherwise.""" ... def clear_calibration() -> None: - """Undoes the calibration, making the compass uncalibrated again. + """Kalibratie ongedaan maken, waardoor het kompas weer losgemaakt wordt. (kalibratie wissen) - Example: ``compass.clear_calibration()`` - """ +Example: ``compass.clear_calibration()``""" ... def get_x() -> int: - """Get the magnetic field strength on the ``x`` axis. + """Krijg de magnetische veldsterkte op de ``x`` as. (krijg x) - Example: ``compass.get_x()`` +Example: ``compass.get_x()`` - Call ``calibrate`` first or the results will be inaccurate. +Call ``calibrate`` first or the results will be inaccurate. - :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. - """ +:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" ... def get_y() -> int: - """Get the magnetic field strength on the ``y`` axis. + """Krijg de magnetische veldsterkte op de ``y`` as. (krijg y) - Example: ``compass.get_y()`` +Example: ``compass.get_y()`` - Call ``calibrate`` first or the results will be inaccurate. +Call ``calibrate`` first or the results will be inaccurate. - :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. - """ +:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" ... def get_z() -> int: - """Get the magnetic field strength on the ``z`` axis. + """Krijg de magnetische veldsterkte op de ``z`` as. (krijg z) - Example: ``compass.get_z()`` +Example: ``compass.get_z()`` - Call ``calibrate`` first or the results will be inaccurate. +Call ``calibrate`` first or the results will be inaccurate. - :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. - """ +:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" ... def heading() -> int: - """Get the compass heading. + """Haal de kompaskop op. (kop) - Example: ``compass.heading()`` +Example: ``compass.heading()`` - :return: An integer in the range from 0 to 360, representing the angle in degrees, clockwise, with north as 0. - """ +:return: An integer in the range from 0 to 360, representing the angle in degrees, clockwise, with north as 0.""" ... def get_field_strength() -> int: - """Get the magnitude of the magnetic field around the device. + """Krijg de magnitude van het magnetische veld rond het apparaat. (krijg veldsterkte) - Example: ``compass.get_field_strength()`` +Example: ``compass.get_field_strength()`` - :return: An integer indication of the magnitude of the magnetic field in nano tesla.""" - ... +:return: An integer indication of the magnitude of the magnetic field in nano tesla.""" + ... \ No newline at end of file diff --git a/lang/nl/typeshed/stdlib/microbit/display.pyi b/lang/nl/typeshed/stdlib/microbit/display.pyi index aa4013e..0447e07 100644 --- a/lang/nl/typeshed/stdlib/microbit/display.pyi +++ b/lang/nl/typeshed/stdlib/microbit/display.pyi @@ -1,115 +1,92 @@ -"""Show text, images and animations on the 5×5 LED display. -""" - +"""Tekst, afbeeldingen en animaties weergeven op het 5×5 LED-weergave.""" from ..microbit import Image from typing import Union, overload, Iterable def get_pixel(x: int, y: int) -> int: - """Get the brightness of the LED at column ``x`` and row ``y``. + """Krijg de helderheid van de LED in kolom ``x`` en rij ``y``. (verkrijg pixel) - Example: ``display.get_pixel(0, 0)`` +Example: ``display.get_pixel(0, 0)`` - :param x: The display column (0..4) - :param y: The display row (0..4) - :return: A number between 0 (off) and 9 (bright) - """ +:param x: (х) De weergavekolom (0..4) +:param y: De weergave rij (0.4) +:return: A number 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``. + """Stel de helderheid van de LED in op kolom ``x`` en rij ``y``. (pixel instellen) - Example: ``display.set_pixel(0, 0, 9)`` +Example: ``display.set_pixel(0, 0, 9)`` - :param x: The display column (0..4) - :param y: The display row (0..4) - :param value: The brightness between 0 (off) and 9 (bright) - """ +:param x: (х) De weergavekolom (0..4) +:param y: De weergave rij (0.4) +:param value: (waarde) De helderheid tussen 0 (uit) en 9 (helderst)""" ... def clear() -> None: - """Set the brightness of all LEDs to 0 (off). + """Stel de helderheid van alle LED's in op 0 (uit). (wissen) - Example: ``display.clear()`` - """ +Example: ``display.clear()``""" ... -def show( - image: Union[str, float, int, Image, Iterable[Image]], - delay: int = 400, - wait: bool = True, - loop: bool = False, - clear: bool = False, -) -> None: - """Shows images, letters or digits on the LED display. +def show(image: Union[str, float, int, Image, Iterable[Image]], delay: int=400, wait: bool=True, loop: bool=False, clear: bool=False) -> None: + """Toont afbeeldingen, letters of cijfers op het LED-scherm. (toon) - Example: ``display.show(Image.HEART)`` +Example: ``display.show(Image.HEART)`` - When ``image`` is an image or a list of images then each image is displayed in turn. - If ``image`` is a string or number, each letter or digit is displayed in turn. +When ``image`` is an image or a list of images then each image is displayed in turn. +If ``image`` is a string or number, each letter or digit is displayed in turn. - :param image: A string, number, image or list of images to show. - :param delay: Each letter, digit or image is shown with ``delay`` milliseconds between them. - :param wait: If ``wait`` is ``True``, this function will block until the animation is finished, otherwise the animation will happen in the background. - :param loop: If ``loop`` is ``True``, the animation will repeat forever. - :param clear: If ``clear`` is ``True``, the display will be cleared after the sequence has finished. +:param image: (afbeelding) Een string, nummer, afbeelding of lijst van weer te geven afbeeldingen. +:param delay: (vertraging) Elke letter, cijfer of afbeelding wordt weergegeven met ``delay`` milliseconden tussen hen. +:param wait: (wacht) Als ``wait`` ``True``is, blokkeert deze functie totdat de animatie is voltooid, anders gebeurt de animatie op de achtergrond. +:param loop: Als ``loop`` ``True``is, zal de animatie voor altijd herhalen. +:param clear: (wissen) Als ``clear`` ``True``is, wordt het scherm gewist nadat de reeks is voltooid. - The ``wait``, ``loop`` and ``clear`` arguments must be specified using their keyword. - """ +The ``wait``, ``loop`` and ``clear`` arguments must be specified using their keyword.""" ... -def scroll( - text: Union[str, float, int], - delay: int = 150, - wait: bool = True, - loop: bool = False, - monospace: bool = False, -) -> None: - """Scrolls a number or text on the LED display. - - Example: ``display.scroll('micro:bit')`` - - :param text: The string to scroll. If ``text`` is an integer or float it is first converted to a string using ``str()``. - :param delay: The ``delay`` parameter controls how fast the text is scrolling. - :param wait: If ``wait`` is ``True``, this function will block until the animation is finished, otherwise the animation will happen in the background. - :param loop: If ``loop`` is ``True``, the animation will repeat forever. - :param monospace: 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. - - The ``wait``, ``loop`` and ``monospace`` arguments must be specified - using their keyword. - """ +def scroll(text: Union[str, float, int], delay: int=150, wait: bool=True, loop: bool=False, monospace: bool=False) -> None: + """Scrolt een nummer of tekst op het LED display (scrollen) + +Example: ``display.scroll('micro:bit')`` + +:param text: (tekst) De tekenreeks om te scrollen. Als ``text`` een geheel getal of float is, wordt het eerst geconverteerd naar een tekenreeks met behulp van ``str()``. +:param delay: (vertraging) De parameter ``delay`` bepaalt hoe snel de tekst scrolt. +:param wait: (wacht) Als ``wait`` ``True``is, blokkeert deze functie totdat de animatie is voltooid, anders gebeurt de animatie op de achtergrond. +:param loop: Als ``loop`` ``True``is, zal de animatie voor altijd herhalen. +:param monospace: Als ``monospace`` ``True`` is, nemen de tekens allemaal 5 pixel kolommen in de breedte in beslag, anders staat er precies 1 lege pixelkolom tussen elk teken terwijl ze scrollen. + +The ``wait``, ``loop`` and ``monospace`` arguments must be specified +using their keyword.""" ... def on() -> None: - """Turn on the LED display. + """Schakel het LED display in. (aan) - Example: ``display.on()`` - """ +Example: ``display.on()``""" ... def off() -> None: - """Turn off the LED display (disabling the display allows you to re-use the GPIO pins for other purposes). + """Het uitschakelen van het LED display (uitschakelen van het scherm geeft je de mogelijkheid om de GPIO-pinnen opnieuw te gebruiken voor andere doeleinden). (uit) - Example: ``display.off()`` - """ +Example: ``display.off()``""" ... def is_on() -> bool: - """Check whether the LED display is enabled. + """Controleer of de LED-weergave is ingeschakeld. (staat aan) - Example: ``display.is_on()`` +Example: ``display.is_on()`` - :return: ``True`` if the display is on, otherwise returns ``False``. - """ +:return: ``True`` if the display is on, otherwise returns ``False``.""" ... def read_light_level() -> int: - """Read the light level. + """Lees het licht niveau. (lees licht niveau) - Example: ``display.read_light_level()`` +Example: ``display.read_light_level()`` - Uses the display's LEDs in reverse-bias mode to sense the amount of light - falling on the display. +Uses the display's LEDs in reverse-bias mode to sense the amount of light +falling on the display. - :return: An integer between 0 and 255 representing the light level, with larger meaning more light. - """ - ... +:return: An integer between 0 and 255 representing the light level, with larger meaning more light.""" + ... \ No newline at end of file diff --git a/lang/nl/typeshed/stdlib/microbit/i2c.pyi b/lang/nl/typeshed/stdlib/microbit/i2c.pyi index df26efa..b3654a5 100644 --- a/lang/nl/typeshed/stdlib/microbit/i2c.pyi +++ b/lang/nl/typeshed/stdlib/microbit/i2c.pyi @@ -1,57 +1,49 @@ -"""Communicate with devices using the I²C bus protocol. -""" - +"""Communiceer met apparaten met behulp van het I²C bus protocol.""" from _typeshed import ReadableBuffer from ..microbit import MicroBitDigitalPin, pin19, pin20 from typing import List -def init( - freq: int = 100000, sda: MicroBitDigitalPin = pin20, scl: MicroBitDigitalPin = pin19 -) -> None: - """Re-initialize a peripheral. +def init(freq: int=100000, sda: MicroBitDigitalPin=pin20, scl: MicroBitDigitalPin=pin19) -> None: + """Initialiseer een randapparaat opnieuw. (initialiseren) - Example: ``i2c.init()`` +Example: ``i2c.init()`` - :param freq: clock frequency - :param sda: ``sda`` pin (default 20) - :param scl: ``scl`` pin (default 19) +:param freq: (frequentie) klok frequentie +:param sda: ``sda`` pin (standaard 20) +:param scl: ``scl`` pin (standaard 19) - On a micro:bit V1 board, changing the I²C pins from defaults will make - the accelerometer and compass stop working, as they are connected - internally to those pins. This warning does not apply to the **V2** - revision of the micro:bit as this has `separate I²C lines `_ - for the motion sensors and the edge connector. - """ +On a micro:bit V1 board, changing the I²C pins from defaults will make +the accelerometer and compass stop working, as they are connected +internally to those pins. This warning does not apply to the **V2** +revision of the micro:bit as this has `separate I²C lines `_ +for the motion sensors and the edge connector.""" ... def scan() -> List[int]: - """Scan the bus for devices. + """Scan de bus op apparaten. (scannen) - Example: ``i2c.scan()`` +Example: ``i2c.scan()`` - :return: A list of 7-bit addresses corresponding to those devices that responded to the scan. - """ +:return: A list of 7-bit addresses corresponding to those devices that responded to the scan.""" ... -def read(addr: int, n: int, repeat: bool = False) -> bytes: - """Read bytes from a device. +def read(addr: int, n: int, repeat: bool=False) -> bytes: + """Lees bytes van een apparaat. (lezen) - Example: ``i2c.read(0x50, 64)`` +Example: ``i2c.read(0x50, 64)`` - :param addr: The 7-bit address of the device - :param n: The number of bytes to read - :param repeat: If ``True``, no stop bit will be sent - :return: The bytes read - """ +:param addr: Het 7-bit adres van het apparaat +:param n: Het aantal te lezen bytes +:param repeat: (herhaal) Als ``True``, zal er geen stop bit worden verzonden +:return: The bytes read""" ... -def write(addr: int, buf: ReadableBuffer, repeat: bool = False) -> None: - """Write bytes to a device. +def write(addr: int, buf: ReadableBuffer, repeat: bool=False) -> None: + """Schrijven van bytes naar een apparaat. (schrijven) - Example: ``i2c.write(0x50, bytes([1, 2, 3]))`` +Example: ``i2c.write(0x50, bytes([1, 2, 3]))`` - :param addr: The 7-bit address of the device - :param buf: A buffer containing the bytes to write - :param repeat: If ``True``, no stop bit will be sent - """ - ... +:param addr: Het 7-bit adres van het apparaat +:param buf: Een buffer met de te schrijven bytes +:param repeat: (herhaal) Als ``True``, zal er geen stop bit worden verzonden""" + ... \ No newline at end of file diff --git a/lang/nl/typeshed/stdlib/microbit/microphone.pyi b/lang/nl/typeshed/stdlib/microbit/microphone.pyi index 68e8f3a..df484aa 100644 --- a/lang/nl/typeshed/stdlib/microbit/microphone.pyi +++ b/lang/nl/typeshed/stdlib/microbit/microphone.pyi @@ -1,70 +1,62 @@ -"""Respond to sound using the built-in microphone (V2 only). -""" - +"""Reageer op geluid met de ingebouwde microfoon (V2 alleen). (microfoon)""" from typing import Optional, Tuple from ..microbit import SoundEvent def current_event() -> Optional[SoundEvent]: - """Get the last recorded sound event + """Krijg de laatst opgenomen geluidsgebeurtenis (huidige gebeurtenis) - Example: ``microphone.current_event()`` +Example: ``microphone.current_event()`` - :return: The event, ``SoundEvent('loud')`` or ``SoundEvent('quiet')``. - """ +:return: The event, ``SoundEvent('loud')`` or ``SoundEvent('quiet')``.""" ... def was_event(event: SoundEvent) -> bool: - """Check if a sound was heard at least once since the last call. + """Controleer of een geluid tenminste één keer is gehoord sinds het laatste gesprek. - Example: ``microphone.was_event(SoundEvent.LOUD)`` +Example: ``microphone.was_event(SoundEvent.LOUD)`` - This call clears the sound history before returning. +This call clears the sound history before returning. - :param event: The event to check for, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET`` - :return: ``True`` if sound was heard at least once since the last call, otherwise ``False``. - """ +:param event: (gebeurtenis) Het te controleren evenement, zoals ``SoundEvent.LOUD`` of ``SoundEvent.QUIET`` +:return: ``True`` if sound was heard at least once since the last call, otherwise ``False``.""" ... def is_event(event: SoundEvent) -> bool: - """Check the most recent sound event detected. + """Controleer de meest recente geluidsgebeurtenis gedetecteerd. - Example: ``microphone.is_event(SoundEvent.LOUD)`` +Example: ``microphone.is_event(SoundEvent.LOUD)`` - This call does not clear the sound event history. +This call does not clear the sound event history. - :param event: The event to check for, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET`` - :return: ``True`` if sound was the most recent heard, ``False`` otherwise. - """ +:param event: (gebeurtenis) Het te controleren evenement, zoals ``SoundEvent.LOUD`` of ``SoundEvent.QUIET`` +:return: ``True`` if sound was the most recent heard, ``False`` otherwise.""" ... def get_events() -> Tuple[SoundEvent, ...]: - """Get the sound event history as a tuple. + """Krijg de geluidsgeschiedenis als tuple. - Example: ``microphone.get_events()`` +Example: ``microphone.get_events()`` - This call clears the sound history before returning. +This call clears the sound history before returning. - :return: A tuple of the event history with the most recent event last. - """ +:return: A tuple of the event history with the most recent event last.""" ... def set_threshold(event: SoundEvent, value: int) -> None: - """Set the threshold for a sound event. + """Stel de drempel in voor een geluidsgebeurtenis. (stel drempelwaarde in) - Example: ``microphone.set_threshold(SoundEvent.LOUD, 250)`` +Example: ``microphone.set_threshold(SoundEvent.LOUD, 250)`` - A high threshold means the event will only trigger if the sound is very loud (>= 250 in the example). +A high threshold means the event will only trigger if the sound is very loud (>= 250 in the example). - :param event: A sound event, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET``. - :param value: The threshold level in the range 0-255. - """ +:param event: (gebeurtenis) Een geluidsgebeurtenis, zoals ``SoundEvent.LOUD`` of ``SoundEvent.QUIET``. +:param value: (waarde) Het drempelniveau in het bereik 0-255.""" ... def sound_level() -> int: - """Get the sound pressure level. + """Krijg het Geluidsdrukniveau. (geluidsniveau) - Example: ``microphone.sound_level()`` +Example: ``microphone.sound_level()`` - :return: A representation of the sound pressure level in the range 0 to 255. - """ - ... +:return: A representation of the sound pressure level in the range 0 to 255.""" + ... \ No newline at end of file diff --git a/lang/nl/typeshed/stdlib/microbit/speaker.pyi b/lang/nl/typeshed/stdlib/microbit/speaker.pyi index 5a74a4d..a1c9cee 100644 --- a/lang/nl/typeshed/stdlib/microbit/speaker.pyi +++ b/lang/nl/typeshed/stdlib/microbit/speaker.pyi @@ -1,18 +1,15 @@ -"""Control the built-in speaker (V2 only). -""" +"""Beheer de ingebouwde luidspreker (alleen V2). (luidspreker)""" def off() -> None: - """Turn the speaker off. + """Luidspreker uitschakelen. (uit) - Example: ``speaker.off()`` +Example: ``speaker.off()`` - This does not disable sound output to an edge connector pin. - """ +This does not disable sound output to an edge connector pin.""" ... def on() -> None: - """Turn the speaker on. + """Luidspreker inschakelen (aan) - Example: ``speaker.on()`` - """ - ... +Example: ``speaker.on()``""" + ... \ No newline at end of file diff --git a/lang/nl/typeshed/stdlib/microbit/spi.pyi b/lang/nl/typeshed/stdlib/microbit/spi.pyi index 09c4046..0faf9ed 100644 --- a/lang/nl/typeshed/stdlib/microbit/spi.pyi +++ b/lang/nl/typeshed/stdlib/microbit/spi.pyi @@ -1,60 +1,47 @@ -"""Communicate with devices using the serial peripheral interface (SPI) bus. -""" - +"""Communiceer met apparaten met behulp van de seriële perifere interface (SPI) bus.""" from _typeshed import ReadableBuffer, WriteableBuffer from ..microbit import pin13, pin14, pin15, MicroBitDigitalPin -def init( - baudrate: int = 1000000, - bits: int = 8, - mode: int = 0, - sclk: MicroBitDigitalPin = pin13, - mosi: MicroBitDigitalPin = pin15, - miso: MicroBitDigitalPin = pin14, -) -> None: - """Initialize SPI communication. - - Example: ``spi.init()`` - - For correct communication, the parameters have to be the same on both communicating devices. - - :param baudrate: The speed of communication. - :param bits: The width in bits of each transfer. Currently only ``bits=8`` is supported. However, this may change in the future. - :param mode: Determines the combination of clock polarity and phase - `see online table `_. - :param sclk: sclk pin (default 13) - :param mosi: mosi pin (default 15) - :param miso: miso pin (default 14) - """ +def init(baudrate: int=1000000, bits: int=8, mode: int=0, sclk: MicroBitDigitalPin=pin13, mosi: MicroBitDigitalPin=pin15, miso: MicroBitDigitalPin=pin14) -> None: + """Initialiseer SPI communicatie. (initialiseren) + +Example: ``spi.init()`` + +For correct communication, the parameters have to be the same on both communicating devices. + +:param baudrate: De snelheid van de communicatie. +:param bits: De breedte in bits van elke overdracht. Momenteel wordt alleen ``bits=8`` ondersteund. Dit kan echter veranderen in de toekomst. +:param mode: (modus) Bepaalt de combinatie van klokpolariteit en fase - `zie online tabel `_. +:param sclk: sclk pin (standaard 13) +:param mosi: mosi pin (standaard 15) +:param miso: miso pin (standaard 14)""" ... -def read(nbytes: int, out: int = 0) -> bytes: - """Read at most ``nbytes`` while continuously writing the single byte given by ``out``. +def read(nbytes: int, out: int=0) -> bytes: + """Lees minstens ``nbytes`` terwijl het enkele byte gegeven in ``out`` continu geschreven wordt. (lezen) - Example: ``spi.read(64)`` +Example: ``spi.read(64)`` - :param nbytes: Maximum number of bytes to read. - :param out: The byte value to write (default 0). - :return: The bytes read. - """ +:param nbytes: Maximum aantal te lezen bytes. +:param out: (uit) De byte-waarde om te schrijven (standaard 0). +:return: The bytes read.""" ... def write(buffer: ReadableBuffer) -> None: - """Write bytes to the bus. + """Schrijf bytes naar de bus. (schrijven) - Example: ``spi.write(bytes([1, 2, 3]))`` +Example: ``spi.write(bytes([1, 2, 3]))`` - :param buffer: A buffer to read data from. - """ +:param buffer: Een buffer om gegevens van te lezen.""" ... def write_readinto(out: WriteableBuffer, in_: ReadableBuffer) -> None: - """Write the ``out`` buffer to the bus and read any response into the ``in_`` buffer. + """Schrijf de ``out`` buffer naar de bus en lees elke reactie in de ``in_`` buffer. (schrijf readinto) - Example: ``spi.write_readinto(out_buffer, in_buffer)`` +Example: ``spi.write_readinto(out_buffer, in_buffer)`` - The length of the buffers should be the same. The buffers can be the same object. +The length of the buffers should be the same. The buffers can be the same object. - :param out: The buffer to write any response to. - :param in_: The buffer to read data from. - """ - ... +:param out: (uit) De buffer om een reactie naar te schrijven. +:param in_: De buffer om gegevens van te lezen.""" + ... \ No newline at end of file diff --git a/lang/nl/typeshed/stdlib/microbit/uart.pyi b/lang/nl/typeshed/stdlib/microbit/uart.pyi index 2ab650f..0f4f26d 100644 --- a/lang/nl/typeshed/stdlib/microbit/uart.pyi +++ b/lang/nl/typeshed/stdlib/microbit/uart.pyi @@ -1,96 +1,79 @@ -"""Communicate with a device using a serial interface. -""" - +"""Communiceer met een apparaat via een seriële interface.""" from _typeshed import WriteableBuffer from ..microbit import MicroBitDigitalPin from typing import Optional, Union - ODD: int -"""Odd parity""" - +"""Oneven pariteit (oneven)""" EVEN: int -"""Even parity""" - -def init( - baudrate: int = 9600, - bits: int = 8, - parity: Optional[int] = None, - stop: int = 1, - tx: Optional[MicroBitDigitalPin] = None, - rx: Optional[MicroBitDigitalPin] = None, -) -> None: - """Initialize serial communication. - - Example: ``uart.init(115200, tx=pin0, rx=pin1)`` - - :param baudrate: The speed of communication. - :param bits: The size of bytes being transmitted. micro:bit only supports 8. - :param parity: How parity is checked, ``None``, ``uart.ODD`` or ``uart.EVEN``. - :param stop: The number of stop bits, has to be 1 for micro:bit. - :param tx: Transmitting pin. - :param rx: Receiving pin. - - 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. - - For more details see `the online documentation `_. - """ +"""Even pariteit""" + +def init(baudrate: int=9600, bits: int=8, parity: Optional[int]=None, stop: int=1, tx: Optional[MicroBitDigitalPin]=None, rx: Optional[MicroBitDigitalPin]=None) -> None: + """Initialiseer seriële communicatie. (initialiseren) + +Example: ``uart.init(115200, tx=pin0, rx=pin1)`` + +:param baudrate: De snelheid van de communicatie. +:param bits: De grootte van de bytes die worden verzonden. micro:bit ondersteunt slechts 8. +:param parity: (pariteit) Hoe de pariteit is aangevinkt, ``None``, ``uart.ODD`` of ``uart.EVEN``. +:param stop: Het aantal stop bits, moet 1 zijn voor micro:bit. +:param tx: Verzend pin. +:param rx: Ontvangende pin. + +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. + +For more details see `the online documentation `_.""" ... def any() -> bool: - """Check if any data is waiting. + """Controleer of er nog gegevens staan te wachten. (elke) - Example: ``uart.any()`` +Example: ``uart.any()`` - :return: ``True`` if any data is waiting, else ``False``. - """ +:return: ``True`` if any data is waiting, else ``False``.""" ... -def read(nbytes: Optional[int] = None) -> Optional[bytes]: - """Read bytes. +def read(nbytes: Optional[int]=None) -> Optional[bytes]: + """Lees bytes. (lezen) - Example: ``uart.read()`` +Example: ``uart.read()`` - :param nbytes: If ``nbytes`` is specified then read at most that many bytes, otherwise read as many bytes as possible - :return: A bytes object or ``None`` on timeout - """ +:param nbytes: Als ``nbytes`` is gespecificeerd, lees dan maximaal zoveel bytes, anders lees zo veel mogelijk bytes +:return: A bytes object or ``None`` on timeout""" ... -def readinto(buf: WriteableBuffer, nbytes: Optional[int] = None) -> Optional[int]: - """Read bytes into the ``buf``. +def readinto(buf: WriteableBuffer, nbytes: Optional[int]=None) -> Optional[int]: + """Lees bytes in de ``buf``. (inlezen) - Example: ``uart.readinto(input_buffer)`` +Example: ``uart.readinto(input_buffer)`` - :param buf: The buffer to write to. - :param nbytes: If ``nbytes`` is specified then read at most that many bytes, otherwise read ``len(buf)`` bytes. - :return: number of bytes read and stored into ``buf`` or ``None`` on timeout. - """ +:param buf: De buffer om naar te schrijven. +:param nbytes: Als ``nbytes`` is gespecificeerd, lees dan hooguit zoveel bytes, anders lees ``len(buf)`` bytes. +:return: number of bytes read and stored into ``buf`` or ``None`` on timeout.""" ... def readline() -> Optional[bytes]: - """Read a line, ending in a newline character. + """Lees een regel, eindigend in een nieuw karakter regel. (leesregel) - Example: ``uart.readline()`` +Example: ``uart.readline()`` - :return: The line read or ``None`` on timeout. The newline character is included in the returned bytes. - """ +:return: The line read or ``None`` on timeout. The newline character is included in the returned bytes.""" ... def write(buf: Union[bytes, str]) -> Optional[int]: - """Write a buffer to the bus. + """Schrijf bytes naar de bus. (schrijven) - Example: ``uart.write('hello world')`` +Example: ``uart.write('hello world')`` - :param buf: A bytes object or a string. - :return: The number of bytes written, or ``None`` on timeout. +:param buf: Een bytes object of een tekenreeks. +:return: The number of bytes written, or ``None`` on timeout. - Examples:: +Examples:: - uart.write('hello world') - uart.write(b'hello world') - uart.write(bytes([1, 2, 3])) - """ - ... + uart.write('hello world') + uart.write(b'hello world') + uart.write(bytes([1, 2, 3]))""" + ... \ No newline at end of file diff --git a/lang/nl/typeshed/stdlib/micropython.pyi b/lang/nl/typeshed/stdlib/micropython.pyi index 7a6079f..7dda37b 100644 --- a/lang/nl/typeshed/stdlib/micropython.pyi +++ b/lang/nl/typeshed/stdlib/micropython.pyi @@ -1,144 +1,132 @@ -"""MicroPython internals.""" - +"""MicroPython intern.""" from typing import Any, TypeVar, overload - -_T = TypeVar("_T") +_T = TypeVar('_T') def const(expr: _T) -> _T: - """Used to declare that the expression is a constant so that the compiler can - optimise it. + """Gebruikt om te verklaren dat de expressie een constante is zodat de compiler +deze kan optimaliseren. - The use of this function should be as follows:: +The use of this function should be as follows:: - from micropython import const - CONST_X = const(123) - CONST_Y = const(2 * CONST_X + 1) + from micropython import const + CONST_X = const(123) + CONST_Y = const(2 * CONST_X + 1) - Constants declared this way are still accessible as global variables from - outside the module they are declared in. On the other hand, if a constant - begins with an underscore then it is hidden, it is not available as a - global variable, and does not take up any memory during execution. +Constants declared this way are still accessible as global variables from +outside the module they are declared in. On the other hand, if a constant +begins with an underscore then it is hidden, it is not available as a +global variable, and does not take up any memory during execution. - :param expr: A constant expression. - """ +:param expr: Een constante expressie.""" ... @overload def opt_level() -> int: - """Get the current optimisation level for the compilation of scripts. + """Krijg het huidige optimalisatieniveau voor de compilatie van scripts. (Kies niveau) - Example: ``micropython.opt_level()`` +Example: ``micropython.opt_level()`` - The optimisation level controls the following compilation features: +The optimisation level controls the following compilation features: - - Assertions: at level 0 assertion statements are enabled and compiled - into the bytecode; at levels 1 and higher assertions are not compiled. +- Assertions: at level 0 assertion statements are enabled and compiled + into the bytecode; at levels 1 and higher assertions are not compiled. - - Built-in ``__debug__`` variable: at level 0 this variable expands to - True; at levels 1 and higher it expands to False. +- Built-in ``__debug__`` variable: at level 0 this variable expands to + True; at levels 1 and higher it expands to False. - - Source-code line numbers: at levels 0, 1 and 2 source-code line number - are stored along with the bytecode so that exceptions can report the - line number they occurred at; at levels 3 and higher line numbers are - not stored. +- Source-code line numbers: at levels 0, 1 and 2 source-code line number + are stored along with the bytecode so that exceptions can report the + line number they occurred at; at levels 3 and higher line numbers are + not stored. - :return: An integer representing the current level. - """ +:return: An integer representing the current level.""" ... @overload def opt_level(level: int) -> None: - """Sets the optimisation level for subsequent compilation of scripts. + """Stelt het optimalisatie niveau in voor de latere compilatie van scripts. (opt niveau) - Example: ``micropython.opt_level(1)`` +Example: ``micropython.opt_level(1)`` - The optimisation level controls the following compilation features: +The optimisation level controls the following compilation features: - - Assertions: at level 0 assertion statements are enabled and compiled - into the bytecode; at levels 1 and higher assertions are not compiled. +- Assertions: at level 0 assertion statements are enabled and compiled + into the bytecode; at levels 1 and higher assertions are not compiled. - - Built-in ``__debug__`` variable: at level 0 this variable expands to - True; at levels 1 and higher it expands to False. +- Built-in ``__debug__`` variable: at level 0 this variable expands to + True; at levels 1 and higher it expands to False. - - Source-code line numbers: at levels 0, 1 and 2 source-code line number - are stored along with the bytecode so that exceptions can report the - line number they occurred at; at levels 3 and higher line numbers are - not stored. +- Source-code line numbers: at levels 0, 1 and 2 source-code line number + are stored along with the bytecode so that exceptions can report the + line number they occurred at; at levels 3 and higher line numbers are + not stored. - The default optimisation level is usually level 0. +The default optimisation level is usually level 0. - :param level: An integer optimisation level. - """ +:param level: (niveau) Een integer optimaliserings niveau.""" ... -def mem_info(verbose: Any = None) -> None: - """Print information about currently used memory. +def mem_info(verbose: Any=None) -> None: + """Druk informatie af over het momenteel gebruikte geheugen. - Example: ``micropython.mem_info()`` +Example: ``micropython.mem_info()`` - :param verbose: If the ``verbose`` argument is given then extra information is printed. - """ +:param verbose: Als het argument van ``verbose`` wordt opgegeven, wordt extra informatie afgedrukt.""" ... -def qstr_info(verbose: Any = None) -> None: - """Print information about currently interned strings. +def qstr_info(verbose: Any=None) -> None: + """Druk informatie af over momenteel gebruikte interne tekenreeksen. - Example: ``micropython.qstr_info()`` +Example: ``micropython.qstr_info()`` - :param verbose: If the ``verbose`` argument is given then extra information is printed. +:param verbose: Als het argument van ``verbose`` wordt opgegeven, wordt extra informatie afgedrukt. - The information that is printed is implementation dependent, but currently - includes the number of interned strings and the amount of RAM they use. In - verbose mode it prints out the names of all RAM-interned strings. - """ +The information that is printed is implementation dependent, but currently +includes the number of interned strings and the amount of RAM they use. In +verbose mode it prints out the names of all RAM-interned strings.""" ... def stack_use() -> int: - """Return an integer representing the current amount of stack that is being - used. + """Retourneert een integer getal dat huidige hoeveelheid stack vertegenwoordigt die wordt gebruikt. (stapel gebruik) - Example: ``micropython.stack_use()`` +Example: ``micropython.stack_use()`` - The absolute value of this is not particularly useful, rather it - should be used to compute differences in stack usage at different points. +The absolute value of this is not particularly useful, rather it +should be used to compute differences in stack usage at different points. - :return: An integer representing current stack use. - """ +:return: An integer representing current stack use.""" ... def heap_lock() -> None: - """Lock the heap. + """Lock de heap. (heap slot) - Example: ``micropython.heap_lock()`` +Example: ``micropython.heap_lock()`` - When locked no memory allocation can occur and a ``MemoryError`` will be - raised if any heap allocation is attempted. - """ +When locked no memory allocation can occur and a ``MemoryError`` will be +raised if any heap allocation is attempted.""" ... def heap_unlock() -> None: """Unlock the heap. - Example: ``micropython.heap_unlock()`` +Example: ``micropython.heap_unlock()`` - When locked no memory allocation can occur and a ``MemoryError`` will be - raised if any heap allocation is attempted. - """ +When locked no memory allocation can occur and a ``MemoryError`` will be +raised if any heap allocation is attempted.""" ... def kbd_intr(chr: int) -> None: - """Set the character that will raise a ``KeyboardInterrupt`` exception. + """Stel het karakter in dat een ``KeyboardInterrupt`` -uitzondering maakt. - Example: ``micropython.kbd_intr(-1)`` +Example: ``micropython.kbd_intr(-1)`` - :param chr: Character code to raise the interrupt or -1 to disable capture of Ctrl-C. +:param chr: Karakter code om de onderbreking of -1 om opname van Ctrl-C uit te schakelen. - By default this is set to 3 during script execution, corresponding to Ctrl-C. - Passing -1 to this function will disable capture of Ctrl-C, and passing 3 - will restore it. +By default this is set to 3 during script execution, corresponding to Ctrl-C. +Passing -1 to this function will disable capture of Ctrl-C, and passing 3 +will restore it. - This function can be used to prevent the capturing of Ctrl-C on the - incoming stream of characters that is usually used for the REPL, in case - that stream is used for other purposes. - """ - ... +This function can be used to prevent the capturing of Ctrl-C on the +incoming stream of characters that is usually used for the REPL, in case +that stream is used for other purposes.""" + ... \ No newline at end of file diff --git a/lang/nl/typeshed/stdlib/music.pyi b/lang/nl/typeshed/stdlib/music.pyi index 5f4778b..5c3c7fc 100644 --- a/lang/nl/typeshed/stdlib/music.pyi +++ b/lang/nl/typeshed/stdlib/music.pyi @@ -1,167 +1,128 @@ -"""Create and play melodies. -""" +"""Maak en speel melodieën. (muziek)""" from typing import Optional, Tuple, Union, List - from .microbit import MicroBitDigitalPin, pin0 - DADADADUM: Tuple[str, ...] -"""Melody: the opening to Beethoven’s 5th Symphony in C minor.""" - +"""Melodie: de opening naar Beethoven's 5e Symfonie in C minor.""" ENTERTAINER: Tuple[str, ...] -"""Melody: the opening fragment of Scott Joplin’s Ragtime classic “The Entertainer”.""" - +"""Melody: het openingsfragment van Scott Joplin’s Ragtime classic “The Entertainer”.""" PRELUDE: Tuple[str, ...] -"""Melody: the opening of the first Prelude in C Major of J.S.Bach’s 48 Preludes and Fugues.""" - +"""Melodie: de opening van de eerste prelude in C Major van J.S.Bach's 48 Preludes en Fugues.""" ODE: Tuple[str, ...] -"""Melody: the “Ode to Joy” theme from Beethoven’s 9th Symphony in D minor.""" - +"""Melodie: het thema "Ode aan Joy" van Beethoven zijn negende Symfonie in D-klein.""" NYAN: Tuple[str, ...] -"""Melody: the Nyan Cat theme (http://www.nyan.cat/). +"""Melodie: het Nyan Cat thema (http://www.nyan.cat/). The composer is unknown. This is fair use for educational porpoises (as they say in New York).""" - RINGTONE: Tuple[str, ...] -"""Melody: something that sounds like a mobile phone ringtone. +"""Melodie: iets dat klinkt als een beltoon van een mobiele telefoon. (beltoon) To be used to indicate an incoming message. """ - FUNK: Tuple[str, ...] -"""Melody: a funky bass line for secret agents and criminal masterminds.""" - +"""Melodie: een grappige bas lijn voor geheime agenten en criminele meesterbreinen.""" BLUES: Tuple[str, ...] -"""Melody: a boogie-woogie 12-bar blues walking bass.""" - +"""Melodie: een boogie-woogie 12-bar blues wandel bas. (Blues)""" BIRTHDAY: Tuple[str, ...] -"""Melody: “Happy Birthday to You…” +"""Melodie: “Happy Birthday to You…” (verjaardag) For copyright status see: http://www.bbc.co.uk/news/world-us-canada-34332853 """ - WEDDING: Tuple[str, ...] -"""Melody: the bridal chorus from Wagner’s opera “Lohengrin”.""" - +"""Melodie: het bruidskoor van de opera van Wagner “Lohengrin”. (bruiloft)""" FUNERAL: Tuple[str, ...] -"""Melody: the “funeral march” otherwise known as Frédéric Chopin’s Piano Sonata No. 2 in B♭ minor, Op. 35.""" - +"""Melody: de “begrafenismars” die ook bekend staat als Frédéric Chopin’s Piano Sonata No. 2 in B♭ minor, Op. 35. (begrafenis)""" PUNCHLINE: Tuple[str, ...] -"""Melody: a fun fragment that signifies a joke has been made.""" - +"""Melodie: een grappig fragment dat aangeeft dat er een grap is gemaakt. (clou)""" PYTHON: Tuple[str, ...] -"""Melody: John Philip Sousa’s march “Liberty Bell” aka, the theme for “Monty Python’s Flying Circus” (after which the Python programming language is named).""" - +"""Melodie: John Philip Sousa's mars "Liberty Bell", ook bekend als het thema voor "Monty Python's Flying Circus" (waarnaar de programmeertaal Python is vernoemd).""" BADDY: Tuple[str, ...] -"""Melody: silent movie era entrance of a baddy.""" - +"""Melodie: stomme filmtijdperk de binnenkomst van een boef. (boef)""" CHASE: Tuple[str, ...] -"""Melody: silent movie era chase scene.""" - +"""Melodie: stille film tijdperk achtervolgings-scène. (achtervolgen)""" BA_DING: Tuple[str, ...] -"""Melody: a short signal to indicate something has happened.""" - +"""Melodie: een kort signaal om aan te geven dat er iets is gebeurd.""" WAWAWAWAA: Tuple[str, ...] -"""Melody: a very sad trombone.""" - +"""Melody: een zeer trieste trombone.""" JUMP_UP: Tuple[str, ...] -"""Melody: for use in a game, indicating upward movement.""" - +"""Melody: voor gebruik in een spel om opwaartse beweging aan te geven. (spring omhoog)""" JUMP_DOWN: Tuple[str, ...] -"""Melody: for use in a game, indicating downward movement.""" - +"""Melody: voor gebruik in een spel, om neerwaartse beweging aan te geven. (spring omlaag)""" POWER_UP: Tuple[str, ...] -"""Melody: a fanfare to indicate an achievement unlocked.""" - +"""Melodie: een fanfare die aantoont dat een prestatie ontgrendeld is. (opstarten)""" POWER_DOWN: Tuple[str, ...] -"""Melody: a sad fanfare to indicate an achievement lost.""" +"""Melody: een droevige fanfare om aan te geven dat een prestatie verloren is gegaan. (afsluiten)""" -def set_tempo(ticks: int = 4, bpm: int = 120) -> None: - """Sets the approximate tempo for playback. +def set_tempo(ticks: int=4, bpm: int=120) -> None: + """Stelt het geschatte tempo in voor het afspelen. (kies tempo) - Example: ``music.set_tempo(bpm=120)`` +Example: ``music.set_tempo(bpm=120)`` - :param ticks: The number of ticks constituting a beat. - :param bpm: An integer determining how many beats per minute. +:param ticks: (tikken) Het aantal tikken in een beat. +:param bpm: Een geheel getal dat het aantal beats per minuut bepaalt. - Suggested default values allow the following useful behaviour: +Suggested default values allow the following useful behaviour: - - music.set_tempo() – reset the tempo to default of ticks = 4, bpm = 120 - - music.set_tempo(ticks=8) – change the “definition” of a beat - - music.set_tempo(bpm=180) – just change the tempo +- music.set_tempo() – reset the tempo to default of ticks = 4, bpm = 120 +- music.set_tempo(ticks=8) – change the “definition” of a beat +- music.set_tempo(bpm=180) – just change the tempo - To work out the length of a tick in milliseconds is very simple arithmetic: - 60000/bpm/ticks_per_beat. For the default values that’s - 60000/120/4 = 125 milliseconds or 1 beat = 500 milliseconds. - """ +To work out the length of a tick in milliseconds is very simple arithmetic: +60000/bpm/ticks_per_beat. For the default values that’s +60000/120/4 = 125 milliseconds or 1 beat = 500 milliseconds.""" ... def get_tempo() -> Tuple[int, int]: - """Gets the current tempo as a tuple of integers: ``(ticks, bpm)``. + """Haalt het huidige tempo op als een heel geheel getal: ``(ticks, bpm)``. (krijg tempo) - Example: ``ticks, beats = music.get_tempo()`` +Example: ``ticks, beats = music.get_tempo()`` - :return: The temp as a tuple with two integer values, the ticks then the beats per minute. - """ +:return: The temp as a tuple with two integer values, the ticks then the beats per minute.""" ... -def play( - music: Union[str, List[str], Tuple[str, ...]], - pin: Optional[MicroBitDigitalPin] = pin0, - wait: bool = True, - loop: bool = False, -) -> None: - """Plays music. +def play(music: Union[str, List[str], Tuple[str, ...]], pin: Optional[MicroBitDigitalPin]=pin0, wait: bool=True, loop: bool=False) -> None: + """Speelt muziek af. (afspelen) - Example: ``music.play(music.NYAN)`` +Example: ``music.play(music.NYAN)`` - :param music: music specified in `a special notation `_ - :param pin: the output pin for use with an external speaker (default ``pin0``), ``None`` for no sound. - :param wait: If ``wait`` is set to ``True``, this function is blocking. - :param loop: If ``loop`` is set to ``True``, the tune repeats until ``stop`` is called or the blocking call is interrupted. +:param music: (muziek) muziek opgegeven in `a special notation `_ +:param pin: de uitvoer pin voor gebruik met een externe luidspreker (standaard ``pin0``), ``None`` voor geen geluid. +:param wait: (wacht) Als ``wait`` is ingesteld op ``True``wordt deze functie geblokkeerd. +:param loop: Als ``loop`` is ingesteld op ``True``herhaalt de melodie tot ``stop`` wordt opgeroepen of wordt de blokkerende oproep word onderbroken. - Many built-in melodies are defined in this module. - """ +Many built-in melodies are defined in this module.""" ... -def pitch( - frequency: int, - duration: int = -1, - pin: Optional[MicroBitDigitalPin] = pin0, - wait: bool = True, -) -> None: - """Play a note. +def pitch(frequency: int, duration: int=-1, pin: Optional[MicroBitDigitalPin]=pin0, wait: bool=True) -> None: + """Speel een noot. (toonhoogte) - Example: ``music.pitch(185, 1000)`` +Example: ``music.pitch(185, 1000)`` - :param frequency: An integer frequency - :param duration: A millisecond duration. If negative then sound is continuous until the next call or a call to ``stop``. - :param pin: Optional output pin (default ``pin0``). - :param wait: If ``wait`` is set to ``True``, this function is blocking. +:param frequency: (frequentie) Een integere frequentie +:param duration: (Duur) Een milliseconde duur. Als negatief dan gaat het geluid door tot de volgende oproep of een oproep tot ``stop``. +:param pin: Optionele uitvoer pin (standaard ``pin0``). +:param wait: (wacht) Als ``wait`` is ingesteld op ``True``wordt deze functie geblokkeerd. - For example, if the frequency is set to 440 and the length to - 1000 then we hear a standard concert A for one second. +For example, if the frequency is set to 440 and the length to +1000 then we hear a standard concert A for one second. - You can only play one pitch on one pin at any one time. - """ +You can only play one pitch on one pin at any one time.""" ... -def stop(pin: Optional[MicroBitDigitalPin] = pin0) -> None: - """Stops all music playback on the built-in speaker and any pin outputting sound. +def stop(pin: Optional[MicroBitDigitalPin]=pin0) -> None: + """Stopt alle muziek op de ingebouwde luidspreker en elke pin die geluid uitzendt. - Example: ``music.stop()`` +Example: ``music.stop()`` - :param pin: An optional argument can be provided to specify a pin, e.g. ``music.stop(pin1)``. - """ +:param pin: Een optioneel argument kan worden opgegeven om een pin op te geven, bijvoorbeeld ``music.stop(pin1)``.""" def reset() -> None: - """Resets ticks, bpm, duration and octave to their default values. + """Reset ticks, bpm, duur en octaven naar hun standaardwaarden. - Example: ``music.reset()`` +Example: ``music.reset()`` - Values: - - ``ticks = 4`` - - ``bpm = 120`` - - ``duration = 4`` - - ``octave = 4`` - """ - ... +Values: +- ``ticks = 4`` +- ``bpm = 120`` +- ``duration = 4`` +- ``octave = 4``""" + ... \ No newline at end of file diff --git a/lang/nl/typeshed/stdlib/neopixel.pyi b/lang/nl/typeshed/stdlib/neopixel.pyi index 2d5a749..93183ed 100644 --- a/lang/nl/typeshed/stdlib/neopixel.pyi +++ b/lang/nl/typeshed/stdlib/neopixel.pyi @@ -1,82 +1,81 @@ -"""Individually addressable RGB and RGBW LED strips. -""" +"""Individueel adresseerbare RGB en RGBW LED-strips.""" from .microbit import MicroBitDigitalPin from typing import Tuple class NeoPixel: - def __init__(self, pin: MicroBitDigitalPin, n: int, bpp: int = 3) -> None: - """Initialise a new strip of neopixel LEDs controlled via a pin. - Example: ``np = neopixel.NeoPixel(pin0, 8)`` + def __init__(self, pin: MicroBitDigitalPin, n: int, bpp: int=3) -> None: + """Initialiseer een nieuwe strip van neopixel LED's beheerd via een pin. (initialiseren) - To support RGBW neopixels, a third argument can be passed to - ``NeoPixel`` to indicate the number of bytes per pixel (``bpp``). - For RGBW, this is is 4 rather than the default of 3 for RGB and GRB. +Example: ``np = neopixel.NeoPixel(pin0, 8)`` - Each pixel is addressed by a position (starting from 0). Neopixels are - given RGB (red, green, blue) / RGBW (red, green, blue, white) values - between 0-255 as a tuple. For example, in RGB, ``(255,255,255)`` is - white. In RGBW, ``(255,255,255,0)`` or ``(0,0,0,255)`` is white. +To support RGBW neopixels, a third argument can be passed to +``NeoPixel`` to indicate the number of bytes per pixel (``bpp``). +For RGBW, this is is 4 rather than the default of 3 for RGB and GRB. - See `the online docs `_ for warnings and other advice. +Each pixel is addressed by a position (starting from 0). Neopixels are +given RGB (red, green, blue) / RGBW (red, green, blue, white) values +between 0-255 as a tuple. For example, in RGB, ``(255,255,255)`` is +white. In RGBW, ``(255,255,255,0)`` or ``(0,0,0,255)`` is white. - :param pin: The pin controlling the neopixel strip. - :param n: The number of neopixels in the strip. - :param bpp: Bytes per pixel. For RGBW neopixel support, pass 4 rather than the default of 3 for RGB and GRB. - """ +See `the online docs `_ for warnings and other advice. + +:param pin: De pin regelt de neopixelstrook. +:param n: Het aantal neopixels in de strip. +:param bpp: Bytes per pixel. Voor ondersteuning van RGBW neopixels geeft je 4 aan in plaats van de standaardwaarde van 3 voor RGB en GRB.""" ... + def clear(self) -> None: - """Clear all the pixels. + """Verwijder alle pixels. (wissen) - Example: ``np.clear()`` - """ +Example: ``np.clear()``""" ... + def show(self) -> None: - """Show the pixels. + """Toon de pixels. (toon) - Example: ``np.show()`` +Example: ``np.show()`` - Must be called for any updates to become visible. - """ +Must be called for any updates to become visible.""" ... + def write(self) -> None: - """Show the pixels (micro:bit V2 only). + """Toon de pixels (alleen micro:bit V2). (schrijven) - Example: ``np.write()`` +Example: ``np.write()`` - Must be called for any updates to become visible. +Must be called for any updates to become visible. - Equivalent to ``show``. - """ +Equivalent to ``show``.""" ... + def fill(self, colour: Tuple[int, ...]) -> None: - """Colour all pixels a given RGB/RGBW value (micro:bit V2 only). + """Kleur alle pixels een bepaalde RGB/RGBW waarde (alleen micro:bit V2). (opvullen) - Example: ``np.fill((0, 0, 255))`` +Example: ``np.fill((0, 0, 255))`` - :param colour: A tuple of the same length as the number of bytes per pixel (bpp). +:param colour: (kleur) Een tuple van dezelfde lengte als het aantal bytes per pixel (bpp). - Use in conjunction with ``show()`` to update the neopixels. - """ +Use in conjunction with ``show()`` to update the neopixels.""" ... + def __setitem__(self, key: int, value: Tuple[int, ...]) -> None: - """Set a pixel colour. + """Stel een pixelkleur in. - Example: ``np[0] = (255, 0, 0)`` +Example: ``np[0] = (255, 0, 0)`` + +:param key: (sleutel) Het pixelnummer. +:param value: (waarde) De kleur.""" - :param key: The pixel number. - :param value: The colour. - """ def __getitem__(self, key: int) -> Tuple[int, ...]: - """Get a pixel colour. + """Krijg een pixelkleur. + +Example: ``r, g, b = np[0]`` - Example: ``r, g, b = np[0]`` +:param key: (sleutel) Het pixelnummer. +:return: The colour tuple.""" - :param key: The pixel number. - :return: The colour tuple. - """ def __len__(self) -> int: - """Get length of this pixel strip. + """Haal de lengte op van deze pixelstrip. - Example: ``len(np)`` - """ +Example: ``len(np)``""" \ No newline at end of file diff --git a/lang/nl/typeshed/stdlib/os.pyi b/lang/nl/typeshed/stdlib/os.pyi index 2f2db77..bfa6adf 100644 --- a/lang/nl/typeshed/stdlib/os.pyi +++ b/lang/nl/typeshed/stdlib/os.pyi @@ -1,73 +1,63 @@ -"""Access the file system. -""" - +"""Toegang tot het bestandssysteem.""" from typing import Tuple from typing import List def listdir() -> List[str]: - """List files. + """Bestanden weergeven. - Example: ``os.listdir()`` +Example: ``os.listdir()`` - :return: A list of the names of all the files contained within the local - persistent on-device file system. - """ +:return: A list of the names of all the files contained within the local +persistent on-device file system.""" ... def remove(filename: str) -> None: - """Remove (delete) a file. + """Verwijder (verwijder) een bestand. (verwijder) - Example: ``os.remove('data.txt')`` +Example: ``os.remove('data.txt')`` - :param filename: The file to delete. +:param filename: (bestands naam) Het bestand is verwijderd - If the file does not exist an ``OSError`` exception will occur. - """ +If the file does not exist an ``OSError`` exception will occur.""" ... def size(filename: str) -> int: - """Returns the size of a file. + """Geeft de grootte van een bestand weer. (grootte) - Example: ``os.size('data.txt')`` +Example: ``os.size('data.txt')`` - :param filename: The file - :return: The size in bytes. +:param filename: (bestands naam) Het bestand +:return: The size in bytes. - If the file does not exist an ``OSError`` exception will occur. - """ +If the file does not exist an ``OSError`` exception will occur.""" class uname_result(Tuple[str, str, str, str, str]): - """Result of ``os.uname()``""" + """Resultaat van ``os.uname()`` (uname resultaat)""" sysname: str - """Operating system name.""" - + """Besturingssysteem naam""" nodename: str - """Name of machine on network (implementation-defined).""" - + """Naam van machine op het netwerk (implementation-defined).""" release: str - """Operating system release.""" - + """Besturingssysteem release. (vrijgeven)""" version: str - """Operating system version.""" - + """Besturingssysteem versie. (versie)""" machine: str - """Hardware identifier.""" + """Identificatie hardware""" def uname() -> uname_result: - """Returns information identifying the current operating system. + """Geeft informatie terug die het huidige besturingssysteem identificeert. - Example: ``os.uname()`` +Example: ``os.uname()`` - The return value is an object with five attributes: +The return value is an object with five attributes: - - ``sysname`` - operating system name - - ``nodename`` - name of machine on network (implementation-defined) - - ``release`` - operating system release - - ``version`` - operating system version - - ``machine`` - hardware identifier +- ``sysname`` - operating system name +- ``nodename`` - name of machine on network (implementation-defined) +- ``release`` - operating system release +- ``version`` - operating system version +- ``machine`` - hardware identifier - There is no underlying operating system in MicroPython. As a result the - information returned by the ``uname`` function is mostly useful for - versioning details. - """ - ... +There is no underlying operating system in MicroPython. As a result the +information returned by the ``uname`` function is mostly useful for +versioning details.""" + ... \ No newline at end of file diff --git a/lang/nl/typeshed/stdlib/radio.pyi b/lang/nl/typeshed/stdlib/radio.pyi index 8dd0267..656cb19 100644 --- a/lang/nl/typeshed/stdlib/radio.pyi +++ b/lang/nl/typeshed/stdlib/radio.pyi @@ -1,152 +1,130 @@ -"""Communicate between micro:bits with the built-in radio. -""" - +"""Communiceer tussen micro:bits met de ingebouwde radio.""" from _typeshed import WriteableBuffer from typing import Optional, Tuple - RATE_1MBIT: int -"""Constant used to indicate a throughput of 1 MBit a second.""" - +"""Constante gebruikt om een doorvoer van 1 MBit per seconde aan te geven.""" RATE_2MBIT: int -"""Constant used to indicate a throughput of 2 MBit a second.""" +"""Constante gebruikt om een doorvoer van 2 MBit per seconde aan te geven.""" def on() -> None: - """Turns the radio on. + """Zet de radio aan. (aan) - Example: ``radio.on()`` +Example: ``radio.on()`` - This needs to be explicitly called since the radio draws power and takes - up memory that you may otherwise need. - """ +This needs to be explicitly called since the radio draws power and takes +up memory that you may otherwise need.""" ... def off() -> None: - """Turns off the radio, saving power and memory. + """Schakelt de radio uit, bespaar stroom en geheugen. (uit) - Example: ``radio.off()`` - """ +Example: ``radio.off()``""" ... -def config( - length: int = 32, - queue: int = 3, - channel: int = 7, - power: int = 6, - address: int = 0x75626974, - group: int = 0, - data_rate: int = RATE_1MBIT, -) -> None: - """Configures the radio. - - Example: ``radio.config(group=42)`` - - The default configuration is suitable for most use. - - :param length: (default=32) defines the maximum length, in bytes, of a message sent via the radio. - It can be up to 251 bytes long (254 - 3 bytes for S0, LENGTH and S1 preamble). - :param queue: (default=3) specifies the number of messages that can be stored on the incoming message queue. - If there are no spaces left on the queue for incoming messages, then the incoming message is dropped. - :param channel: (default=7) an integer value from 0 to 83 (inclusive) that defines an arbitrary "channel" to which the radio is tuned. - Messages will be sent via this channel and only messages received via this channel will be put onto the incoming message queue. Each step is 1MHz wide, based at 2400MHz. - :param power: (default=6) is an integer value from 0 to 7 (inclusive) to indicate the strength of signal used when broadcasting a message. - The higher the value the stronger the signal, but the more power is consumed by the device. The numbering translates to positions in the following list of dBm (decibel milliwatt) values: -30, -20, -16, -12, -8, -4, 0, 4. - :param address: (default=0x75626974) an arbitrary name, expressed as a 32-bit address, that's used to filter incoming packets at the hardware level, keeping only those that match the address you set. - The default used by other micro:bit related platforms is the default setting used here. - :param group: (default=0) an 8-bit value (0-255) used with the ``address`` when filtering messages. - Conceptually, "address" is like a house/office address and "group" is like the person at that address to which you want to send your message. - :param data_rate: (default=``radio.RATE_1MBIT``) indicates the speed at which data throughput takes place. - Can be one of the following constants defined in the ``radio`` module: ``RATE_250KBIT``, ``RATE_1MBIT`` or ``RATE_2MBIT``. - - If ``config`` is not called then the defaults described above are assumed. - """ +def config(length: int=32, queue: int=3, channel: int=7, power: int=6, address: int=1969383796, group: int=0, data_rate: int=RATE_1MBIT) -> None: + """Configureert de radio. (configuratie) + +Example: ``radio.config(group=42)`` + +The default configuration is suitable for most use. + +:param length: (lengte) (default=32) definieert de maximale lengte, in bytes, van een bericht dat via de radio wordt verzonden. +Het kan maximaal 251 bytes lang zijn (254 - 3 bytes voor S0, LENGTH en S1 preamble). +:param queue: (wachtrij) (standaard=3) geeft het aantal berichten aan dat in de wachtrij van het inkomende bericht kan worden opgeslagen. +Als er geen ruimte meer is in de wachtrij voor binnenkomende berichten, dan valt het inkomende bericht weg. +:param channel: (kanaal) (default=7) een integer waarde van 0 tot 83 (inclusief) die een willekeurig "kanaal" definieert waaraan de radio wordt afgestemd. +Berichten worden via dit kanaal verzonden en alleen via dit kanaal worden berichten in de wachtrij van het inkomende berichten geplaatst. Elke stap is 1 MHz breed, gebaseerd op 2400MHz. +:param power: (vermogen) (default=6) is een integer waarde van 0 tot 7 (inclusief) om de sterkte van het signaal aan te geven dat wordt gebruikt bij het uitzenden van een bericht. +Hoe hoger de waarde, des te sterker het signaal, maar hoe meer stroom het apparaat verbruikt. De nummering vertaalt naar posities in de volgende lijst van dBm (decibel milliwatt) waarden: -30, -20, -16, -12, -8, -4, 0, 4. +:param address: (adres) (default=0x75626974) een willekeurige naam, uitgedrukt als een 32-bits adres, wordt gebruikt om inkomende pakketten op hardware-niveau te filteren, waarbij alleen de pakketten worden bewaard die overeenkomen met het adres dat je zelf instelt. +De standaard gebruiker door andere micro:bit gerelateerde platforms is de standaard instelling die hier wordt gebruikt. +:param group: (groep) (standaard=0) een 8-bit waarde (0-255) gebruikt met de ``address`` bij het filteren van berichten. +Conceptueel, "adres" is als een huis/kantooradres en "groep" is als de persoon op dat adres waarnaar je je bericht wilt sturen. +:param data_rate: (Gegevens snelheid) (default=``radio.RATE_1MBIT``) geeft aan hoe snel de doorvoer van gegevens plaatsvindt. +Kan een van de volgende constanten zijn gedefinieerd in de ``radio`` module: ``RATE_250KBIT``, ``RATE_1MBIT`` of ``RATE_2MBIT``. + +If ``config`` is not called then the defaults described above are assumed.""" ... def reset() -> None: - """Reset the settings to their default values. + """Reset alle instellingen naar hun standaardwaarde. - Example: ``radio.reset()`` +Example: ``radio.reset()`` - The defaults as as per the ``config`` function above. - """ +The defaults as as per the ``config`` function above.""" ... def send_bytes(message: bytes) -> None: - """Sends a message containing bytes. + """Stuurt een bericht met bytes. (verstuur bytes) - Example: ``radio.send_bytes(b'hello')`` +Example: ``radio.send_bytes(b'hello')`` - :param message: The bytes to send. - """ +:param message: (bericht) De te verzenden bytes.""" ... def receive_bytes() -> Optional[bytes]: - """Receive the next incoming message on the message queue. + """Ontvang het volgende inkomende bericht in de wachtrij van het bericht. (ontvang bytes) - Example: ``radio.receive_bytes()`` +Example: ``radio.receive_bytes()`` - :return: The message bytes if any, otherwise ``None``. - """ +:return: The message bytes if any, otherwise ``None``.""" ... def receive_bytes_into(buffer: WriteableBuffer) -> Optional[int]: - """Copy the next incoming message on the message queue into a buffer. + """Kopieer het volgende inkomende bericht in de wachtrij van het bericht naar een buffer. (ontvang bytes in) - Example: ``radio.receive_bytes_info(buffer)`` +Example: ``radio.receive_bytes_info(buffer)`` - :param buffer: The target buffer. The message is truncated if larger than the buffer. - :return: ``None`` if there are no pending messages, otherwise it returns the length of the message (which might be more than the length of the buffer). - """ +:param buffer: De doel buffer. Het bericht wordt ingekort als het groter is dan de buffer. +:return: ``None`` if there are no pending messages, otherwise it returns the length of the message (which might be more than the length of the buffer).""" ... def send(message: str) -> None: - """Sends a message string. + """Stuurt een berichtenreeks. (verzenden) - Example: ``radio.send('hello')`` +Example: ``radio.send('hello')`` - This is the equivalent of ``radio.send_bytes(bytes(message, 'utf8'))`` but with ``b'\x01\x00\x01'`` - prepended to the front (to make it compatible with other platforms that target the micro:bit). +This is the equivalent of ``radio.send_bytes(bytes(message, 'utf8'))`` but with ``b'\x01\x00\x01'`` +prepended to the front (to make it compatible with other platforms that target the micro:bit). - :param message: The string to send. - """ +:param message: (bericht) De te verzenden tekenreeks.""" ... def receive() -> Optional[str]: - """Works in exactly the same way as ``receive_bytes`` but returns whatever was sent. + """Werkt op precies dezelfde manier als ``receive_bytes`` , maar retourneert wat er verzonden is. (ontvang) - Example: ``radio.receive()`` +Example: ``radio.receive()`` - Equivalent to ``str(receive_bytes(), 'utf8')`` but with a check that the the first - three bytes are ``b'\x01\x00\x01'`` (to make it compatible with other platforms that - may target the micro:bit). +Equivalent to ``str(receive_bytes(), 'utf8')`` but with a check that the the first +three bytes are ``b'\x01\x00\x01'`` (to make it compatible with other platforms that +may target the micro:bit). - :return: The message with the prepended bytes stripped and converted to a string. +:return: The message with the prepended bytes stripped and converted to a string. - A ``ValueError`` exception is raised if conversion to string fails. - """ +A ``ValueError`` exception is raised if conversion to string fails.""" ... def receive_full() -> Optional[Tuple[bytes, int, int]]: - """Returns a tuple containing three values representing the next incoming message on the message queue. + """Geeft als resultaat een dup met drie waarden die het volgende inkomende bericht in de wachtrij van het bericht weergeven. (Ontvang vol) - Example: ``radio.receive_full()`` +Example: ``radio.receive_full()`` - If there are no pending messages then ``None`` is returned. +If there are no pending messages then ``None`` is returned. - The three values in the tuple represent: +The three values in the tuple represent: - - the next incoming message on the message queue as bytes. - - the RSSI (signal strength): a value between 0 (strongest) and -255 (weakest) as measured in dBm. - - a microsecond timestamp: the value returned by ``time.ticks_us()`` when the message was received. +- the next incoming message on the message queue as bytes. +- the RSSI (signal strength): a value between 0 (strongest) and -255 (weakest) as measured in dBm. +- a microsecond timestamp: the value returned by ``time.ticks_us()`` when the message was received. - For example:: +For example:: - details = radio.receive_full() - if details: - msg, rssi, timestamp = details + details = radio.receive_full() + if details: + msg, rssi, timestamp = details - This function is useful for providing information needed for triangulation - and/or trilateration with other micro:bit devices. +This function is useful for providing information needed for triangulation +and/or trilateration with other micro:bit devices. - :return: ``None`` if there is no message, otherwise a tuple of length three with the bytes, strength and timestamp values. - """ - ... +:return: ``None`` if there is no message, otherwise a tuple of length three with the bytes, strength and timestamp values.""" + ... \ No newline at end of file diff --git a/lang/nl/typeshed/stdlib/random.pyi b/lang/nl/typeshed/stdlib/random.pyi index a2c2ef3..32acd0e 100644 --- a/lang/nl/typeshed/stdlib/random.pyi +++ b/lang/nl/typeshed/stdlib/random.pyi @@ -1,93 +1,81 @@ -"""Generate random numbers. -""" +"""Willekeurige getallen genereren. (willekeurig)""" from typing import TypeVar, Sequence, Union, overload def getrandbits(n: int) -> int: - """Generate an integer with ``n`` random bits. + """Genereer een geheel getal met ``n`` willekeurige bits. - Example: ``random.getrandbits(1)`` +Example: ``random.getrandbits(1)`` - :param n: A value between 1-30 (inclusive). - """ +:param n: Een waarde tussen 1-30 (inclusief).""" ... def seed(n: int) -> None: - """Initialize the random number generator. + """Initialiseer de willekeurige getalgenerator. - Example: ``random.seed(0)`` +Example: ``random.seed(0)`` - :param n: The integer seed +:param n: De integer seed - This will give you reproducibly deterministic randomness from a given starting - state (``n``). - """ +This will give you reproducibly deterministic randomness from a given starting +state (``n``).""" ... def randint(a: int, b: int) -> int: - """Choose a random integer between ``a`` and ``b`` inclusive. + """Kies een willekeurig geheel getal tussen ``a`` en ``b`` inclusief. - Example: ``random.randint(0, 9)`` +Example: ``random.randint(0, 9)`` - :param a: Start value for the range (inclusive) - :param b: End value for the range (inclusive) +:param a: Beginwaarde voor het bereik (inclusief) +:param b: Eindwaarde voor het bereik (inclusief) - Alias for ``randrange(a, b + 1)``. - """ +Alias for ``randrange(a, b + 1)``.""" ... @overload def randrange(stop: int) -> int: - """Choose a randomly selected integer between zero and up to (but not - including) ``stop``. + """Kies een willekeurig geselecteerd geheel getal tussen nul en tot (maar niet +inclusief) ``stop``. - Example: ``random.randrange(10)`` +Example: ``random.randrange(10)`` - :param stop: End value for the range (exclusive) - """ +:param stop: Eindwaarde voor het bereik (exclusief)""" ... @overload -def randrange(start: int, stop: int, step: int = 1) -> int: - """ - Choose a randomly selected element from ``range(start, stop, step)``. +def randrange(start: int, stop: int, step: int=1) -> int: + """Kies een willekeurig geselecteerd element uit ``range(start, stop, step)``. - Example: ``random.randrange(0, 10)`` +Example: ``random.randrange(0, 10)`` - :param start: The start of the range (inclusive) - :param stop: The end of the range (exclusive) - :param step: The step. - """ +:param start: Het begin van het bereik (inclusief) +:param stop: Einde van het bereik (exclusief) +:param step: (stap) De stap.""" ... - -_T = TypeVar("_T") +_T = TypeVar('_T') def choice(seq: Sequence[_T]) -> _T: - """Choose a random element from the non-empty sequence ``seq``. + """Kies een willekeurig element uit de niet-lege reeks ``seq``. (keuze) - Example: ``random.choice([Image.HAPPY, Image.SAD])`` +Example: ``random.choice([Image.HAPPY, Image.SAD])`` - :param seq: A sequence. +:param seq: Een volgorde. - If ``seq`` is empty, raises ``IndexError``. - """ +If ``seq`` is empty, raises ``IndexError``.""" ... def random() -> float: - """Generate a random floating point number in the range [0.0, 1.0). + """Genereer een willekeurig zwevend puntnummer in het bereik [0.0, 1.0). (willekeurig) - Example: ``random.random()`` +Example: ``random.random()`` - :return: The random floating point number - """ +:return: The random floating point number""" ... def uniform(a: float, b: float) -> float: - """ - Return a random floating point number between ``a`` and ``b`` inclusive. + """Geeft een willekeurig zwevend punt nummer tussen ``a`` en ``b`` inclusief. - Example: ``random.uniform(0, 9)`` +Example: ``random.uniform(0, 9)`` - :param a: Start value for the range (inclusive) - :param b: End value for the range (inclusive) - """ - ... +:param a: Beginwaarde voor het bereik (inclusief) +:param b: Eindwaarde voor het bereik (inclusief)""" + ... \ No newline at end of file diff --git a/lang/nl/typeshed/stdlib/speech.pyi b/lang/nl/typeshed/stdlib/speech.pyi index 349d188..2075501 100644 --- a/lang/nl/typeshed/stdlib/speech.pyi +++ b/lang/nl/typeshed/stdlib/speech.pyi @@ -1,106 +1,76 @@ -"""Make the micro:bit talk, sing and make other speech like sounds. -""" - +"""Laat de micro:bit praten, zingen en andere spraak maken, zoals geluid. (spraak)""" from typing import Optional from .microbit import MicroBitDigitalPin, pin0 def translate(words: str) -> str: - """Translate English words to phonemes. + """Vertaal Engelse woorden naar fonemen. (vertalen) - Example: ``speech.translate('hello world')`` +Example: ``speech.translate('hello world')`` - :param words: A string of English words. - :return: A string containing a best guess at the appropriate phonemes to pronounce. - The output is generated from this `text to phoneme translation table `_. +:param words: (woorden) Een tekenreeks Engelse woorden. +:return: A string containing a best guess at the appropriate phonemes to pronounce. +The output is generated from this `text to phoneme translation table `_. - This function should be used to generate a first approximation of phonemes - that can be further hand-edited to improve accuracy, inflection and - emphasis. +This function should be used to generate a first approximation of phonemes +that can be further hand-edited to improve accuracy, inflection and +emphasis. - See `the online documentation `_ for detailed information. - """ +See `the online documentation `_ for detailed information.""" ... -def pronounce( - phonemes: str, - pitch: int = 64, - speed: int = 72, - mouth: int = 128, - throat: int = 128, - pin: Optional[MicroBitDigitalPin] = pin0, -) -> None: - """Pronounce phonemes. - - Example: ``speech.pronounce(' /HEHLOW WERLD')`` - - :param phonemes: The string of phonemes to pronounce - :param pitch: A number representing the pitch of the voice - :param speed: A number representing the speed of the voice - :param mouth: A number representing the mouth of the voice - :param throat: A number representing the throat of the voice - :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. - If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. - - Override the optional pitch, speed, mouth and throat settings to change the - timbre (quality) of the voice. - - See `the online documentation `_ for detailed information. - """ - ... +def pronounce(phonemes: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: Optional[MicroBitDigitalPin]=pin0) -> None: + """Uitspraak phonemes. (uitspreken) + +Example: ``speech.pronounce(' /HEHLOW WERLD')`` + +:param phonemes: (fonemen) De reeks fonemen om uit te spreken +:param pitch: (toonhoogte) Een nummer dat de toonhoogte van de stem weergeeft +:param speed: (snelheid) Een nummer dat de snelheid van de stem vertegenwoordigt +:param mouth: (mond) Een nummer dat de mond van de stem weergeeft +:param throat: (keel) Een nummer dat de keel van de stem weergeeft +:param pin: Een optioneel argument om de uitvoer pin op te geven, kan worden gebruikt om de standaard van ``pin0``te overschrijven. Als we geen geluid willen afspelen, kunnen we ``pin=None`` gebruiken. Alleen voor micro:bit V2. -def say( - words: str, - pitch: int = 64, - speed: int = 72, - mouth: int = 128, - throat: int = 128, - pin: MicroBitDigitalPin = pin0, -) -> None: - """Say English words. - - Example: ``speech.say('hello world')`` - - :param words: The string of words to say. - :param pitch: A number representing the pitch of the voice - :param speed: A number representing the speed of the voice - :param mouth: A number representing the mouth of the voice - :param throat: A number representing the throat of the voice - :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. - If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. - - The result is semi-accurate for English. Override the optional pitch, speed, - mouth and throat settings to change the timbre (quality) of the voice. - - This is a short-hand equivalent of: - ``speech.pronounce(speech.translate(words))`` - - See `the online documentation `_ for detailed information. - """ +Override the optional pitch, speed, mouth and throat settings to change the +timbre (quality) of the voice. + +See `the online documentation `_ for detailed information.""" ... -def sing( - phonemes: str, - pitch: int = 64, - speed: int = 72, - mouth: int = 128, - throat: int = 128, - pin: MicroBitDigitalPin = pin0, -) -> None: - """Sing phonemes. - - Example: ``speech.sing(' /HEHLOW WERLD')`` - - :param phonemes: The string of words to sing. - :param pitch: A number representing the pitch of the voice - :param speed: A number representing the speed of the voice - :param mouth: A number representing the mouth of the voice - :param throat: A number representing the throat of the voice - :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. - If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. - - Override the optional pitch, speed, mouth and throat settings to change - the timbre (quality) of the voice. - - See `the online documentation `_ for detailed information. - """ +def say(words: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: MicroBitDigitalPin=pin0) -> None: + """Zeg Engelse woorden. (zeg) + +Example: ``speech.say('hello world')`` + +:param words: (woorden) De tekenreeks van woorden om te zeggen. +:param pitch: (toonhoogte) Een nummer dat de toonhoogte van de stem weergeeft +:param speed: (snelheid) Een nummer dat de snelheid van de stem vertegenwoordigt +:param mouth: (mond) Een nummer dat de mond van de stem weergeeft +:param throat: (keel) Een nummer dat de keel van de stem weergeeft +:param pin: Een optioneel argument om de uitvoer pin op te geven, kan worden gebruikt om de standaard van ``pin0``te overschrijven. Als we geen geluid willen afspelen, kunnen we ``pin=None`` gebruiken. Alleen voor micro:bit V2. + +The result is semi-accurate for English. Override the optional pitch, speed, +mouth and throat settings to change the timbre (quality) of the voice. + +This is a short-hand equivalent of: +``speech.pronounce(speech.translate(words))`` + +See `the online documentation `_ for detailed information.""" ... + +def sing(phonemes: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: MicroBitDigitalPin=pin0) -> None: + """Zing fonemen. (zing) + +Example: ``speech.sing(' /HEHLOW WERLD')`` + +:param phonemes: (fonemen) De tekenreeks van woorden om te zingen. +:param pitch: (toonhoogte) Een nummer dat de toonhoogte van de stem weergeeft +:param speed: (snelheid) Een nummer dat de snelheid van de stem vertegenwoordigt +:param mouth: (mond) Een nummer dat de mond van de stem weergeeft +:param throat: (keel) Een nummer dat de keel van de stem weergeeft +:param pin: Een optioneel argument om de uitvoer pin op te geven, kan worden gebruikt om de standaard van ``pin0``te overschrijven. Als we geen geluid willen afspelen, kunnen we ``pin=None`` gebruiken. Alleen voor micro:bit V2. + +Override the optional pitch, speed, mouth and throat settings to change +the timbre (quality) of the voice. + +See `the online documentation `_ for detailed information.""" + ... \ No newline at end of file diff --git a/lang/nl/typeshed/stdlib/struct.pyi b/lang/nl/typeshed/stdlib/struct.pyi index 53b3e0b..f88dc4a 100644 --- a/lang/nl/typeshed/stdlib/struct.pyi +++ b/lang/nl/typeshed/stdlib/struct.pyi @@ -1,65 +1,56 @@ -"""Pack and unpack primitive data types. -""" - +"""Primitieve datatypes inpakken en uitpakken.""" from _typeshed import ReadableBuffer, WriteableBuffer from typing import Any, Tuple, Union def calcsize(fmt: str) -> int: - """Get the number of bytes needed to store the given ``fmt``. + """Haal het aantal bytes op dat nodig is om de gegeven ``fmt`` op te slaan. - Example: ``struct.calcsize('hf')`` +Example: ``struct.calcsize('hf')`` - :param fmt: A format string. - :return The number of bytes needed to store such a value. - """ +:param fmt: Tekenreeks opmaak. +:return The number of bytes needed to store such a value.""" ... def pack(fmt: str, v1: Any, *vn: Any) -> bytes: - """Pack values according to a format string. + """Verpak de waarden op basis van een string formaat. (inpakken) - Example: ``struct.pack('hf', 1, 3.1415)`` +Example: ``struct.pack('hf', 1, 3.1415)`` - :param fmt: The format string. - :param v1: The first value. - :param *vn: The remaining values. - :return A bytes object encoding the values. - """ +:param fmt: De formaat tekenreeks. +:param v1: De eerste waarde. +:param *vn: De resterende waarden. +:return A bytes object encoding the values.""" ... -def pack_into( - fmt: str, buffer: WriteableBuffer, offset: int, v1: Any, *vn: Any -) -> None: - """Pack values according to a format string. +def pack_into(fmt: str, buffer: WriteableBuffer, offset: int, v1: Any, *vn: Any) -> None: + """Verpak de waarden op basis van een string formaat. (inpakken) - Example: ``struct.pack_info('hf', buffer, 1, 3.1415)`` +Example: ``struct.pack_info('hf', buffer, 1, 3.1415)`` - :param fmt: The format string. - :param buffer: The target buffer to write into. - :param offset: The offset into the buffer. May be negative to count from the end of the buffer. - :param v1: The first value. - :param *vn: The remaining values. - """ +:param fmt: De formaat tekenreeks. +:param buffer: De doelbuffer om in te schrijven. +:param offset: (Offset) De compensatie in de buffer. Kan negatief zijn om te tellen aan het einde van de buffer. +:param v1: De eerste waarde. +:param *vn: De resterende waarden.""" ... def unpack(fmt: str, data: ReadableBuffer) -> Tuple[Any, ...]: - """Unpack data according to a format string. + """Uitpakken van gegevens volgens een opmaakreeks. (uitpakken) - Example: ``v1, v2 = struct.unpack('hf', buffer)`` +Example: ``v1, v2 = struct.unpack('hf', buffer)`` - :param fmt: The format string. - :param data: The data. - :return: A tuple of the unpacked values. - """ +:param fmt: De formaat tekenreeks. +:param data: (gegevens) De gegevens. +:return: A tuple of the unpacked values.""" ... -def unpack_from(fmt: str, buffer: ReadableBuffer, offset: int = 0) -> Tuple: - """Unpack data from a buffer according to a format string. +def unpack_from(fmt: str, buffer: ReadableBuffer, offset: int=0) -> Tuple: + """Uitpakken van gegevens van een buffer volgens een opmaak. (uitpakken van) - Example: ``v1, v2 = struct.unpack_from('hf', buffer)`` +Example: ``v1, v2 = struct.unpack_from('hf', buffer)`` - :param fmt: The format string. - :param buffer: The source buffer to read from. - :param offset: The offset into the buffer. May be negative to count from the end of the buffer. - :return: A tuple of the unpacked values. - """ - ... +:param fmt: De formaat tekenreeks. +:param buffer: De bronbuffer om uit te lezen. +:param offset: (Offset) De compensatie in de buffer. Kan negatief zijn om te tellen aan het einde van de buffer. +:return: A tuple of the unpacked values.""" + ... \ No newline at end of file diff --git a/lang/nl/typeshed/stdlib/sys.pyi b/lang/nl/typeshed/stdlib/sys.pyi index 320bac9..90c34d5 100644 --- a/lang/nl/typeshed/stdlib/sys.pyi +++ b/lang/nl/typeshed/stdlib/sys.pyi @@ -1,43 +1,36 @@ -"""System specific functions""" - +"""Systeem specifieke functies""" from typing import Any, Dict, List, NoReturn, TextIO, Tuple -def exit(retval: object = ...) -> NoReturn: - """Terminate current program with a given exit code. +def exit(retval: object=...) -> NoReturn: + """Beëindig het huidige programma met een bepaalde exit code. (afsluiten) - Example: ``sys.exit(1)`` +Example: ``sys.exit(1)`` - This function raises a ``SystemExit`` exception. If an argument is given, its - value given as an argument to ``SystemExit``. +This function raises a ``SystemExit`` exception. If an argument is given, its +value given as an argument to ``SystemExit``. - :param retval: The exit code or message. - """ +:param retval: De exit code of bericht.""" ... def print_exception(exc: Exception) -> None: - """ - Print an exception with a traceback. - - Example: ``sys.print_exception(e)`` + """Print een exception met traceback. (exceptie afdrukken) - :param exc: The exception to print +Example: ``sys.print_exception(e)`` - This is simplified version of a function which appears in the - ``traceback`` module in CPython. - """ +:param exc: De af te drukken uitzondering +This is simplified version of a function which appears in the +``traceback`` module in CPython.""" argv: List[str] -"""A mutable list of arguments the current program was started with.""" - +"""Een veranderlijke lijst met argumenten waarmee het huidige programma is gestart.""" byteorder: str -"""The byte order of the system (``"little"`` or ``"big"``).""" +"""De byte volgorde van het systeem (``"little"`` of ``"big"``). (byte volgorde)""" class _implementation: name: str version: Tuple[int, int, int] - implementation: _implementation -"""Object with information about the current Python implementation. +"""Object met informatie over de huidige Python implementatie. (implementatie) For MicroPython, it has following attributes: @@ -51,13 +44,10 @@ minimal ports). CPython mandates more attributes for this object, but the actual useful bare minimum is implemented in MicroPython. """ - maxsize: int """ -Maximum value which a native integer type can hold on the current platform, -or maximum value representable by MicroPython integer type, if it's smaller -than platform max value (that is the case for MicroPython ports without -long int support). +Maximale waarde die een native integer type kan aanhouden op het huidige platform, of de maximale waarde die kan worden vertegenwoordigd door MicroPython integer type, als het kleiner is dan platform max waarde (dat is het geval voor MicroPython poorten zonder +lange int ondersteuning). This attribute is useful for detecting "bitness" of a platform (32-bit vs 64-bit, etc.). It's recommended to not compare this attribute to some @@ -77,17 +67,14 @@ value directly, but instead count number of bits in it:: # (e.g. 31) due to peculiarities described above, so use "> 16", # "> 32", "> 64" style of comparisons. """ - modules: Dict[str, Any] -"""Dictionary of loaded modules. +"""Woordenboek van geladen modules. On some ports, it may not include builtin modules.""" - path: List[str] -"""A mutable list of directories to search for imported modules.""" - +"""Een aanpasbare lijst van mappen om te zoeken naar geïmporteerde modules. (pad)""" platform: str -"""The platform that MicroPython is running on. +"""Het platform waarop MicroPython actief is. For OS/RTOS ports, this is usually an identifier of the OS, e.g. ``"linux"``. For baremetal ports it is an identifier of a board, e.g. ``"pyboard"`` for @@ -97,13 +84,11 @@ distinguish one board from another. If you need to check whether your program runs on MicroPython (vs other Python implementation), use ``sys.implementation`` instead. """ - version: str -"""Python language version that this implementation conforms to, as a string.""" - +"""Python taalversie waar deze implementatie mee overeenstemt als tekenreeks. (versie)""" version_info: Tuple[int, int, int] -"""Python language version that this implementation conforms to, as a tuple of ints. +"""Python taalversie waaraan deze implementatie voldoet, als een tupel van ints. (versie informatie) Only the first three version numbers (major, minor, micro) are supported and they can be referenced only by index, not by name. -""" +""" \ No newline at end of file diff --git a/lang/nl/typeshed/stdlib/time.pyi b/lang/nl/typeshed/stdlib/time.pyi index 598c483..7c26199 100644 --- a/lang/nl/typeshed/stdlib/time.pyi +++ b/lang/nl/typeshed/stdlib/time.pyi @@ -1,132 +1,112 @@ -"""Measure time and add delays to programs. -""" - +"""Meet tijd en voeg vertragingen toe aan programma's. (tijd)""" from typing import Union def sleep(seconds: Union[int, float]) -> None: - """ - Delay a number of seconds. + """Vertraag een aantal seconden. (slapen) - Example: ``time.sleep(1)`` +Example: ``time.sleep(1)`` - :param seconds: The number of seconds to sleep for. - Use a floating-point number to sleep for a fractional number of seconds. - """ +:param seconds: (seconden) Het aantal seconden om voor te slapen. +Gebruik een floating-point nummer om te slapen voor een fractioneel aantal seconden.""" ... def sleep_ms(ms: int) -> None: - """ - Delay for given number of milliseconds. + """Vertraging voor een bepaald aantal milliseconden. (slaap ms) - Example: ``time.sleep_ms(1_000_000)`` +Example: ``time.sleep_ms(1_000_000)`` - :param ms: The number of milliseconds delay (>= 0). - """ +:param ms: Het aantal milliseconden vertraging (>= 0).""" ... def sleep_us(us: int) -> None: - """ - Delay for given number of microseconds. + """Vertraging voor een bepaald aantal microseconden. (slaap us) - Example: ``time.sleep_us(1000)`` +Example: ``time.sleep_us(1000)`` - :param us: The number of microseconds delay (>= 0). - """ +:param us: Het aantal microseconden vertraging (>= 0).""" ... def ticks_ms() -> int: - """ - Get an increasing, millisecond counter with an arbitrary reference point, - that wraps around after some value. + """Krijg een toenemende milliseconde teller met een willekeurig referentiepunt, dat omwikkeld na een waarde. - Example: ``time.ticks_ms()`` +Example: ``time.ticks_ms()`` - :return: The counter value in milliseconds. - """ +:return: The counter value in milliseconds.""" ... def ticks_us() -> int: - """ - Get an increasing, microsecond counter with an arbitrary reference point, - that wraps around after some value. + """Krijg een toenemende milliseconde teller met een willekeurig referentiepunt, dat omwikkeld na een waarde. - Example: ``time.ticks_us()`` +Example: ``time.ticks_us()`` - :return: The counter value in microseconds. - """ +:return: The counter value in microseconds.""" ... def ticks_add(ticks: int, delta: int) -> int: - """ - Offset ticks value by a given number, which can be either positive or - negative. + """Waarde van de offset ticks door een bepaald getal, die ofwel positief ofwel +negatief kan zijn. (ticks toevoegen) - Example: ``time.ticks_add(time.ticks_ms(), 200)`` +Example: ``time.ticks_add(time.ticks_ms(), 200)`` - Given a ticks value, this function allows to calculate ticks - value delta ticks before or after it, following modular-arithmetic - definition of tick values. +Given a ticks value, this function allows to calculate ticks +value delta ticks before or after it, following modular-arithmetic +definition of tick values. - :param ticks: A ticks value - :param delta: An integer offset +:param ticks: (tikken) Een ticks waarde +:param delta: Een integer verschuiving - Example:: +Example:: - # Find out what ticks value there was 100ms ago - print(ticks_add(time.ticks_ms(), -100)) + # Find out what ticks value there was 100ms ago + print(ticks_add(time.ticks_ms(), -100)) - # Calculate deadline for operation and test for it - deadline = ticks_add(time.ticks_ms(), 200) - while ticks_diff(deadline, time.ticks_ms()) > 0: - do_a_little_of_something() + # Calculate deadline for operation and test for it + deadline = ticks_add(time.ticks_ms(), 200) + while ticks_diff(deadline, time.ticks_ms()) > 0: + do_a_little_of_something() - # Find out TICKS_MAX used by this port - print(ticks_add(0, -1)) - """ + # Find out TICKS_MAX used by this port + print(ticks_add(0, -1))""" ... def ticks_diff(ticks1: int, ticks2: int) -> int: - """ - Measure ticks difference between values returned from - ``time.ticks_ms()`` or ``ticks_us()``, as a signed value - which may wrap around. - - Example: ``time.ticks_diff(scheduled_time, now)`` - - :param ticks1: The value to subtract from - :param ticks2: The value to subtract - - The argument order is the same as for subtraction operator, - ``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. - - ``ticks_diff()`` is designed to accommodate various usage - patterns, among them: - - Polling with timeout. In this case, the order of events is known, and you - will deal only with positive results of :func:`time.ticks_diff()`:: - - # Wait for GPIO pin to be asserted, but at most 500us - start = time.ticks_us() - while pin.value() == 0: - if time.ticks_diff(time.ticks_us(), start) > 500: - raise TimeoutError - - - Scheduling events. In this case, :func:`time.ticks_diff()` result may be - negative if an event is overdue:: - - # This code snippet is not optimized - now = time.ticks_ms() - scheduled_time = task.scheduled_time() - if ticks_diff(scheduled_time, now) > 0: - print("Too early, let's nap") - sleep_ms(ticks_diff(scheduled_time, now)) - task.run() - elif ticks_diff(scheduled_time, now) == 0: - print("Right at time!") - task.run() - elif ticks_diff(scheduled_time, now) < 0: - print("Oops, running late, tell task to run faster!") - task.run(run_faster=True) - """ - ... + """Meet het verschil in ticks tussen waarden die worden geretourneerd door ``time.ticks_ms()`` of ``ticks_us()``, als een ondertekende waarde die rond kan lopen. + +Example: ``time.ticks_diff(scheduled_time, now)`` + +:param ticks1: De waarde om van af te trekken +:param ticks2: De waarde om af te trekken + +The argument order is the same as for subtraction operator, +``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. + +``ticks_diff()`` is designed to accommodate various usage +patterns, among them: + +Polling with timeout. In this case, the order of events is known, and you +will deal only with positive results of :func:`time.ticks_diff()`:: + + # Wait for GPIO pin to be asserted, but at most 500us + start = time.ticks_us() + while pin.value() == 0: + if time.ticks_diff(time.ticks_us(), start) > 500: + raise TimeoutError + + +Scheduling events. In this case, :func:`time.ticks_diff()` result may be +negative if an event is overdue:: + + # This code snippet is not optimized + now = time.ticks_ms() + scheduled_time = task.scheduled_time() + if ticks_diff(scheduled_time, now) > 0: + print("Too early, let's nap") + sleep_ms(ticks_diff(scheduled_time, now)) + task.run() + elif ticks_diff(scheduled_time, now) == 0: + print("Right at time!") + task.run() + elif ticks_diff(scheduled_time, now) < 0: + print("Oops, running late, tell task to run faster!") + task.run(run_faster=True)""" + ... \ No newline at end of file diff --git a/lang/pl/typeshed/stdlib/gc.pyi b/lang/pl/typeshed/stdlib/gc.pyi index 1370abf..3a3e5a5 100644 --- a/lang/pl/typeshed/stdlib/gc.pyi +++ b/lang/pl/typeshed/stdlib/gc.pyi @@ -1,73 +1,68 @@ -"""Control the garbage collector""" - +"""Steruj zbieraniem śmieci""" from typing import overload def enable() -> None: - """Enable automatic garbage collection.""" + """Włącz automatyczne zbieranie śmieci.""" ... def disable() -> None: - """Disable automatic garbage collection. + """Wyłącz automatyczne zbieranie śmieci. - Heap memory can still be allocated, - and garbage collection can still be initiated manually using ``gc.collect``.""" +Heap memory can still be allocated, +and garbage collection can still be initiated manually using ``gc.collect``.""" def collect() -> None: - """Run a garbage collection.""" + """Uruchom zbieranie śmieci.""" ... def mem_alloc() -> int: - """Get the number of bytes of heap RAM that are allocated. + """Znajdź liczbę przydzielonych bajtów sterty pamięci RAM. - :return: The number of bytes allocated. +:return: The number of bytes allocated. - This function is MicroPython extension. - """ +This function is MicroPython extension.""" ... def mem_free() -> int: - """Get the number of bytes of available heap RAM, or -1 if this amount is not known. + """Znajdź liczbę bajtów dostępnej sterty pamięci RAM lub -1, jeśli ta liczba nie jest znana. - :return: The number of bytes free. +:return: The number of bytes free. - This function is MicroPython extension. - """ +This function is MicroPython extension.""" ... @overload def threshold() -> int: - """Query the additional GC allocation threshold. + """Zapytanie o dodatkowy próg przydziału GC. - :return: The GC allocation threshold. +:return: The GC allocation threshold. - This function is a MicroPython extension. CPython has a similar - function - ``set_threshold()``, but due to different GC - implementations, its signature and semantics are different. - """ +This function is a MicroPython extension. CPython has a similar +function - ``set_threshold()``, but due to different GC +implementations, its signature and semantics are different.""" ... @overload def threshold(amount: int) -> None: - """Set the additional GC allocation threshold. - - Normally, a collection is triggered only when a new allocation - cannot be satisfied, i.e. on an out-of-memory (OOM) condition. - If this function is called, in addition to OOM, a collection - will be triggered each time after ``amount`` bytes have been - allocated (in total, since the previous time such an amount of bytes - have been allocated). ``amount`` is usually specified as less than the - full heap size, with the intention to trigger a collection earlier than when the - heap becomes exhausted, and in the hope that an early collection will prevent - excessive memory fragmentation. This is a heuristic measure, the effect - of which will vary from application to application, as well as - the optimal value of the ``amount`` parameter. - - A value of -1 means a disabled allocation threshold. - - This function is a MicroPython extension. CPython has a similar - function - ``set_threshold()``, but due to different GC - implementations, its signature and semantics are different. - - :param amount: The number of bytes after which a garbage collection should be triggered. - """ - ... + """Ustaw próg dodatkowego przydziału GC. + +Normally, a collection is triggered only when a new allocation +cannot be satisfied, i.e. on an out-of-memory (OOM) condition. +If this function is called, in addition to OOM, a collection +will be triggered each time after ``amount`` bytes have been +allocated (in total, since the previous time such an amount of bytes +have been allocated). ``amount`` is usually specified as less than the +full heap size, with the intention to trigger a collection earlier than when the +heap becomes exhausted, and in the hope that an early collection will prevent +excessive memory fragmentation. This is a heuristic measure, the effect +of which will vary from application to application, as well as +the optimal value of the ``amount`` parameter. + +A value of -1 means a disabled allocation threshold. + +This function is a MicroPython extension. CPython has a similar +function - ``set_threshold()``, but due to different GC +implementations, its signature and semantics are different. + +:param amount: Liczba bajtów, po których powinno zostać uruchomione zbieranie śmieci.""" + ... \ No newline at end of file diff --git a/lang/pl/typeshed/stdlib/log.pyi b/lang/pl/typeshed/stdlib/log.pyi index c9870fa..4aa875f 100644 --- a/lang/pl/typeshed/stdlib/log.pyi +++ b/lang/pl/typeshed/stdlib/log.pyi @@ -1,104 +1,89 @@ -"""Log data to your micro:bit V2.""" - +"""Zaloguj dane do swojego micro:bita V2.""" from typing import Literal, Mapping, Optional, Union, overload - MILLISECONDS = 1 -"""Milliseconds timestamp format.""" - +"""Format znacznika czasu w milisekundach.""" SECONDS = 10 -"""Seconds timestamp format.""" - +"""Format znacznika czasu w sekundach.""" MINUTES = 600 -"""Minutes timestamp format.""" - +"""Format znacznika czasu w minutach.""" HOURS = 36000 -"""Hours timestamp format.""" - +"""Format znacznika czasu w godzinach.""" DAYS = 864000 -"""Days timestamp format.""" +"""Format znacznika czasu w dniach.""" -def set_labels( - *labels: str, timestamp: Optional[Literal[1, 10, 36000, 864000]] = SECONDS -) -> None: - """Set up the log file header. +def set_labels(*labels: str, timestamp: Optional[Literal[1, 10, 36000, 864000]]=SECONDS) -> None: + """Ustaw nagłówek pliku dziennika. - Example: ``log.set_labels('X', 'Y', 'Z', timestamp=log.MINUTES)`` +Example: ``log.set_labels('X', 'Y', 'Z', timestamp=log.MINUTES)`` - Ideally this function should be called a single time, before any data is - logged, to configure the data table header once. +Ideally this function should be called a single time, before any data is +logged, to configure the data table header once. - If a log file already exists when the program starts, or if this function - is called multiple times, it will check the labels already defined in the - log file. If this function call contains any new labels not already - present, it will generate a new header row with the additional columns. +If a log file already exists when the program starts, or if this function +is called multiple times, it will check the labels already defined in the +log file. If this function call contains any new labels not already +present, it will generate a new header row with the additional columns. - By default the first column contains a timestamp for each row. The time - unit can be selected via the timestamp argument. +By default the first column contains a timestamp for each row. The time +unit can be selected via the timestamp argument. - :param *labels: Any number of positional arguments, each corresponding to an entry in the log header. - :param timestamp: Select the timestamp unit that will be automatically added as the first column in every row. Timestamp values can be one of ``log.MILLISECONDS``, ``log.SECONDS``, ``log.MINUTES``, ``log.HOURS``, ``log.DAYS`` or ``None`` to disable the timestamp. The default value is ``log.SECONDS``. - """ +:param *labels: Dowolna liczba argumentów pozycyjnych, każdy odpowiadający wpisowi w nagłówku dziennika. +:param timestamp: Wybierz jednostkę znacznika czasu, która będzie automatycznie dodana jako pierwsza kolumna w każdym wierszu. Wartości znacznika czasu mogą być jedną z ``log.MILLISECONDS``, ``log.SECONDS``, ``log.MINUTES``, ``log.HOURS``, ``log.DAYS`` lub ``None``, aby wyłączyć znacznik czasu. Wartością domyślną jest ``log.SECONDS``.""" ... @overload -def add( - data_dictionary: Optional[Mapping[str, Union[str, int, float]]], -) -> None: - """Add a data row to the log by passing a dictionary of headers and values. +def add(data_dictionary: Optional[Mapping[str, Union[str, int, float]]]) -> None: + """Dodaj wiersz danych do dziennika poprzez podanie słownika nagłówków i wartości. - Example: ``log.add({ 'temp': temperature() })`` +Example: ``log.add({ 'temp': temperature() })`` - Each call to this function adds a row to the log. +Each call to this function adds a row to the log. - New labels not previously specified via the set_labels function, or by a - previous call to this function, will trigger a new header entry to be added - to the log with the extra labels. +New labels not previously specified via the set_labels function, or by a +previous call to this function, will trigger a new header entry to be added +to the log with the extra labels. - Labels previously specified and not present in a call to this function will - be skipped with an empty value in the log row. +Labels previously specified and not present in a call to this function will +be skipped with an empty value in the log row. - :param data_dictionary: The data to log as a dictionary with a key for each header. - """ +:param data_dictionary: Dane do logowania jako słownik z kluczem dla każdego nagłówka.""" ... @overload def add(**kwargs: Union[str, int, float]) -> None: - """Add a data row to the log using keyword arguments. + """Dodaj wiersz danych do dziennika używając argumentów słów kluczowych. (dodaj) - Example: ``log.add(temp=temperature())`` +Example: ``log.add(temp=temperature())`` - Each call to this function adds a row to the log. +Each call to this function adds a row to the log. - New labels not previously specified via the set_labels function, or by a - previous call to this function, will trigger a new header entry to be added - to the log with the extra labels. +New labels not previously specified via the set_labels function, or by a +previous call to this function, will trigger a new header entry to be added +to the log with the extra labels. - Labels previously specified and not present in a call to this function will - be skipped with an empty value in the log row. - """ +Labels previously specified and not present in a call to this function will +be skipped with an empty value in the log row.""" ... def delete(full=False): - """Deletes the contents of the log, including headers. + """Usuwa zawartość wpisu, w tym nagłówki. - Example: ``log.delete()`` +Example: ``log.delete()`` - To add the log headers again the ``set_labels`` function should to be called after this function. +To add the log headers again the ``set_labels`` function should to be called after this function. - There are two erase modes; “full” completely removes the data from the physical storage, - and “fast” invalidates the data without removing it. +There are two erase modes; “full” completely removes the data from the physical storage, +and “fast” invalidates the data without removing it. - :param full: ``True`` selects a “full” erase and ``False`` selects the “fast” erase method. - """ +:param full: ``True`` wybiera usunięcie "pełne" i ``False`` wybiera metodę "szybkiego" usunięcia.""" ... def set_mirroring(serial: bool): - """Configure mirroring of the data logging activity to the serial output. + """Skonfiguruj lustrzane odbicie logowania danych do wyjścia szeregowego. - Example: ``log.set_mirroring(True)`` +Example: ``log.set_mirroring(True)`` - Serial mirroring is disabled by default. When enabled, it will print to serial each row logged into the log file. +Serial mirroring is disabled by default. When enabled, it will print to serial each row logged into the log file. - :param serial: ``True`` enables mirroring data to the serial output. - """ - ... +:param serial: ``True`` umożliwia odbicie lustrzane danych na szeregowe wyjście.""" + ... \ No newline at end of file diff --git a/lang/pl/typeshed/stdlib/machine.pyi b/lang/pl/typeshed/stdlib/machine.pyi index 2e82f5b..70046a9 100644 --- a/lang/pl/typeshed/stdlib/machine.pyi +++ b/lang/pl/typeshed/stdlib/machine.pyi @@ -1,97 +1,84 @@ -"""Low-level utilities. -""" +"""Narzędzia niskiego poziomu.""" from typing import Any from .microbit import MicroBitDigitalPin def unique_id() -> bytes: - """Get a byte string with a unique identifier of a board. + """Pobierz ciąg bajtów z unikatowym identyfikatorem płytki. - Example: ``machine.unique_id()`` +Example: ``machine.unique_id()`` - :return: An identifier that varies from one board instance to another. - """ +:return: An identifier that varies from one board instance to another.""" ... def reset() -> None: - """Reset the device in a manner similar to pushing the external RESET button. + """Zresetuj urządzenie w sposób podobny do naciśnięcia zewnętrznego przycisku RESET. - Example: ``machine.reset()`` - """ +Example: ``machine.reset()``""" ... def freq() -> int: - """Get the CPU frequency in hertz. + """Uzyskaj częstotliwość procesora w hercach - Example: ``machine.freq()`` +Example: ``machine.freq()`` - :return: The CPU frequency. - """ +:return: The CPU frequency.""" ... def disable_irq() -> Any: - """Disable interrupt requests. + """Wyłącz żądania przerwań. - Example: ``interrupt_state = machine.disable_irq()`` +Example: ``interrupt_state = machine.disable_irq()`` - :return: the previous IRQ state which should be considered an opaque value +:return: the previous IRQ state which should be considered an opaque value - The return value should be passed to the ``enable_irq`` function to restore - interrupts to their original state. - """ +The return value should be passed to the ``enable_irq`` function to restore +interrupts to their original state.""" ... def enable_irq(state: Any) -> None: - """Re-enable interrupt requests. + """Ponownie włącz żądania przerwań. - Example: ``machine.enable_irq(interrupt_state)`` +Example: ``machine.enable_irq(interrupt_state)`` - :param state: The value that was returned from the most recent call to the ``disable_irq`` function. - """ +:param state: Wartość, która została zwrócona z ostatniego wywołania funkcji ``disable_irq``.""" ... -def time_pulse_us( - pin: MicroBitDigitalPin, pulse_level: int, timeout_us: int = 1000000 -) -> int: - """Time a pulse on a pin. +def time_pulse_us(pin: MicroBitDigitalPin, pulse_level: int, timeout_us: int=1000000) -> int: + """Czas pulsowania na pinie. - Example: ``time_pulse_us(pin0, 1)`` +Example: ``time_pulse_us(pin0, 1)`` - If the current input value of the pin is different to ``pulse_level``, the - function first waits until the pin input becomes equal to - ``pulse_level``, then times the duration that the pin is equal to - ``pulse_level``. If the pin is already equal to ``pulse_level`` then timing - starts straight away. +If the current input value of the pin is different to ``pulse_level``, the +function first waits until the pin input becomes equal to +``pulse_level``, then times the duration that the pin is equal to +``pulse_level``. If the pin is already equal to ``pulse_level`` then timing +starts straight away. - :param pin: The pin to use - :param pulse_level: 0 to time a low pulse or 1 to time a high pulse - :param timeout_us: A microsecond timeout - :return: The duration of the pulse in microseconds, or -1 for a timeout waiting for the level to match ``pulse_level``, or -2 on timeout waiting for the pulse to end - """ +:param pin: Pin do użycia +:param pulse_level: 0 do czasu niskiego pulsu lub 1 do czasu wysokiego pulsu +:param timeout_us: Mikrosekundowy limit czasu +:return: The duration of the pulse in microseconds, or -1 for a timeout waiting for the level to match ``pulse_level``, or -2 on timeout waiting for the pulse to end""" ... class mem: - """The class for the ``mem8``, ``mem16`` and ``mem32`` memory views.""" + """Klasa dla widoków pamięci ``mem8``, ``mem16`` i ``mem32``.""" def __getitem__(self, address: int) -> int: - """Access a value from memory. + """Uzyskaj dostęp do wartości z pamięci. - :param address: The memory address. - :return: The value at that address as an integer. - """ +:param address: Adres pamięci. +:return: The value at that address as an integer.""" ... + def __setitem__(self, address: int, value: int) -> None: - """Set a value at the given address. + """Ustaw wartość dla podanego adresu. - :param address: The memory address. - :param value: The integer value to set. - """ +:param address: Adres pamięci. +:param value: Wartość całkowita do ustawiania.""" ... - mem8: mem -"""8-bit (byte) view of memory.""" - +"""8-bitowy widok pamięci.""" mem16: mem -"""16-bit view of memory.""" - +"""16-bitowy widok pamięci.""" mem32: mem -"""32-bit view of memory.""" +"""32-bitowy widok pamięci.""" \ No newline at end of file diff --git a/lang/pl/typeshed/stdlib/math.pyi b/lang/pl/typeshed/stdlib/math.pyi index f82d4de..e61fbe3 100644 --- a/lang/pl/typeshed/stdlib/math.pyi +++ b/lang/pl/typeshed/stdlib/math.pyi @@ -1,273 +1,246 @@ -"""Mathematical functions. -""" - +"""Funkcje matematyczne.""" from typing import Tuple def acos(x: float) -> float: - """Calculate the inverse cosine. + """Obliczyć odwrotność cosinusa. - Example: ``math.acos(1)`` +Example: ``math.acos(1)`` - :param x: A number - :return: The inverse cosine of ``x`` - """ +:param x: Liczba +:return: The inverse cosine of ``x``""" ... def asin(x: float) -> float: - """Calculate the inverse sine. + """Obliczyć odwrotność sinusa. - Example: ``math.asin(0)`` +Example: ``math.asin(0)`` - :param x: A number - :return: The inverse sine of ``x`` - """ +:param x: Liczba +:return: The inverse sine of ``x``""" ... def atan(x: float) -> float: - """Calculate the inverse tangent. + """Oblicz odwrotność tangensa. - Example: ``math.atan(0)`` +Example: ``math.atan(0)`` - :param x: A number - :return: The inverse tangent of ``x`` - """ +:param x: Liczba +:return: The inverse tangent of ``x``""" ... def atan2(y: float, x: float) -> float: - """Calculate the principal value of the inverse tangent of ``y/x``. + """Oblicz wartość główną odwrotności tangensa ``y/x``. - Example: ``math.atan2(0, -1)`` +Example: ``math.atan2(0, -1)`` - :param y: A number - :param x: A number - :return: The principal value of the inverse tangent of ``y/x`` - """ +:param y: Liczba +:param x: Liczba +:return: The principal value of the inverse tangent of ``y/x``""" ... def ceil(x: float) -> float: - """Round a number towards positive infinity. + """Zaokrąglij liczbę w kierunku dodatniej nieskończoności. - Example: ``math.ceil(0.1)`` +Example: ``math.ceil(0.1)`` - :param x: A number - :return: ``x`` rounded towards positive infinity. - """ +:param x: Liczba +:return: ``x`` rounded towards positive infinity.""" ... def copysign(x: float, y: float) -> float: - """Calculate ``x`` with the sign of ``y``. + """Oblicz ``x`` ze znakiem ``y``. - Example: ``math.copysign(1, -1)`` +Example: ``math.copysign(1, -1)`` - :param x: A number - :param y: The source of the sign for the return value - :return: ``x`` with the sign of ``y`` - """ +:param x: Liczba +:param y: Źródło znaku dla wartości zwracanej +:return: ``x`` with the sign of ``y``""" ... def cos(x: float) -> float: - """Calculate the cosine of ``x``. + """Oblicz cosinus ``x``. - Example: ``math.cos(0)`` +Example: ``math.cos(0)`` - :param x: A number - :return: The cosine of ``x`` - """ +:param x: Liczba +:return: The cosine of ``x``""" ... def degrees(x: float) -> float: - """Convert radians to degrees. + """Konwertuj radiany na stopnie. - Example: ``math.degrees(2 * math.pi)`` +Example: ``math.degrees(2 * math.pi)`` - :param x: A value in radians - :return: The value converted to degrees""" +:param x: Wartość w radianach +:return: The value converted to degrees""" ... def exp(x: float) -> float: - """Calculate the exponential of ``x``. + """Oblicz potęgę ``x``. - Example: ``math.exp(1)`` +Example: ``math.exp(1)`` - :param x: A number - :return: The exponential of ``x``. - """ +:param x: Liczba +:return: The exponential of ``x``.""" ... def fabs(x: float) -> float: - """Return the absolute value of ``x``. + """Zwróć wartość bezwzględną ``x``. - Example: ``math.fabs(-0.1)`` +Example: ``math.fabs(-0.1)`` - :param x: A number - :return: The absolute value of ``x`` - """ +:param x: Liczba +:return: The absolute value of ``x``""" ... def floor(x: float) -> int: - """Round a number towards negative infinity. + """Zaokrąglij liczbę w kierunku ujemnej nieskończoności. - Example: ``math.floor(0.9)`` +Example: ``math.floor(0.9)`` - :param x: A number - :return: ``x`` rounded towards negative infinity. - """ +:param x: Liczba +:return: ``x`` rounded towards negative infinity.""" ... def fmod(x: float, y: float) -> float: - """Calculate the remainder of ``x/y``. + """Oblicz resztę z ``x/y``. - Example: ``math.fmod(10, 3)`` +Example: ``math.fmod(10, 3)`` - :param x: The numerator - :param y: The denominator - """ +:param x: Licznik +:param y: Mianownik""" ... def frexp(x: float) -> Tuple[float, int]: - """Decomposes a floating-point number into its mantissa and exponent. + """Rozkłada liczbę zmiennopozycyjną na mantysę i wykładnik. - Example: ``mantissa, exponent = math.frexp(2)`` +Example: ``mantissa, exponent = math.frexp(2)`` - The returned value is the tuple ``(m, e)`` such that ``x == m * 2**e`` - exactly. If ``x == 0`` then the function returns ``(0.0, 0)``, otherwise - the relation ``0.5 <= abs(m) < 1`` holds. +The returned value is the tuple ``(m, e)`` such that ``x == m * 2**e`` +exactly. If ``x == 0`` then the function returns ``(0.0, 0)``, otherwise +the relation ``0.5 <= abs(m) < 1`` holds. - :param x: A floating-point number - :return: A tuple of length two containing its mantissa then exponent - """ +:param x: Liczba zmiennopozycyjna +:return: A tuple of length two containing its mantissa then exponent""" ... def isfinite(x: float) -> bool: - """Check if a value is finite. + """Sprawdź, czy wartość jest skończona. - Example: ``math.isfinite(float('inf'))`` +Example: ``math.isfinite(float('inf'))`` - :param x: A number. - :return: ``True`` if ``x`` is finite, ``False`` otherwise. - """ +:param x: Liczba. +:return: ``True`` if ``x`` is finite, ``False`` otherwise.""" ... def isinf(x: float) -> bool: - """Check if a value is infinite. + """Sprawdź, czy wartość jest nieskończona. - Example: ``math.isinf(float('-inf'))`` +Example: ``math.isinf(float('-inf'))`` - :param x: A number. - :return: ``True`` if ``x`` is infinite, ``False`` otherwise. - """ +:param x: Liczba. +:return: ``True`` if ``x`` is infinite, ``False`` otherwise.""" ... def isnan(x: float) -> bool: - """Check if a value is not-a-number (NaN). + """Sprawdź, czy wartość nie jest liczbą (NaN). - Example: ``math.isnan(float('nan'))`` +Example: ``math.isnan(float('nan'))`` - :param x: A number - :return: ``True`` if ``x`` is not-a-number (NaN), ``False`` otherwise.""" +:param x: Liczba +:return: ``True`` if ``x`` is not-a-number (NaN), ``False`` otherwise.""" ... def ldexp(x: float, exp: int) -> float: - """Calculate ``x * (2**exp)``. + """Oblicz ``x * (2**exp)``. - Example: ``math.ldexp(0.5, 2)`` +Example: ``math.ldexp(0.5, 2)`` - :param x: A number - :param exp: Integer exponent - :return: ``x * (2**exp)`` - """ +:param x: Liczba +:param exp: Wykładnik całkowity +:return: ``x * (2**exp)``""" ... -def log(x: float, base: float = e) -> float: - """Calculate the logarithm of ``x`` to the given base (defaults to natural logorithm). +def log(x: float, base: float=e) -> float: + """Oblicz logarytm z ``x`` przy podanej podstawie (domyślnie loggorytm naturalny). - Example: ``math.log(math.e)`` +Example: ``math.log(math.e)`` - With one argument, return the natural logarithm of x (to base e). +With one argument, return the natural logarithm of x (to base e). - With two arguments, return the logarithm of x to the given base, calculated as ``log(x)/log(base)``. +With two arguments, return the logarithm of x to the given base, calculated as ``log(x)/log(base)``. - :param x: A number - :param base: The base to use - :return: The natural logarithm of ``x`` - """ +:param x: Liczba +:param base: Podstawa do użycia +:return: The natural logarithm of ``x``""" ... def modf(x: float) -> Tuple[float, float]: - """Calculate the fractional and integral parts of ``x``. + """Oblicz część ułamkową i całkowitą z ``x``. - Example: ``fractional, integral = math.modf(1.5)`` +Example: ``fractional, integral = math.modf(1.5)`` - :param x: A number - :return: A tuple of two floats representing the fractional then integral parts of ``x``. +:param x: Liczba +:return: A tuple of two floats representing the fractional then integral parts of ``x``. - Both the fractional and integral values have the same sign as ``x``. - """ +Both the fractional and integral values have the same sign as ``x``.""" ... def pow(x: float, y: float) -> float: - """Returns ``x`` to the power of ``y``. + """Zwraca ``x`` do potęgi ``y``. - Example: ``math.pow(4, 0.5)`` +Example: ``math.pow(4, 0.5)`` - :param x: A number - :param y: The exponent - :return: ``x`` to the power of ``y`` - """ +:param x: Liczba +:param y: Wykładnik +:return: ``x`` to the power of ``y``""" ... def radians(x: float) -> float: - """Convert a degrees to radians. + """Konwertuj stopnie na radiany. - Example: ``math.radians(360)`` +Example: ``math.radians(360)`` - :param x: A value in degrees - :return: The value converted to radians - """ +:param x: Wartość w stopniach +:return: The value converted to radians""" ... def sin(x: float) -> float: - """Calculate the sine of ``x``. + """Oblicz sinus ``x``. - Example: ``math.sin(math.pi/2)`` +Example: ``math.sin(math.pi/2)`` - :param x: A number - :return: The sine of ``x`` - """ +:param x: Liczba +:return: The sine of ``x``""" ... def sqrt(x: float) -> float: - """Calculate the square root of ``x``. + """Oblicz pierwiastek kwadratowy z ``x``. - Example: ``math.sqrt(4)`` +Example: ``math.sqrt(4)`` - :param x: A number - :return: The square root of ``x`` - """ +:param x: Liczba +:return: The square root of ``x``""" ... def tan(x: float) -> float: - """Calculate the tangent of ``x``. + """Oblicz tangens z ``x``. - Example: ``math.tan(0)`` +Example: ``math.tan(0)`` - :param x: A number - :return: The tangent of ``x``. - """ +:param x: Liczba +:return: The tangent of ``x``.""" ... def trunc(x: float) -> int: - """Round a number towards 0. + """Zaokrąglij liczbę w kierunku 0. - Example: ``math.trunc(-0.9)`` +Example: ``math.trunc(-0.9)`` - :param x: A number - :return: ``x`` rounded towards zero. - """ +:param x: Liczba +:return: ``x`` rounded towards zero.""" ... - e: float -"""Base of the natural logarithm""" - +"""Podstawa logarytmu naturalnego""" pi: float -"""The ratio of a circle's circumference to its diameter""" +"""Stosunek obwodu okręgu do jego średnicy""" \ No newline at end of file diff --git a/lang/pl/typeshed/stdlib/microbit/__init__.pyi b/lang/pl/typeshed/stdlib/microbit/__init__.pyi index f12158f..a40d3d6 100644 --- a/lang/pl/typeshed/stdlib/microbit/__init__.pyi +++ b/lang/pl/typeshed/stdlib/microbit/__init__.pyi @@ -1,11 +1,6 @@ -"""Pins, images, sounds, temperature and volume. -""" - +"""Piny, obrazy, dźwięki, temperatura i głośność.""" from typing import Any, Callable, List, Optional, Tuple, Union, overload - from _typeshed import ReadableBuffer - -# V2 only from . import accelerometer as accelerometer from . import audio as audio from . import compass as compass @@ -16,831 +11,701 @@ from . import speaker as speaker from . import spi as spi from . import uart as uart -def run_every( - callback: Optional[Callable[[], None]] = None, - days: int = 0, - h: int = 0, - min: int = 0, - s: int = 0, - ms: int = 0, -) -> Callable[[Callable[[], None]], Callable[[], None]]: - """Schedule to run a function at the interval specified by the time arguments **V2 only**. +def run_every(callback: Optional[Callable[[], None]]=None, days: int=0, h: int=0, min: int=0, s: int=0, ms: int=0) -> Callable[[Callable[[], None]], Callable[[], None]]: + """Zaplanuj uruchomienie funkcji w przedziale określonym przez argumenty czasu **tylko V2**. - Example: ``run_every(my_logging, min=5)`` +Example: ``run_every(my_logging, min=5)`` - ``run_every`` can be used in two ways: +``run_every`` can be used in two ways: - As a Decorator - placed on top of the function to schedule. For example:: +As a Decorator - placed on top of the function to schedule. For example:: - @run_every(h=1, min=20, s=30, ms=50) - def my_function(): - # Do something here + @run_every(h=1, min=20, s=30, ms=50) + def my_function(): + # Do something here - As a Function - passing the callback as a positional argument. For example:: +As a Function - passing the callback as a positional argument. For example:: - def my_function(): - # Do something here - run_every(my_function, s=30) + def my_function(): + # Do something here + run_every(my_function, s=30) - Each argument corresponds to a different time unit and they are additive. - So ``run_every(min=1, s=30)`` schedules the callback every minute and a half. +Each argument corresponds to a different time unit and they are additive. +So ``run_every(min=1, s=30)`` schedules the callback every minute and a half. - When an exception is thrown inside the callback function it deschedules the - function. To avoid this you can catch exceptions with ``try/except``. +When an exception is thrown inside the callback function it deschedules the +function. To avoid this you can catch exceptions with ``try/except``. - :param callback: Function to call at the provided interval. Omit when using as a decorator. - :param days: Sets the day mark for the scheduling. - :param h: Sets the hour mark for the scheduling. - :param min: Sets the minute mark for the scheduling. - :param s: Sets the second mark for the scheduling. - :param ms: Sets the millisecond mark for the scheduling. - """ +:param callback: Funkcja wywoływana w podanym przedziale. Pomiń, jeśli używasz jako dekorator. +:param days: Ustawia oznaczenie dnia dla harmonogramu. +:param h: Ustawia znak godziny dla harmonogramu. +:param min: Ustawia znak minuty dla harmonogramu. +:param s: Ustawia znak sekundy dla harmonogramu. +:param ms: Ustawia znak milisekundy dla harmonogramu.""" def panic(n: int) -> None: - """Enter a panic mode. + """Wejdź w tryb paniki. - Example: ``panic(127)`` +Example: ``panic(127)`` - :param n: An arbitrary integer <= 255 to indicate a status. +:param n: Dowolna liczba całkowita <= 255 dla wskazania statusu. - Requires restart. - """ +Requires restart.""" def reset() -> None: - """Restart the board.""" - + """Uruchom ponownie płytkę.""" @overload def scale(value: float, from_: Tuple[float, float], to: Tuple[int, int]) -> int: - """Converts a value from a range to an integer range. + """Konwertuje wartość z zakresu do zakresu liczb całkowitych. - Example: ``volume = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255))`` +Example: ``volume = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255))`` - For example, to convert an accelerometer X value to a speaker volume. +For example, to convert an accelerometer X value to a speaker volume. - If one of the numbers in the ``to`` parameter is a floating point - (i.e a decimal number like ``10.0``), this function will return a - floating point number. +If one of the numbers in the ``to`` parameter is a floating point +(i.e a decimal number like ``10.0``), this function will return a +floating point number. - temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0)) + temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0)) - :param value: A number to convert. - :param from_: A tuple to define the range to convert from. - :param to: A tuple to define the range to convert to. - :return: The ``value`` converted to the ``to`` range. - """ +:param value: Liczba do konwersji. +:param from_: Krotka do zdefiniowania zakresu dla konwersji z. +:param to: Krotka do zdefiniowania zakresu dla konwersji do. +:return: The ``value`` converted to the ``to`` range.""" @overload def scale(value: float, from_: Tuple[float, float], to: Tuple[float, float]) -> float: - """Converts a value from a range to a floating point range. + """Konwertuje wartość z zakresu do zakresu o zmiennopozycyjnego. - Example: ``temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0))`` +Example: ``temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0))`` - For example, to convert temperature from a Celsius scale to Fahrenheit. +For example, to convert temperature from a Celsius scale to Fahrenheit. - If one of the numbers in the ``to`` parameter is a floating point - (i.e a decimal number like ``10.0``), this function will return a - floating point number. - If they are both integers (i.e ``10``), it will return an integer:: +If one of the numbers in the ``to`` parameter is a floating point +(i.e a decimal number like ``10.0``), this function will return a +floating point number. +If they are both integers (i.e ``10``), it will return an integer:: - returns_int = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255)) + returns_int = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255)) - :param value: A number to convert. - :param from_: A tuple to define the range to convert from. - :param to: A tuple to define the range to convert to. - :return: The ``value`` converted to the ``to`` range. - """ +:param value: Liczba do konwersji. +:param from_: Krotka do zdefiniowania zakresu dla konwersji z. +:param to: Krotka do zdefiniowania zakresu, na jaki konwertować. +:return: The ``value`` converted to the ``to`` range.""" def sleep(n: float) -> None: - """Wait for ``n`` milliseconds. + """Poczekaj ``n`` milisekund. - Example: ``sleep(1000)`` +Example: ``sleep(1000)`` - :param n: The number of milliseconds to wait +:param n: Liczba milisekund oczekiwania - One second is 1000 milliseconds, so:: +One second is 1000 milliseconds, so:: - microbit.sleep(1000) + microbit.sleep(1000) - will pause the execution for one second. - """ +will pause the execution for one second.""" def running_time() -> int: - """Get the running time of the board. + """Uzyskaj czas pracy płytki. - :return: The number of milliseconds since the board was switched on or restarted. - """ +:return: The number of milliseconds since the board was switched on or restarted.""" def temperature() -> int: - """Get the temperature of the micro:bit in degrees Celsius.""" + """Uzyskaj temperaturę micro:bita w stopniach Celsjusza.""" def set_volume(v: int) -> None: - """Sets the volume. + """Ustawia głośność. - Example: ``set_volume(127)`` +Example: ``set_volume(127)`` - :param v: a value between 0 (low) and 255 (high). +:param v: wartość między 0 (niska) a 255 (wysoka). - Out of range values will be clamped to 0 or 255. +Out of range values will be clamped to 0 or 255. - **V2** only. - """ +**V2** only.""" ... class Button: - """The class for the buttons ``button_a`` and ``button_b``.""" + """Klasa dla przycisków ``button_a`` i ``button_b``.""" def is_pressed(self) -> bool: - """Check if the button is pressed. + """Sprawdź, czy przycisk jest naciśnięty. - :return: ``True`` if the specified button ``button`` is pressed, and ``False`` otherwise. - """ +:return: ``True`` if the specified button ``button`` is pressed, and ``False`` otherwise.""" ... + def was_pressed(self) -> bool: - """Check if the button was pressed since the device started or the last time this method was called. + """Sprawdź, czy przycisk został naciśnięty od momentu uruchomienia urządzenia lub kiedy ta metoda została wywołana. - Calling this method will clear the press state so - that the button must be pressed again before this method will return - ``True`` again. +Calling this method will clear the press state so +that the button must be pressed again before this method will return +``True`` again. - :return: ``True`` if the specified button ``button`` was pressed, and ``False`` otherwise - """ +:return: ``True`` if the specified button ``button`` was pressed, and ``False`` otherwise""" ... + def get_presses(self) -> int: - """Get the running total of button presses, and resets this total - to zero before returning. + """Pobierz sumę naciśnięć przycisków i zresetuje tę sumę +do zera przed powrotem. - :return: The number of presses since the device started or the last time this method was called - """ +:return: The number of presses since the device started or the last time this method was called""" ... - button_a: Button -"""The left button ``Button`` object.""" - +"""Lewy przycisk ``Button`` obiekt.""" button_b: Button -"""The right button ``Button`` object.""" +"""Prawy przycisk ``Button`` obiekt.""" class MicroBitDigitalPin: - """A digital pin. - - Some pins support analog and touch features using the ``MicroBitAnalogDigitalPin`` and ``MicroBitTouchPin`` subclasses. - """ + """Cyfrowy pin. +Some pins support analog and touch features using the ``MicroBitAnalogDigitalPin`` and ``MicroBitTouchPin`` subclasses.""" NO_PULL: int PULL_UP: int PULL_DOWN: int + def read_digital(self) -> int: - """Get the digital value of the pin. + """Uzyskaj cyfrową wartość pinu. - Example: ``value = pin0.read_digital()`` +Example: ``value = pin0.read_digital()`` - :return: 1 if the pin is high, and 0 if it's low. - """ +:return: 1 if the pin is high, and 0 if it's low.""" ... + def write_digital(self, value: int) -> None: - """Set the digital value of the pin. + """Ustaw cyfrową wartość pinu. - Example: ``pin0.write_digital(1)`` +Example: ``pin0.write_digital(1)`` - :param value: 1 to set the pin high or 0 to set the pin low""" +:param value: 1, aby ustawić wysoką wartość pinu lub 0, aby ustawić niską wartość pinu""" ... + def set_pull(self, value: int) -> None: - """Set the pull state to one of three possible values: ``PULL_UP``, ``PULL_DOWN`` or ``NO_PULL``. + """Ustaw stan ciągnięcia na jedną z trzech możliwych wartości: ``PULL_UP``, ``PULL_DOWN`` lub ``NO_PULL``. - Example: ``pin0.set_pull(pin0.PULL_UP)`` +Example: ``pin0.set_pull(pin0.PULL_UP)`` - :param value: The pull state from the relevant pin, e.g. ``pin0.PULL_UP``. - """ +:param value: Stan ciągnięcia z odpowiedniego pinu, np. ``pin0.PULL_UP``.""" ... + def get_pull(self) -> int: - """Get the pull state on a pin. + """Uzyskaj stan cignięcia na pinie. - Example: ``pin0.get_pull()`` +Example: ``pin0.get_pull()`` - :return: ``NO_PULL``, ``PULL_DOWN``, or ``PULL_UP`` +:return: ``NO_PULL``, ``PULL_DOWN``, or ``PULL_UP`` - These are set using the ``set_pull()`` method or automatically configured - when a pin mode requires it. - """ +These are set using the ``set_pull()`` method or automatically configured +when a pin mode requires it.""" ... + def get_mode(self) -> str: - """Returns the pin mode. + """Zwraca tryb pinu. - Example: ``pin0.get_mode()`` +Example: ``pin0.get_mode()`` - When a pin is used for a specific function, like - writing a digital value, or reading an analog value, the pin mode - changes. +When a pin is used for a specific function, like +writing a digital value, or reading an analog value, the pin mode +changes. - :return: ``"unused"``, ``"analog"``, ``"read_digital"``, ``"write_digital"``, ``"display"``, ``"button"``, ``"music"``, ``"audio"``, ``"touch"``, ``"i2c"``, or ``"spi"`` - """ +:return: ``"unused"``, ``"analog"``, ``"read_digital"``, ``"write_digital"``, ``"display"``, ``"button"``, ``"music"``, ``"audio"``, ``"touch"``, ``"i2c"``, or ``"spi"``""" ... + def write_analog(self, value: int) -> None: - """Output a PWM signal on the pin, with the duty cycle proportional to ``value``. + """Wysyłaj sygnał PWM na pin, z cyklem pracy proporcjonalnym do ``value``. + +Example: ``pin0.write_analog(254)`` - Example: ``pin0.write_analog(254)`` +:param value: Liczba całkowita lub liczba zmiennopozycyjna między 0 (0% cyklu pracy) a 1023 (100% cyklu pracy).""" - :param value: 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. + """Ustaw okres wyjścia sygnału PWM na ``period`` w milisekundach. - Example: ``pin0.set_analog_period(10)`` +Example: ``pin0.set_analog_period(10)`` + +:param period: Okres w milisekundach z minimalną poprawną wartością 1 ms.""" - :param period: The period in milliseconds with a minimum valid value of 1ms. - """ def set_analog_period_microseconds(self, period: int) -> None: - """Set the period of the PWM signal being output to ``period`` in microseconds. + """Ustaw okres wyjścia sygnału PWM na ``period`` w mikrosekundach. (ustaw mikrosekundy okresu analogowego) - Example: ``pin0.set_analog_period_microseconds(512)`` +Example: ``pin0.set_analog_period_microseconds(512)`` - :param period: The period in microseconds with a minimum valid value of 256µs. - """ +:param period: Okres w mikrosekundach z minimalną poprawną wartością 256µs.""" class MicroBitAnalogDigitalPin(MicroBitDigitalPin): - """A pin with analog and digital features.""" + """Pin z funkcjami analogowymi i cyfrowymi.""" def read_analog(self) -> int: - """Read the voltage applied to the pin. + """Odczytaj napięcie przyłożone do pinu. - Example: ``pin0.read_analog()`` +Example: ``pin0.read_analog()`` - :return: An integer between 0 (meaning 0V) and 1023 (meaning 3.3V). - """ +:return: An integer between 0 (meaning 0V) and 1023 (meaning 3.3V).""" class MicroBitTouchPin(MicroBitAnalogDigitalPin): - """A pin with analog, digital and touch features.""" - + """Pin z funkcjami analogowymi, cyfrowymi i dotykowymi.""" CAPACITIVE: int RESISTIVE: int + def is_touched(self) -> bool: - """Check if the pin is being touched. + """Sprawdź, czy pin został dotknięty. - Example: ``pin0.is_touched()`` +Example: ``pin0.is_touched()`` - The default touch mode for the pins on the edge connector is ``resistive``. - The default for the logo pin **V2** is ``capacitive``. +The default touch mode for the pins on the edge connector is ``resistive``. +The default for the logo pin **V2** is ``capacitive``. - **Resistive touch** - This test is done by measuring how much resistance there is between the - pin and ground. A low resistance gives a reading of ``True``. To get - a reliable reading using a finger you may need to touch the ground pin - with another part of your body, for example your other hand. +**Resistive touch** +This test is done by measuring how much resistance there is between the +pin and ground. A low resistance gives a reading of ``True``. To get +a reliable reading using a finger you may need to touch the ground pin +with another part of your body, for example your other hand. - **Capacitive touch** - This test is done by interacting with the electric field of a capacitor - using a finger as a conductor. `Capacitive touch - `_ - does not require you to make a ground connection as part of a circuit. +**Capacitive touch** +This test is done by interacting with the electric field of a capacitor +using a finger as a conductor. `Capacitive touch +`_ +does not require you to make a ground connection as part of a circuit. - :return: ``True`` if the pin is being touched with a finger, otherwise return ``False``. - """ +:return: ``True`` if the pin is being touched with a finger, otherwise return ``False``.""" ... + def set_touch_mode(self, value: int) -> None: - """Set the touch mode for the pin. + """Ustaw tryb dotykowy dla pinu. - Example: ``pin0.set_touch_mode(pin0.CAPACITIVE)`` +Example: ``pin0.set_touch_mode(pin0.CAPACITIVE)`` - The default touch mode for the pins on the edge connector is - ``resistive``. The default for the logo pin **V2** is ``capacitive``. +The default touch mode for the pins on the edge connector is +``resistive``. The default for the logo pin **V2** is ``capacitive``. - :param value: ``CAPACITIVE`` or ``RESISTIVE`` from the relevant pin. - """ +:param value: ``CAPACITIVE`` lub ``RESISTIVE`` z odpowiedniego pinu.""" ... - pin0: MicroBitTouchPin -"""Pin with digital, analog and touch features.""" - +"""Pin z funkcjami cyfrową, analogową i dotykową.""" pin1: MicroBitTouchPin -"""Pin with digital, analog and touch features.""" - +"""Pin z funkcjami cyfrową, analogową i dotykową.""" pin2: MicroBitTouchPin -"""Pin with digital, analog and touch features.""" - +"""Pin z funkcjami cyfrową, analogową i dotykową.""" pin3: MicroBitAnalogDigitalPin -"""Pin with digital and analog features.""" - +"""Pin z funkcjami cyfrowymi i analogowymi.""" pin4: MicroBitAnalogDigitalPin -"""Pin with digital and analog features.""" - +"""Pin z funkcjami cyfrowymi i analogowymi.""" pin5: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin z funkcjami cyfrowymi.""" pin6: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin z funkcjami cyfrowymi.""" pin7: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin z funkcjami cyfrowymi.""" pin8: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin z funkcjami cyfrowymi.""" pin9: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin z funkcjami cyfrowymi.""" pin10: MicroBitAnalogDigitalPin -"""Pin with digital and analog features.""" - +"""Pin z funkcjami cyfrowymi i analogowymi.""" pin11: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin z funkcjami cyfrowymi.""" pin12: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin z funkcjami cyfrowymi.""" pin13: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin z funkcjami cyfrowymi.""" pin14: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin z funkcjami cyfrowymi.""" pin15: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin z funkcjami cyfrowymi.""" pin16: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin z funkcjami cyfrowymi.""" pin19: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin z funkcjami cyfrowymi.""" pin20: MicroBitDigitalPin -"""Pin with digital features.""" - +"""Pin z funkcjami cyfrowymi.""" pin_logo: MicroBitTouchPin -"""A touch sensitive logo pin on the front of the micro:bit, which by default is set to capacitive touch mode.""" - +"""Wrażliwy na dotyk pin z logo z przodu micro:bita, który domyślnie jest ustawiony na pojemnościowy tryb dotykowy.""" pin_speaker: MicroBitAnalogDigitalPin -"""A pin to address the micro:bit speaker. +"""Pin adresujący głośnik micro:bita. This API is intended only for use in Pulse-Width Modulation pin operations e.g. pin_speaker.write_analog(128). """ class Image: - """An image to show on the micro:bit LED display. + """Obraz wyświetlany na wyświetlaczu LED micro:bita. - Given an image object it's possible to display it via the ``display`` API:: - - display.show(Image.HAPPY) - """ +Given an image object it's possible to display it via the ``display`` API:: + display.show(Image.HAPPY)""" HEART: Image - """Heart image.""" - + """Obraz serca.""" HEART_SMALL: Image - """Small heart image.""" - + """Obraz małego serca.""" HAPPY: Image - """Happy face image.""" - + """Obraz szczęśliwej twarzy.""" SMILE: Image - """Smiling mouth image.""" - + """Obraz uśmiechniętej twarzy.""" SAD: Image - """Sad face image.""" - + """Obraz smutnej twarzy.""" CONFUSED: Image - """Confused face image.""" - + """Obraz zmieszanej twarzy.""" ANGRY: Image - """Angry face image.""" - + """Obraz złej twarzy.""" ASLEEP: Image - """Sleeping face image.""" - + """Obraz śpiącej twarzy.""" SURPRISED: Image - """Surprised face image.""" - + """Obraz zaskoczonej twarzy.""" SILLY: Image - """Silly face image.""" - + """Obraz głupiej twarzy.""" FABULOUS: Image - """Sunglasses face image.""" - + """Obraz twarzy w okularach przeciwsłonecznych.""" MEH: Image - """Unimpressed face image.""" - + """Obraz niewzruszonej twarzy.""" YES: Image - """Tick image.""" - + """Haczyk na TAK.""" NO: Image - """Cross image.""" - + """Krzyżyk na NIE.""" CLOCK12: Image - """Image with line pointing to 12 o'clock.""" - + """Obraz z linią wskazującą na godzinę 12.""" CLOCK11: Image - """Image with line pointing to 11 o'clock.""" - + """Obraz z linią wskazującą na godzinę 11.""" CLOCK10: Image - """Image with line pointing to 10 o'clock.""" - + """Obraz z linią wskazującą na godzinę 10.""" CLOCK9: Image - """Image with line pointing to 9 o'clock.""" - + """Obraz z linią wskazującą na godzinę 9.""" CLOCK8: Image - """Image with line pointing to 8 o'clock.""" - + """Obraz z linią wskazującą na godzinę 8.""" CLOCK7: Image - """Image with line pointing to 7 o'clock.""" - + """Obraz z linią wskazującą na godzinę 7.""" CLOCK6: Image - """Image with line pointing to 6 o'clock.""" - + """Obraz z linią wskazującą na godzinę 6.""" CLOCK5: Image - """Image with line pointing to 5 o'clock.""" - + """Obraz z linią wskazującą na godzinę 5.""" CLOCK4: Image - """Image with line pointing to 4 o'clock.""" - + """Obraz z linią wskazującą na godzinę 4.""" CLOCK3: Image - """Image with line pointing to 3 o'clock.""" - + """Obraz z linią wskazującą na godzinę 3.""" CLOCK2: Image - """Image with line pointing to 2 o'clock.""" - + """Obraz z linią wskazującą na godzinę 2.""" CLOCK1: Image - """Image with line pointing to 1 o'clock.""" - + """Obraz z linią wskazującą na godzinę 1.""" ARROW_N: Image - """Image of arrow pointing north.""" - + """Obraz strzałki wskazującej północ.""" ARROW_NE: Image - """Image of arrow pointing north east.""" - + """Obraz strzałki wskazującej północny wschód.""" ARROW_E: Image - """Image of arrow pointing east.""" - + """Obraz strzałki wskazującej wschód.""" ARROW_SE: Image - """Image of arrow pointing south east.""" - + """Obraz strzałki wskazującej południowy wschód.""" ARROW_S: Image - """Image of arrow pointing south.""" - + """Obraz strzałki wskazującej południe.""" ARROW_SW: Image - """Image of arrow pointing south west.""" - + """Obraz strzałki wskazującej południowy zachód.""" ARROW_W: Image - """Image of arrow pointing west.""" - + """Obraz strzałki wskazującej zachód.""" ARROW_NW: Image - """Image of arrow pointing north west.""" - + """Obraz strzałki wskazującej północny zachód.""" TRIANGLE: Image - """Image of a triangle pointing up.""" - + """Obraz trójkąta skierowanego do góry.""" TRIANGLE_LEFT: Image - """Image of a triangle in the left corner.""" - + """Obraz trójkąta w lewym rogu.""" CHESSBOARD: Image - """Alternate LEDs lit in a chessboard pattern.""" - + """Diody LED świecą naprzemiennie w układzie szachownicy.""" DIAMOND: Image - """Diamond image.""" - + """Obraz diamentu.""" DIAMOND_SMALL: Image - """Small diamond image.""" - + """Obraz małego diamentu.""" SQUARE: Image - """Square image.""" - + """Obraz kwadratu.""" SQUARE_SMALL: Image - """Small square image.""" - + """Obraz małego kwadratu.""" RABBIT: Image - """Rabbit image.""" - + """Obraz królika.""" COW: Image - """Cow image.""" - + """Obraz krowy.""" MUSIC_CROTCHET: Image - """Crotchet note image.""" - + """Obraz ćwierćnuty.""" MUSIC_QUAVER: Image - """Quaver note image.""" - + """Obraz nuty ósemki.""" MUSIC_QUAVERS: Image - """Pair of quavers note image.""" - + """Obraz pary nut ósemek.""" PITCHFORK: Image - """Pitchfork image.""" - + """Obraz kamertonu.""" XMAS: Image - """Christmas tree image.""" - + """Obraz choinki.""" PACMAN: Image - """Pac-Man arcade character image.""" - + """Obrazek postaci arcade Pac-Man""" TARGET: Image - """Target image.""" - + """Obraz celu.""" TSHIRT: Image - """T-shirt image.""" - + """Obraz t-shirt.""" ROLLERSKATE: Image - """Rollerskate image.""" - + """Obraz Rollerskate.""" DUCK: Image - """Duck image.""" - + """Obraz kaczki.""" HOUSE: Image - """House image.""" - + """Obraz domu.""" TORTOISE: Image - """Tortoise image.""" - + """Obraz żółwia.""" BUTTERFLY: Image - """Butterfly image.""" - + """Obraz motyla.""" STICKFIGURE: Image - """Stick figure image.""" - + """Obraz przyklejonej figury.""" GHOST: Image - """Ghost image.""" - + """Obraz ducha.""" SWORD: Image - """Sword image.""" - + """Obraz miecza.""" GIRAFFE: Image - """Giraffe image.""" - + """Obraz żyrafy.""" SKULL: Image - """Skull image.""" - + """Obraz czaszki.""" UMBRELLA: Image - """Umbrella image.""" - + """Obraz parasola.""" SNAKE: Image - """Snake image.""" - + """Obraz węża.""" SCISSORS: Image - """Scissors image.""" - + """Obraz nożyczek.""" ALL_CLOCKS: List[Image] - """A list containing all the CLOCK_ images in sequence.""" - + """Lista zawierająca wszystkie obrazy CLOCK_ po kolei.""" ALL_ARROWS: List[Image] - """A list containing all the ARROW_ images in sequence.""" + """Lista zawierająca wszystkie obrazy ARROW_ po kolei.""" + @overload def __init__(self, string: str) -> None: - """Create an image from a string describing which LEDs are lit. + """Utwórz obraz z łańcucha opisującego, które diody LED są zapalone. - ``string`` has to consist of digits 0-9 arranged into lines, - describing the image, for example:: +``string`` has to consist of digits 0-9 arranged into lines, +describing the image, for example:: - image = Image("90009:" - "09090:" - "00900:" - "09090:" - "90009") + 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 newlines (\\n) insead of the colons. +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 newlines (\\n) insead of the colons. - :param string: The string describing the image. - """ +:param string: Łańcuch opisujący obraz.""" ... + @overload - def __init__( - self, width: int = 5, height: int = 5, buffer: ReadableBuffer = None - ) -> None: - """Create an empty image with ``width`` columns and ``height`` rows. + def __init__(self, width: int=5, height: int=5, buffer: ReadableBuffer=None) -> None: + """Utwórz pusty obraz z ``width`` kolumnami i ``height`` wierszami. - :param width: Optional width of the image - :param height: Optional height of the image - :param buffer: Optional array or bytes of ``width``×``height`` integers in range 0-9 to initialize the image +:param width: Opcjonalna szerokość obrazu +:param height: Opcjonalna wysokość obrazu +:param buffer: Opcjonalna tablica lub bajty ``width``×``height`` liczb całkowitych w zakresie 0-9 do zainicjowania obrazu - Examples:: +Examples:: - Image(2, 2, b'\x08\x08\x08\x08') - Image(2, 2, bytearray([9,9,9,9])) + Image(2, 2, b'\x08\x08\x08\x08') + Image(2, 2, bytearray([9,9,9,9])) - These create 2 x 2 pixel images at full brightness. - """ +These create 2 x 2 pixel images at full brightness.""" ... + def width(self) -> int: - """Get the number of columns. + """Ustal liczbę kolumn - :return: The number of columns in the image - """ +:return: The number of columns in the image""" ... + def height(self) -> int: - """Get the number of rows. + """Uzyskaj liczbę wierszy - :return: The number of rows in the image - """ +:return: The number of rows in the image""" ... + def set_pixel(self, x: int, y: int, value: int) -> None: - """Set the brightness of a pixel. + """Ustaw jasność piksela. - Example: ``my_image.set_pixel(0, 0, 9)`` +Example: ``my_image.set_pixel(0, 0, 9)`` - :param x: The column number - :param y: The row number - :param value: The brightness as an integer between 0 (dark) and 9 (bright) +:param x: Numer kolumny +:param y: Numer wiersza +:param value: Jasność jako liczba całkowita między 0 (ciemny) i 9 (jasna) - This method will raise an exception when called on any of the built-in - read-only images, like ``Image.HEART``. - """ +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: - """Get the brightness of a pixel. + """uzyskaj jasność piksela. - Example: ``my_image.get_pixel(0, 0)`` +Example: ``my_image.get_pixel(0, 0)`` - :param x: The column number - :param y: The row number - :return: The brightness as an integer between 0 and 9. - """ +:param x: Numer kolumny +:param y: Numer wiersza +:return: The brightness as an integer between 0 and 9.""" ... + def shift_left(self, n: int) -> Image: - """Create a new image by shifting the picture left. + """Utwórz nowy obraz przesuwając ten obraz w lewo. - Example: ``Image.HEART_SMALL.shift_left(1)`` +Example: ``Image.HEART_SMALL.shift_left(1)`` - :param n: The number of columns to shift by - :return: The shifted image - """ +:param n: Liczba kolumn do przesunięcia +:return: The shifted image""" ... + def shift_right(self, n: int) -> Image: - """Create a new image by shifting the picture right. + """Utwórz nowy obraz, przesuwając ten obraz w prawo. - Example: ``Image.HEART_SMALL.shift_right(1)`` +Example: ``Image.HEART_SMALL.shift_right(1)`` - :param n: The number of columns to shift by - :return: The shifted image - """ +:param n: Liczba kolumn do przesunięcia +:return: The shifted image""" ... + def shift_up(self, n: int) -> Image: - """Create a new image by shifting the picture up. + """Utwórz nowy obraz, przesuwając obraz do góry. - Example: ``Image.HEART_SMALL.shift_up(1)`` +Example: ``Image.HEART_SMALL.shift_up(1)`` - :param n: The number of rows to shift by - :return: The shifted image - """ +:param n: Liczba wierszy do przesunięcia o +:return: The shifted image""" ... + def shift_down(self, n: int) -> Image: - """Create a new image by shifting the picture down. + """Utwórz nowy obraz, przesuwając obraz do dołu. - Example: ``Image.HEART_SMALL.shift_down(1)`` +Example: ``Image.HEART_SMALL.shift_down(1)`` - :param n: The number of rows to shift by - :return: The shifted image - """ +:param n: Liczba wierszy do przesunięcia o +:return: The shifted image""" ... + def crop(self, x: int, y: int, w: int, h: int) -> Image: - """Create a new image by cropping the picture. + """Utwórz nowy obraz przez przycięcie zdjęcia. - Example: ``Image.HEART.crop(1, 1, 3, 3)`` +Example: ``Image.HEART.crop(1, 1, 3, 3)`` - :param x: The crop offset column - :param y: The crop offset row - :param w: The crop width - :param h: The crop height - :return: The new image - """ +:param x: Kolumna przesunięcia przycięcia +:param y: Wiersz przesunięcia przycięcia +:param w: Szerokość przycięcia +:param h: Wysokość przycięcia +:return: The new image""" ... + def copy(self) -> Image: - """Create an exact copy of the image. + """Utwórz dokładną kopię obrazu. - Example: ``Image.HEART.copy()`` +Example: ``Image.HEART.copy()`` - :return: The new image - """ +:return: The new image""" ... + def invert(self) -> Image: - """Create a new image by inverting the brightness of the pixels in the - source image. + """Utwórz nowy obraz przez odwrócenie jasności pikseli w obrazie źródłowym. - Example: ``Image.SMALL_HEART.invert()`` +Example: ``Image.SMALL_HEART.invert()`` - :return: The new image. - """ +:return: The new image.""" ... + def fill(self, value: int) -> None: - """Set the brightness of all the pixels in the image. + """Ustaw jasność wszystkich pikseli obrazka. - Example: ``my_image.fill(5)`` +Example: ``my_image.fill(5)`` - :param value: The new brightness as a number between 0 (dark) and 9 (bright). +:param value: Nowa jasność jako liczba między 0 (ciemny) a 9 (jasny). - This method will raise an exception when called on any of the built-in - read-only images, like ``Image.HEART``. - """ +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 an area from another image into this image. - - Example: ``my_image.blit(Image.HEART, 1, 1, 3, 3, 1, 1)`` - - :param src: The source image - :param x: The starting column offset in the source image - :param y: The starting row offset in the source image - :param w: The number of columns to copy - :param h: The number of rows to copy - :param xdest: The column offset to modify in this image - :param ydest: The row offset to modify in this image - - Pixels outside the source image are treated as having a brightness 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 blit(self, src: Image, x: int, y: int, w: int, h: int, xdest: int=0, ydest: int=0) -> None: + """Skopiuj obszar z innego obrazu na ten obraz. + +Example: ``my_image.blit(Image.HEART, 1, 1, 3, 3, 1, 1)`` + +:param src: Zdjęcie źródłowe +:param x: Początkowe przesunięcie kolumny w obrazie źródłowym +:param y: Początkowe przesunięcie wiersza na obrazie źródłowym +:param w: Liczba kolumn do skopiowania +:param h: Liczba wierszy do skopiowania +:param xdest: Przesunięcie kolumny do modyfikacji na tym obrazie +:param ydest: Przesunięcie wiersza do modyfikacji na tym obrazie + +Pixels outside the source image are treated as having a brightness 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.""" + """Uzyskaj kompaktową reprezentację obrazu w postaci łańcucha.""" ... + def __str__(self) -> str: - """Get a readable string representation of the image.""" + """Uzyskaj czytelną reprezentację obrazu w postaci łańcucha.""" ... + def __add__(self, other: Image) -> Image: - """Create a new image by adding the brightness values from the two - images for each pixel. + """Utwórz nowy obraz, dodając wartości jasności z dwóch +obrazów dla każdego piksela. - Example: ``Image.HEART + Image.HAPPY`` +Example: ``Image.HEART + Image.HAPPY`` - :param other: The image to add. - """ +:param other: Obraz do dodania.""" ... + def __sub__(self, other: Image) -> Image: - """Create a new image by subtracting the brightness values of the - other image from this image. + """Utwórz nowy obraz, odejmując wartości jasności +innego obrazu od tego obrazu. - Example: ``Image.HEART - Image.HEART_SMALL`` +Example: ``Image.HEART - Image.HEART_SMALL`` - :param other: The image to subtract. - """ +:param other: Obraz do odjęcia.""" ... + def __mul__(self, n: float) -> Image: - """Create a new image by multiplying the brightness of each pixel by - ``n``. + """Utwórz nowy obraz, mnożąc jasność każdego piksela przez +``n``. - Example: ``Image.HEART * 0.5`` +Example: ``Image.HEART * 0.5`` - :param n: The value to multiply by. - """ +:param n: Wartość do mnożenia przez.""" ... + def __truediv__(self, n: float) -> Image: - """Create a new image by dividing the brightness of each pixel by - ``n``. + """Utwórz nowy obraz, dzieląc jasność każdego piksela przez +``n``. - Example: ``Image.HEART / 2`` +Example: ``Image.HEART / 2`` - :param n: The value to divide by. - """ +:param n: Wartość do dzielenia przez.""" ... class SoundEvent: LOUD: SoundEvent - """Represents the transition of sound events, from ``quiet`` to ``loud`` like clapping or shouting.""" - + """Przedstawia przejście zdarzeń dźwiękowych z ``quiet`` do ``loud``, jak klaskanie lub krzyczenie.""" QUIET: SoundEvent - """Represents the transition of sound events, from ``loud`` to ``quiet`` like speaking or background music.""" + """Przedstawia przejście zdarzeń dźwiękowych z ``loud`` do ``quiet``, jak mówienie lub muzyka w tle.""" class Sound: - """The built-in sounds can be called using ``audio.play(Sound.NAME)``.""" - + """Wbudowane dźwięki można wywołać za pomocą ``audio.play(Sound.NAME)``.""" GIGGLE: Sound - """Giggling sound.""" - + """Chichoczący dźwięk.""" HAPPY: Sound - """Happy sound.""" - + """Szczęśliwy dźwięk.""" HELLO: Sound - """Greeting sound.""" - + """Dźwięk powitania.""" MYSTERIOUS: Sound - """Mysterious sound.""" - + """Tajemniczy dźwięk.""" SAD: Sound - """Sad sound.""" - + """Smutny dźwięk.""" SLIDE: Sound - """Sliding sound.""" - + """Przesuwający się dźwięk.""" SOARING: Sound - """Soaring sound.""" - + """Wznoszący się dźwięk.""" SPRING: Sound - """Spring sound.""" - + """Wiosny dźwięk.""" TWINKLE: Sound - """Twinkling sound.""" - + """Migoczący dźwięk.""" YAWN: Sound - """Yawning sound.""" + """Dźwięk ziewania.""" \ No newline at end of file diff --git a/lang/pl/typeshed/stdlib/microbit/accelerometer.pyi b/lang/pl/typeshed/stdlib/microbit/accelerometer.pyi index bac82c0..e47dc08 100644 --- a/lang/pl/typeshed/stdlib/microbit/accelerometer.pyi +++ b/lang/pl/typeshed/stdlib/microbit/accelerometer.pyi @@ -1,115 +1,103 @@ -"""Measure the acceleration of the micro:bit and recognise gestures. -""" - +"""Zmierz przyspieszenie micro:bita i rozpoznawaj gesty.""" from typing import Tuple def get_x() -> int: - """Get the acceleration measurement in the ``x`` axis in milli-g. + """Uzyskaj pomiar przyspieszenia na osi ``x`` w mili-g. - Example: ``accelerometer.get_x()`` +Example: ``accelerometer.get_x()`` - :return: A positive or negative integer depending on direction in the range +/- 2000mg. - """ +:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" ... def get_y() -> int: - """Get the acceleration measurement in the ``y`` axis in milli-g. + """Uzyskaj pomiar przyspieszenia na osi ``y`` w mili-g. - Example: ``accelerometer.get_y()`` +Example: ``accelerometer.get_y()`` - :return: A positive or negative integer depending on direction in the range +/- 2000mg. - """ +:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" ... def get_z() -> int: - """Get the acceleration measurement in the ``z`` axis in milli-g. + """Uzyskaj pomiar przyspieszenia na osi ``z`` w mili-g. - Example: ``accelerometer.get_z()`` +Example: ``accelerometer.get_z()`` - :return: A positive or negative integer depending on direction in the range +/- 2000mg. - """ +:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" ... def get_values() -> Tuple[int, int, int]: - """Get the acceleration measurements in all axes at once as a tuple. + """Uzyskaj pomiary przyspieszenia na wszystkich osiach jednocześnie, jako krotkę. - Example: ``x, y, z = accelerometer.get_values()`` +Example: ``x, y, z = accelerometer.get_values()`` - :return: a three-element tuple of integers ordered as X, Y, Z, each value a positive or negative integer depending on direction in the range +/- 2000mg - """ +:return: a three-element tuple of integers ordered as X, Y, Z, each value a positive or negative integer depending on direction in the range +/- 2000mg""" ... def get_strength() -> int: - """Get the acceleration measurement of all axes combined, as a positive integer. This is the Pythagorean sum of the X, Y and Z axes. + """Uzyskaj pomiar przyspieszenia wszystkich osi łącznie jako dodatnią liczbę całkowitą. Jest to suma pitagorejska osi X, Y i Z. - Example: ``accelerometer.get_strength()`` +Example: ``accelerometer.get_strength()`` - :return: The combined acceleration strength of all the axes, in milli-g. - """ +:return: The combined acceleration strength of all the axes, in milli-g.""" ... def current_gesture() -> str: - """Get the name of the current gesture. + """Pobierz nazwę aktualnego gestu. - Example: ``accelerometer.current_gesture()`` +Example: ``accelerometer.current_gesture()`` - 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. +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. - :return: The current gesture - """ +:return: The current gesture""" ... def is_gesture(name: str) -> bool: - """Check if the named gesture is currently active. + """Sprawdź, czy nazwany gest jest aktualnie aktywny. - Example: ``accelerometer.is_gesture('shake')`` +Example: ``accelerometer.is_gesture('shake')`` - 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. +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. - :param name: The gesture name. - :return: ``True`` if the gesture is active, ``False`` otherwise. - """ +:param name: Nazwa gestu. +:return: ``True`` if the gesture is active, ``False`` otherwise.""" ... def was_gesture(name: str) -> bool: - """Check if the named gesture was active since the last call. + """Sprawdź, czy nazwany gest był aktywny od ostatniego połączenia. - Example: ``accelerometer.was_gesture('shake')`` +Example: ``accelerometer.was_gesture('shake')`` - 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. +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. - :param name: The gesture name. - :return: ``True`` if the gesture was active since the last call, ``False`` otherwise. - """ +:param name: Nazwa gestu. +:return: ``True`` if the gesture was active since the last call, ``False`` otherwise.""" def get_gestures() -> Tuple[str, ...]: - """Return a tuple of the gesture history. + """Zwróć krotkę historii gestów. - Example: ``accelerometer.get_gestures()`` +Example: ``accelerometer.get_gestures()`` - Clears the gesture history before returning. +Clears the gesture history before returning. - Gestures are not updated in the background so there needs to be constant - calls to some accelerometer method to do the gesture detection. Usually - gestures can be detected using a loop with a small :func:`microbit.sleep` delay. +Gestures are not updated in the background so there needs to be constant +calls to some accelerometer method to do the gesture detection. Usually +gestures can be detected using a loop with a small :func:`microbit.sleep` delay. - :return: The history as a tuple, most recent last. - """ +:return: The history as a tuple, most recent last.""" ... def set_range(value: int) -> None: - """Set the accelerometer sensitivity range, in g (standard gravity), to the closest values supported by the hardware, so it rounds to either ``2``, ``4``, or ``8`` g. + """Ustaw zakres czułości akcelerometru w g (standardowa grawitacja) na najbliższe wartości obsługiwane przez sprzęt tak, aby zaokrąglał się do ``2``, ``4`` lub ``8`` g. - Example: ``accelerometer.set_range(8)`` +Example: ``accelerometer.set_range(8)`` - :param value: New range for the accelerometer, an integer in ``g``. - """ +:param value: Nowy zakres dla akcelerometru, liczba całkowita w ``g``.""" \ No newline at end of file diff --git a/lang/pl/typeshed/stdlib/microbit/audio.pyi b/lang/pl/typeshed/stdlib/microbit/audio.pyi index 3b1e327..3a3fe4b 100644 --- a/lang/pl/typeshed/stdlib/microbit/audio.pyi +++ b/lang/pl/typeshed/stdlib/microbit/audio.pyi @@ -1,160 +1,123 @@ -"""Play sounds using the micro:bit (import ``audio`` for V1 compatibility). -""" - +"""Odtwarzaj dźwięki za pomocą micro:bita (importuj ``audio`` dla kompatybilności V1).""" from ..microbit import MicroBitDigitalPin, Sound, pin0 from typing import ClassVar, Iterable, Union -def play( - source: Union[Iterable[AudioFrame], Sound, SoundEffect], - wait: bool = True, - pin: MicroBitDigitalPin = pin0, - return_pin: Union[MicroBitDigitalPin, None] = None, -) -> None: - """Play a built-in sound, sound effect or custom audio frames. +def play(source: Union[Iterable[AudioFrame], Sound, SoundEffect], wait: bool=True, pin: MicroBitDigitalPin=pin0, return_pin: Union[MicroBitDigitalPin, None]=None) -> None: + """Odtwórz wbudowany dźwięk, efekt dźwiękowy lub niestandardowe ramki audio. - Example: ``audio.play(Sound.GIGGLE)`` +Example: ``audio.play(Sound.GIGGLE)`` - :param source: A built-in ``Sound`` such as ``Sound.GIGGLE``, a ``SoundEffect`` or sample data as an iterable of ``AudioFrame`` objects. - :param wait: If ``wait`` is ``True``, this function will block until the sound is complete. - :param pin: An optional argument to specify the output pin can be used to override the default of ``pin0``. If we do not want any sound to play we can use ``pin=None``. - :param return_pin: Specifies a differential edge connector pin to connect to an external speaker instead of ground. This is ignored for the **V2** revision. - """ +:param source: Wbudowany ``Sound``, taki jak ``Sound.GIGGLE``, ``SoundEffect`` lub przykładowe dane jako iteracja obiektów ``AudioFrame``. +:param wait: Jeśli ``wait`` jest ``True``, ta funkcja będzie blokować, aż dźwięk zostanie zakończony. +:param pin: Opcjonalny argument do określenia pinu wyjściowego może być użyty do nadpisania domyślnej wartości ``pin0``. Jeśli nie chcemy, aby żaden dźwięk nie był odtwarzany, możemy użyć ``pin=None``. +:param return_pin: Określa pin łącznika różnicowego, aby podłączyć płytkę do zewnętrznego głośnika zamiast do ziemi. Jest to ignorowane dla **V2**.""" def is_playing() -> bool: - """Check whether a sound is playing. + """Sprawdź, czy dźwięk jest odtwarzany. - Example: ``audio.is_playing()`` +Example: ``audio.is_playing()`` - :return: ``True`` if audio is playing, otherwise ``False``.""" +:return: ``True`` if audio is playing, otherwise ``False``.""" ... def stop() -> None: - """Stop all audio playback. + """Zatrzymaj odtwarzania audio. - Example: ``audio.stop()`` - """ +Example: ``audio.stop()``""" ... class SoundEffect: - """A sound effect, composed by a set of parameters configured via the constructor or attributes.""" - + """Efekt dźwiękowy, utworzony przez zestaw parametrów skonfigurowanych za pomocą konstruktora lub atrybutów.""" WAVEFORM_SINE: ClassVar[int] - """Sine wave option used for the ``waveform`` parameter.""" - + """Opcja sinusoidalnej fali używana dla parametru ``waveform``.""" WAVEFORM_SAWTOOTH: ClassVar[int] - """Sawtooth wave option used for the ``waveform`` parameter.""" - + """Opcja fali piłokształtnej używana dla parametru ``waveform``.""" WAVEFORM_TRIANGLE: ClassVar[int] - """Triangle wave option used for the ``waveform`` parameter.""" - + """Opcja fali trójkątnej używana dla parametru ``waveform``.""" WAVEFORM_SQUARE: ClassVar[int] - """Square wave option used for the ``waveform`` parameter.""" - + """Opcja fali kwadratowj używana dla parametru ``waveform``.""" WAVEFORM_NOISE: ClassVar[int] - """Noise option used for the ``waveform`` parameter.""" - + """Opcja szumu używana dla parametru ``waveform``.""" SHAPE_LINEAR: ClassVar[int] - """Linear interpolation option used for the ``shape`` parameter.""" - + """Opcja interpolacji liniowej używana dla parametru ``shape``.""" SHAPE_CURVE: ClassVar[int] - """Curve interpolation option used for the ``shape`` parameter.""" - + """Opcja interpolacji krzywej używana dla parametru ``shape``.""" SHAPE_LOG: ClassVar[int] - """Logarithmic interpolation option used for the ``shape`` parameter.""" - + """Opcja interpolacji logarytmicznej używana dla parametru ``shape``.""" FX_NONE: ClassVar[int] - """No effect option used for the ``fx`` parameter.""" - + """Opcja braku efektu użyta dla parametru ``fx``.""" FX_TREMOLO: ClassVar[int] - """Tremolo effect option used for the ``fx`` parameter.""" - + """Opcja efektu Tremelo użyta dla parametru ``fx``.""" FX_VIBRATO: ClassVar[int] - """Vibrato effect option used for the ``fx`` parameter.""" - + """Opcja efektu Vibrato użyta dla parametru ``fx``.""" FX_WARBLE: ClassVar[int] - """Warble effect option used for the ``fx`` parameter.""" - + """Opcja efektu Warble użyta dla parametru ``fx``.""" freq_start: int - """Start frequency in Hertz (Hz), a number between ``0`` and ``9999``""" - + """Częstotliwość początkowa w hercach (Hz), liczba między ``0`` i ``9999``""" freq_end: int - """End frequency in Hertz (Hz), a number between ``0`` and ``9999``""" - + """Częstotliwość końcowa w hercach (Hz), liczba między ``0`` i ``9999``""" duration: int - """Duration of the sound in milliseconds, a number between ``0`` and ``9999``""" - + """Czas trwania dźwięku w milisekundach, liczba pomiędzy ``0`` i ``9999``""" vol_start: int - """Start volume value, a number between ``0`` and ``255``""" - + """Wartość głośności początkowej, liczba między ``0`` i ``255``""" vol_end: int - """End volume value, a number between ``0`` and ``255``""" - + """Wartość głośności końcowej, liczba między ``0`` i ``255``""" waveform: int - """Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise)""" - + """Rodzaj kształtu fali, jedna z tych wartości:``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (losowo generowany szum)""" fx: int - """Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``""" - + """Efekt do dodania do dźwięku, jedna z następujących wartości: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE`` lub ``FX_NONE``""" shape: int - """The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``""" - - def __init__( - self, - freq_start: int = 500, - freq_end: int = 2500, - duration: int = 500, - vol_start: int = 255, - vol_end: int = 0, - waveform: int = WAVEFORM_SQUARE, - fx: int = FX_NONE, - shape: int = SHAPE_LOG, - ): - """Create a new sound effect. - - Example: ``my_effect = SoundEffect(duration=1000)`` - - All the parameters are optional, with default values as shown above, and - they can all be modified via attributes of the same name. For example, we - can first create an effect ``my_effect = SoundEffect(duration=1000)``, - and then change its attributes ``my_effect.duration = 500``. - - :param freq_start: Start frequency in Hertz (Hz), a number between ``0`` and ``9999``. - :param freq_end: End frequency in Hertz (Hz), a number between ``0`` and ``9999``. - :param duration: Duration of the sound in milliseconds, a number between ``0`` and ``9999``. - :param vol_start: Start volume value, a number between ``0`` and ``255``. - :param vol_end: End volume value, a number between ``0`` and ``255``. - :param waveform: Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise). - :param fx: Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``. - :param shape: The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``. - """ + """Rodzaj krzywej interpolacji między częstotliwością początkową i końcową, różne kształty fal mają różne szybkości zmian częstotliwości. Jedna z następujących wartości: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``""" + + def __init__(self, freq_start: int=500, freq_end: int=2500, duration: int=500, vol_start: int=255, vol_end: int=0, waveform: int=WAVEFORM_SQUARE, fx: int=FX_NONE, shape: int=SHAPE_LOG): + """Utwórz nowy efekt dźwiękowy. + +Example: ``my_effect = SoundEffect(duration=1000)`` + +All the parameters are optional, with default values as shown above, and +they can all be modified via attributes of the same name. For example, we +can first create an effect ``my_effect = SoundEffect(duration=1000)``, +and then change its attributes ``my_effect.duration = 500``. + +:param freq_start: Częstotliwość początkowa w hercach (Hz), liczba między ``0`` i ``9999``. +:param freq_end: Częstotliwość końcowa w hercach (Hz), liczba między ``0`` i ``9999``. +:param duration: Czas trwania dźwięku w milisekundach, liczba między ``0`` i ``9999``. +:param vol_start: Początkowa wartość głośności, liczba pomiędzy ``0`` i ``255``. +:param vol_end: Końcowa wartość głośności, liczba pomiędzy ``0`` i ``255``. +:param waveform: Rodzaj kształtu fali, jedna z tych wartości: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (losowo generowany szum). +:param fx: Efekt do dodania do dźwięku, jedna z następujących wartości: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE`` lub ``FX_NONE``. +:param shape: Rodzaj krzywej interpolacji między częstotliwością początkową i końcową, różne kształty fal mają różne szybkości zmian częstotliwości. Jedna z następujących wartości: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``.""" + def copy(self) -> SoundEffect: - """Create a copy of this ``SoundEffect``. + """Utwórz kopię ``SoundEffect``. - Example: ``sound_2 = sound_1.copy()`` +Example: ``sound_2 = sound_1.copy()`` - :return: A copy of the SoundEffect. - """ +:return: A copy of the SoundEffect.""" class AudioFrame: - """An ``AudioFrame`` object is a list of 32 samples each of which is a unsigned byte - (whole number between 0 and 255). + """Obiekt ``AudioFrame`` jest listą 32 próbek, z których każda jest niepodpisanym bajtem (liczba całkowita między 0 a 255). - It takes just over 4 ms to play a single frame. +It takes just over 4 ms to play a single frame. - Example:: +Example:: - frame = AudioFrame() - for i in range(len(frame)): - frame[i] = 252 - i * 8 - """ + frame = AudioFrame() + for i in range(len(frame)): + frame[i] = 252 - i * 8""" def copyfrom(self, other: AudioFrame) -> None: - """Overwrite the data in this ``AudioFrame`` with the data from another ``AudioFrame`` instance. + """Zastąp dane w tym ``AudioFrame`` danymi z innej instancji ``AudioFrame``. + +Example: ``my_frame.copyfrom(source_frame)`` + +:param other: Instancja ``AudioFrame``, z której skopiowane są dane.""" + + def __len__(self) -> int: + ... - Example: ``my_frame.copyfrom(source_frame)`` + def __setitem__(self, key: int, value: int) -> None: + ... - :param other: ``AudioFrame`` instance from which to copy the data. - """ - def __len__(self) -> int: ... - def __setitem__(self, key: int, value: int) -> None: ... - def __getitem__(self, key: int) -> int: ... + def __getitem__(self, key: int) -> int: + ... \ No newline at end of file diff --git a/lang/pl/typeshed/stdlib/microbit/compass.pyi b/lang/pl/typeshed/stdlib/microbit/compass.pyi index c74a47b..cd6c9c7 100644 --- a/lang/pl/typeshed/stdlib/microbit/compass.pyi +++ b/lang/pl/typeshed/stdlib/microbit/compass.pyi @@ -1,78 +1,70 @@ -"""Use the built-in compass. -""" +"""Użyj wbudowanego kompasu.""" def calibrate() -> None: - """Starts the calibration process. + """Rozpoczyna proces kalibracji. - Example: ``compass.calibrate()`` +Example: ``compass.calibrate()`` - 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. - """ +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: - """Check is the compass is calibrated. + """Sprawdź, czy kompas jest skalibrowany. - Example: ``compass.is_calibrated()`` +Example: ``compass.is_calibrated()`` - :return: ``True`` if the compass has been successfully calibrated, ``False`` otherwise. - """ +:return: ``True`` if the compass has been successfully calibrated, ``False`` otherwise.""" ... def clear_calibration() -> None: - """Undoes the calibration, making the compass uncalibrated again. + """Cofnij kalibrację, czyniąc kompas ponownie niekalibrowanym. - Example: ``compass.clear_calibration()`` - """ +Example: ``compass.clear_calibration()``""" ... def get_x() -> int: - """Get the magnetic field strength on the ``x`` axis. + """Uzyskaj natężenie pola magnetycznego na osi ``x``. - Example: ``compass.get_x()`` +Example: ``compass.get_x()`` - Call ``calibrate`` first or the results will be inaccurate. +Call ``calibrate`` first or the results will be inaccurate. - :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. - """ +:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" ... def get_y() -> int: - """Get the magnetic field strength on the ``y`` axis. + """Uzyskaj natężenie pola magnetycznego na osi ``y``. - Example: ``compass.get_y()`` +Example: ``compass.get_y()`` - Call ``calibrate`` first or the results will be inaccurate. +Call ``calibrate`` first or the results will be inaccurate. - :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. - """ +:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" ... def get_z() -> int: - """Get the magnetic field strength on the ``z`` axis. + """Uzyskaj natężenie pola magnetycznego na osi ``z``. - Example: ``compass.get_z()`` +Example: ``compass.get_z()`` - Call ``calibrate`` first or the results will be inaccurate. +Call ``calibrate`` first or the results will be inaccurate. - :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. - """ +:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" ... def heading() -> int: - """Get the compass heading. + """Pobierz kierunek kompasu. - Example: ``compass.heading()`` +Example: ``compass.heading()`` - :return: An integer in the range from 0 to 360, representing the angle in degrees, clockwise, with north as 0. - """ +:return: An integer in the range from 0 to 360, representing the angle in degrees, clockwise, with north as 0.""" ... def get_field_strength() -> int: - """Get the magnitude of the magnetic field around the device. + """Uzyskaj wielkość pola magnetycznego wokół urządzenia. - Example: ``compass.get_field_strength()`` +Example: ``compass.get_field_strength()`` - :return: An integer indication of the magnitude of the magnetic field in nano tesla.""" - ... +:return: An integer indication of the magnitude of the magnetic field in nano tesla.""" + ... \ No newline at end of file diff --git a/lang/pl/typeshed/stdlib/microbit/display.pyi b/lang/pl/typeshed/stdlib/microbit/display.pyi index aa4013e..25ee96c 100644 --- a/lang/pl/typeshed/stdlib/microbit/display.pyi +++ b/lang/pl/typeshed/stdlib/microbit/display.pyi @@ -1,115 +1,92 @@ -"""Show text, images and animations on the 5×5 LED display. -""" - +"""Pokaż tekst, obrazy i animacje na wyświetlaczu 5x5 LED.""" from ..microbit import Image from typing import Union, overload, Iterable def get_pixel(x: int, y: int) -> int: - """Get the brightness of the LED at column ``x`` and row ``y``. + """Uzyskaj jasność LED w kolumnie ``x`` i w wierszu ``y``. - Example: ``display.get_pixel(0, 0)`` +Example: ``display.get_pixel(0, 0)`` - :param x: The display column (0..4) - :param y: The display row (0..4) - :return: A number between 0 (off) and 9 (bright) - """ +:param x: Wyświetlana kolumna (0..4) +:param y: Wyświetlany wiersz (0..4) +:return: A number 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``. + """Ustaw jasność LED w kolumnie ``x`` i wierszu ``y``. - Example: ``display.set_pixel(0, 0, 9)`` +Example: ``display.set_pixel(0, 0, 9)`` - :param x: The display column (0..4) - :param y: The display row (0..4) - :param value: The brightness between 0 (off) and 9 (bright) - """ +:param x: Wyświetlana kolumna (0..4) +:param y: Wyświetlany wiersz (0..4) +:param value: Jasność między 0 (wyłączona) i 9 (jasna)""" ... def clear() -> None: - """Set the brightness of all LEDs to 0 (off). + """Ustaw jasność wszystkich diod LED na 0 (wyłączone). - Example: ``display.clear()`` - """ +Example: ``display.clear()``""" ... -def show( - image: Union[str, float, int, Image, Iterable[Image]], - delay: int = 400, - wait: bool = True, - loop: bool = False, - clear: bool = False, -) -> None: - """Shows images, letters or digits on the LED display. +def show(image: Union[str, float, int, Image, Iterable[Image]], delay: int=400, wait: bool=True, loop: bool=False, clear: bool=False) -> None: + """Pokazuje obrazy, litery lub cyfry na wyświetlaczu LED. - Example: ``display.show(Image.HEART)`` +Example: ``display.show(Image.HEART)`` - When ``image`` is an image or a list of images then each image is displayed in turn. - If ``image`` is a string or number, each letter or digit is displayed in turn. +When ``image`` is an image or a list of images then each image is displayed in turn. +If ``image`` is a string or number, each letter or digit is displayed in turn. - :param image: A string, number, image or list of images to show. - :param delay: Each letter, digit or image is shown with ``delay`` milliseconds between them. - :param wait: If ``wait`` is ``True``, this function will block until the animation is finished, otherwise the animation will happen in the background. - :param loop: If ``loop`` is ``True``, the animation will repeat forever. - :param clear: If ``clear`` is ``True``, the display will be cleared after the sequence has finished. +:param image: Łańcuch, liczba, obraz lub lista obrazów do pokazania. +:param delay: Każda litera, cyfra lub obraz są wyświetlane z ``delay`` milisekundami między sobą. +:param wait: Jeśli ``wait`` jest ``True``, ta funkcja będzie blokować, aż zakończy się animacja, w przeciwnym razie animacja pojawi się w tle. +:param loop: Jeśli ``loop`` jest ``True``, animacja będzie powtarzana w nieskończoność. +:param clear: Jeśli ``clear`` jest ``True``, wyświetlacz zostanie wyczyszczony po zakończeniu sekwencji. - The ``wait``, ``loop`` and ``clear`` arguments must be specified using their keyword. - """ +The ``wait``, ``loop`` and ``clear`` arguments must be specified using their keyword.""" ... -def scroll( - text: Union[str, float, int], - delay: int = 150, - wait: bool = True, - loop: bool = False, - monospace: bool = False, -) -> None: - """Scrolls a number or text on the LED display. - - Example: ``display.scroll('micro:bit')`` - - :param text: The string to scroll. If ``text`` is an integer or float it is first converted to a string using ``str()``. - :param delay: The ``delay`` parameter controls how fast the text is scrolling. - :param wait: If ``wait`` is ``True``, this function will block until the animation is finished, otherwise the animation will happen in the background. - :param loop: If ``loop`` is ``True``, the animation will repeat forever. - :param monospace: 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. - - The ``wait``, ``loop`` and ``monospace`` arguments must be specified - using their keyword. - """ +def scroll(text: Union[str, float, int], delay: int=150, wait: bool=True, loop: bool=False, monospace: bool=False) -> None: + """Przewija liczbę lub tekst na wyświetlaczu LED. + +Example: ``display.scroll('micro:bit')`` + +:param text: Łańcuch do przewinięcia. Jeśli ``text`` jest liczbą całkowitą lub zmiennopozycyjną, najpierw zostanie przekonwertowany na łańcuch za pomocą ``str()``. +:param delay: Parametr ``delay`` kontroluje szybkość przewijania tekstu. +:param wait: Jeśli ``wait`` jest ``True``, ta funkcja będzie blokować, aż zakończy się animacja, w przeciwnym razie animacja pojawi się w tle. +:param loop: Jeśli ``loop`` jest ``True``, animacja będzie powtarzana w nieskończoność. +:param monospace: Jeśli ``monospace`` jest ``True``, wszystkie znaki zajmą co najwyżej 5 kolumn pikseli na szerokość, w przeciwnym razie będzie dokładnie 1 pusta kolumna pikseli pomiędzy każdym znakiem, gdy się przewijają. + +The ``wait``, ``loop`` and ``monospace`` arguments must be specified +using their keyword.""" ... def on() -> None: - """Turn on the LED display. + """Włącz wyświetlacz LED. - Example: ``display.on()`` - """ +Example: ``display.on()``""" ... def off() -> None: - """Turn off the LED display (disabling the display allows you to re-use the GPIO pins for other purposes). + """Wyłącz wyświetlacz LED (wyłączenie wyświetlania pozwala na ponowne użycie pinów GPIO do innych celów). - Example: ``display.off()`` - """ +Example: ``display.off()``""" ... def is_on() -> bool: - """Check whether the LED display is enabled. + """Sprawdź, czy wyświetlacz LED jest włączony. - Example: ``display.is_on()`` +Example: ``display.is_on()`` - :return: ``True`` if the display is on, otherwise returns ``False``. - """ +:return: ``True`` if the display is on, otherwise returns ``False``.""" ... def read_light_level() -> int: - """Read the light level. + """Odczytuj poziom światła. - Example: ``display.read_light_level()`` +Example: ``display.read_light_level()`` - Uses the display's LEDs in reverse-bias mode to sense the amount of light - falling on the display. +Uses the display's LEDs in reverse-bias mode to sense the amount of light +falling on the display. - :return: An integer between 0 and 255 representing the light level, with larger meaning more light. - """ - ... +:return: An integer between 0 and 255 representing the light level, with larger meaning more light.""" + ... \ No newline at end of file diff --git a/lang/pl/typeshed/stdlib/microbit/i2c.pyi b/lang/pl/typeshed/stdlib/microbit/i2c.pyi index df26efa..0adc4a4 100644 --- a/lang/pl/typeshed/stdlib/microbit/i2c.pyi +++ b/lang/pl/typeshed/stdlib/microbit/i2c.pyi @@ -1,57 +1,49 @@ -"""Communicate with devices using the I²C bus protocol. -""" - +"""Komunikuj się z urządzeniami za pomocą protokołu magistrali I2C.""" from _typeshed import ReadableBuffer from ..microbit import MicroBitDigitalPin, pin19, pin20 from typing import List -def init( - freq: int = 100000, sda: MicroBitDigitalPin = pin20, scl: MicroBitDigitalPin = pin19 -) -> None: - """Re-initialize a peripheral. +def init(freq: int=100000, sda: MicroBitDigitalPin=pin20, scl: MicroBitDigitalPin=pin19) -> None: + """Ponownie zainicjuj peryferia. - Example: ``i2c.init()`` +Example: ``i2c.init()`` - :param freq: clock frequency - :param sda: ``sda`` pin (default 20) - :param scl: ``scl`` pin (default 19) +:param freq: clock frequency +:param sda: ``sda`` pin (domyślnie 20) +:param scl: ``scl`` pin (domyślnie 19) - On a micro:bit V1 board, changing the I²C pins from defaults will make - the accelerometer and compass stop working, as they are connected - internally to those pins. This warning does not apply to the **V2** - revision of the micro:bit as this has `separate I²C lines `_ - for the motion sensors and the edge connector. - """ +On a micro:bit V1 board, changing the I²C pins from defaults will make +the accelerometer and compass stop working, as they are connected +internally to those pins. This warning does not apply to the **V2** +revision of the micro:bit as this has `separate I²C lines `_ +for the motion sensors and the edge connector.""" ... def scan() -> List[int]: - """Scan the bus for devices. + """Przeskanuj magistralę w poszukiwaniu urządzeń. - Example: ``i2c.scan()`` +Example: ``i2c.scan()`` - :return: A list of 7-bit addresses corresponding to those devices that responded to the scan. - """ +:return: A list of 7-bit addresses corresponding to those devices that responded to the scan.""" ... -def read(addr: int, n: int, repeat: bool = False) -> bytes: - """Read bytes from a device. +def read(addr: int, n: int, repeat: bool=False) -> bytes: + """Odczytaj bajty z urządzenia.. - Example: ``i2c.read(0x50, 64)`` +Example: ``i2c.read(0x50, 64)`` - :param addr: The 7-bit address of the device - :param n: The number of bytes to read - :param repeat: If ``True``, no stop bit will be sent - :return: The bytes read - """ +:param addr: 7-bitowy adres urządzenia +:param n: Liczba bajtów do odczytu +:param repeat: Jeśli ``True``, nie zostaną wysłane żadne bity zatrzymania +:return: The bytes read""" ... -def write(addr: int, buf: ReadableBuffer, repeat: bool = False) -> None: - """Write bytes to a device. +def write(addr: int, buf: ReadableBuffer, repeat: bool=False) -> None: + """Zapisz bajty na urządzenie. - Example: ``i2c.write(0x50, bytes([1, 2, 3]))`` +Example: ``i2c.write(0x50, bytes([1, 2, 3]))`` - :param addr: The 7-bit address of the device - :param buf: A buffer containing the bytes to write - :param repeat: If ``True``, no stop bit will be sent - """ - ... +:param addr: 7-bitowy adres urządzenia +:param buf: Bufor zawierający bajty do zapisu +:param repeat: Jeśli ``True``, nie zostaną wysłane żadne bity zatrzymania""" + ... \ No newline at end of file diff --git a/lang/pl/typeshed/stdlib/microbit/microphone.pyi b/lang/pl/typeshed/stdlib/microbit/microphone.pyi index 68e8f3a..368df6f 100644 --- a/lang/pl/typeshed/stdlib/microbit/microphone.pyi +++ b/lang/pl/typeshed/stdlib/microbit/microphone.pyi @@ -1,70 +1,62 @@ -"""Respond to sound using the built-in microphone (V2 only). -""" - +"""Odpowiedz na dźwięk przy użyciu wbudowanego mikrofonu (tylko V2).""" from typing import Optional, Tuple from ..microbit import SoundEvent def current_event() -> Optional[SoundEvent]: - """Get the last recorded sound event + """Pobierz ostatnie nagrane zdarzenie dźwiękowe - Example: ``microphone.current_event()`` +Example: ``microphone.current_event()`` - :return: The event, ``SoundEvent('loud')`` or ``SoundEvent('quiet')``. - """ +:return: The event, ``SoundEvent('loud')`` or ``SoundEvent('quiet')``.""" ... def was_event(event: SoundEvent) -> bool: - """Check if a sound was heard at least once since the last call. + """Sprawdź, czy dźwięk był słyszany co najmniej raz od ostatniego połączenia. - Example: ``microphone.was_event(SoundEvent.LOUD)`` +Example: ``microphone.was_event(SoundEvent.LOUD)`` - This call clears the sound history before returning. +This call clears the sound history before returning. - :param event: The event to check for, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET`` - :return: ``True`` if sound was heard at least once since the last call, otherwise ``False``. - """ +:param event: Zdarzenie do sprawdzenia, takie jak ``SoundEvent.LOUD`` lub ``SoundEvent.QUIET`` +:return: ``True`` if sound was heard at least once since the last call, otherwise ``False``.""" ... def is_event(event: SoundEvent) -> bool: - """Check the most recent sound event detected. + """Sprawdź najnowsze wykryte zdarzenie dźwiękowe. - Example: ``microphone.is_event(SoundEvent.LOUD)`` +Example: ``microphone.is_event(SoundEvent.LOUD)`` - This call does not clear the sound event history. +This call does not clear the sound event history. - :param event: The event to check for, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET`` - :return: ``True`` if sound was the most recent heard, ``False`` otherwise. - """ +:param event: Zdarzenie do sprawdzenia, takie jak ``SoundEvent.LOUD`` lub ``SoundEvent.QUIET`` +:return: ``True`` if sound was the most recent heard, ``False`` otherwise.""" ... def get_events() -> Tuple[SoundEvent, ...]: - """Get the sound event history as a tuple. + """Pobierz historię zdarzeń dźwiękowych jako krotkę. - Example: ``microphone.get_events()`` +Example: ``microphone.get_events()`` - This call clears the sound history before returning. +This call clears the sound history before returning. - :return: A tuple of the event history with the most recent event last. - """ +:return: A tuple of the event history with the most recent event last.""" ... def set_threshold(event: SoundEvent, value: int) -> None: - """Set the threshold for a sound event. + """Ustaw próg dla zdarzenia dźwiękowego. - Example: ``microphone.set_threshold(SoundEvent.LOUD, 250)`` +Example: ``microphone.set_threshold(SoundEvent.LOUD, 250)`` - A high threshold means the event will only trigger if the sound is very loud (>= 250 in the example). +A high threshold means the event will only trigger if the sound is very loud (>= 250 in the example). - :param event: A sound event, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET``. - :param value: The threshold level in the range 0-255. - """ +:param event: Zdarzenie dźwiękowe, takie jak ``SoundEvent.LOUD`` lub ``SoundEvent.QUIET``. +:param value: Poziom progu w zakresie 0-255.""" ... def sound_level() -> int: - """Get the sound pressure level. + """Uzyskaj poziom ciśnienia akustycznego. - Example: ``microphone.sound_level()`` +Example: ``microphone.sound_level()`` - :return: A representation of the sound pressure level in the range 0 to 255. - """ - ... +:return: A representation of the sound pressure level in the range 0 to 255.""" + ... \ No newline at end of file diff --git a/lang/pl/typeshed/stdlib/microbit/speaker.pyi b/lang/pl/typeshed/stdlib/microbit/speaker.pyi index 5a74a4d..9cd1b88 100644 --- a/lang/pl/typeshed/stdlib/microbit/speaker.pyi +++ b/lang/pl/typeshed/stdlib/microbit/speaker.pyi @@ -1,18 +1,15 @@ -"""Control the built-in speaker (V2 only). -""" +"""Sprawdź wbudowany głośnik (tylko V2).""" def off() -> None: - """Turn the speaker off. + """Wyłącz głośnik. - Example: ``speaker.off()`` +Example: ``speaker.off()`` - This does not disable sound output to an edge connector pin. - """ +This does not disable sound output to an edge connector pin.""" ... def on() -> None: - """Turn the speaker on. + """Włącz głośnik. - Example: ``speaker.on()`` - """ - ... +Example: ``speaker.on()``""" + ... \ No newline at end of file diff --git a/lang/pl/typeshed/stdlib/microbit/spi.pyi b/lang/pl/typeshed/stdlib/microbit/spi.pyi index 09c4046..9dc3445 100644 --- a/lang/pl/typeshed/stdlib/microbit/spi.pyi +++ b/lang/pl/typeshed/stdlib/microbit/spi.pyi @@ -1,60 +1,47 @@ -"""Communicate with devices using the serial peripheral interface (SPI) bus. -""" - +"""Komunikuj się z urządzeniami za pomocą magistrali szeregowego interfejsu (SPI).""" from _typeshed import ReadableBuffer, WriteableBuffer from ..microbit import pin13, pin14, pin15, MicroBitDigitalPin -def init( - baudrate: int = 1000000, - bits: int = 8, - mode: int = 0, - sclk: MicroBitDigitalPin = pin13, - mosi: MicroBitDigitalPin = pin15, - miso: MicroBitDigitalPin = pin14, -) -> None: - """Initialize SPI communication. - - Example: ``spi.init()`` - - For correct communication, the parameters have to be the same on both communicating devices. - - :param baudrate: The speed of communication. - :param bits: The width in bits of each transfer. Currently only ``bits=8`` is supported. However, this may change in the future. - :param mode: Determines the combination of clock polarity and phase - `see online table `_. - :param sclk: sclk pin (default 13) - :param mosi: mosi pin (default 15) - :param miso: miso pin (default 14) - """ +def init(baudrate: int=1000000, bits: int=8, mode: int=0, sclk: MicroBitDigitalPin=pin13, mosi: MicroBitDigitalPin=pin15, miso: MicroBitDigitalPin=pin14) -> None: + """Zainicjuj komunikację SPI. + +Example: ``spi.init()`` + +For correct communication, the parameters have to be the same on both communicating devices. + +:param baudrate: Szybkość komunikacji. +:param bits: Szerokość w bitach każdego transferu. Obecnie obsługiwanych jest tylko ``bits=8``. Może to jednak ulec zmianie w przyszłości. +:param mode: Określa połączenie polarności zegara i fazy - `zobacz tabelę online `_. +:param sclk: pin sclk (domyślnie 13) +:param mosi: pin mosi (domyślnie 15) +:param miso: pin miso (domyślnie 14)""" ... -def read(nbytes: int, out: int = 0) -> bytes: - """Read at most ``nbytes`` while continuously writing the single byte given by ``out``. +def read(nbytes: int, out: int=0) -> bytes: + """Przeczytaj co najwyżej ``nbytes`` podczas ciągłego pisania pojedynczego bajtu danego przez ``out``. - Example: ``spi.read(64)`` +Example: ``spi.read(64)`` - :param nbytes: Maximum number of bytes to read. - :param out: The byte value to write (default 0). - :return: The bytes read. - """ +:param nbytes: Maksymalna liczba bajtów do odczytu. +:param out: Wartość bajtu do zapisu (domyślnie 0). +:return: The bytes read.""" ... def write(buffer: ReadableBuffer) -> None: - """Write bytes to the bus. + """Zapisz bajty na magistrali. - Example: ``spi.write(bytes([1, 2, 3]))`` +Example: ``spi.write(bytes([1, 2, 3]))`` - :param buffer: A buffer to read data from. - """ +:param buffer: Bufor do odczytu danych.""" ... def write_readinto(out: WriteableBuffer, in_: ReadableBuffer) -> None: - """Write the ``out`` buffer to the bus and read any response into the ``in_`` buffer. + """Zapisz bufor ``out`` do magistrali i wczytaj dowolną odpowiedź do bufora ``in_``. - Example: ``spi.write_readinto(out_buffer, in_buffer)`` +Example: ``spi.write_readinto(out_buffer, in_buffer)`` - The length of the buffers should be the same. The buffers can be the same object. +The length of the buffers should be the same. The buffers can be the same object. - :param out: The buffer to write any response to. - :param in_: The buffer to read data from. - """ - ... +:param out: Bufor do zapisu dowolnej odpowiedzi. +:param in_: Bufor do odczytu danych.""" + ... \ No newline at end of file diff --git a/lang/pl/typeshed/stdlib/microbit/uart.pyi b/lang/pl/typeshed/stdlib/microbit/uart.pyi index 2ab650f..375b560 100644 --- a/lang/pl/typeshed/stdlib/microbit/uart.pyi +++ b/lang/pl/typeshed/stdlib/microbit/uart.pyi @@ -1,96 +1,79 @@ -"""Communicate with a device using a serial interface. -""" - +"""Komunikuj się z urządzeniem za pomocą interfejsu szeregowego.""" from _typeshed import WriteableBuffer from ..microbit import MicroBitDigitalPin from typing import Optional, Union - ODD: int -"""Odd parity""" - +"""Nieparzysta parzystość""" EVEN: int -"""Even parity""" - -def init( - baudrate: int = 9600, - bits: int = 8, - parity: Optional[int] = None, - stop: int = 1, - tx: Optional[MicroBitDigitalPin] = None, - rx: Optional[MicroBitDigitalPin] = None, -) -> None: - """Initialize serial communication. - - Example: ``uart.init(115200, tx=pin0, rx=pin1)`` - - :param baudrate: The speed of communication. - :param bits: The size of bytes being transmitted. micro:bit only supports 8. - :param parity: How parity is checked, ``None``, ``uart.ODD`` or ``uart.EVEN``. - :param stop: The number of stop bits, has to be 1 for micro:bit. - :param tx: Transmitting pin. - :param rx: Receiving pin. - - 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. - - For more details see `the online documentation `_. - """ +"""Parzysta parzystość""" + +def init(baudrate: int=9600, bits: int=8, parity: Optional[int]=None, stop: int=1, tx: Optional[MicroBitDigitalPin]=None, rx: Optional[MicroBitDigitalPin]=None) -> None: + """Zainicjuj komunikację seryjną. + +Example: ``uart.init(115200, tx=pin0, rx=pin1)`` + +:param baudrate: Szybkość komunikacji. +:param bits: Rozmiar przesyłanych bajtów. micro:bit obsługuje tylko 8. +:param parity: Jak sprawdzana jest parzystość, ``None``, ``uart.ODD`` lub ``uart.EVEN``. +:param stop: Liczba bitów stopu musi wynosić 1 dla micro:bita. +:param tx: Transmitując pin. +:param rx: Odbieranie pinu. + +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. + +For more details see `the online documentation `_.""" ... def any() -> bool: - """Check if any data is waiting. + """Sprawdź, czy czekają jakieś dane. - Example: ``uart.any()`` +Example: ``uart.any()`` - :return: ``True`` if any data is waiting, else ``False``. - """ +:return: ``True`` if any data is waiting, else ``False``.""" ... -def read(nbytes: Optional[int] = None) -> Optional[bytes]: - """Read bytes. +def read(nbytes: Optional[int]=None) -> Optional[bytes]: + """Czytaj bajty. - Example: ``uart.read()`` +Example: ``uart.read()`` - :param nbytes: If ``nbytes`` is specified then read at most that many bytes, otherwise read as many bytes as possible - :return: A bytes object or ``None`` on timeout - """ +:param nbytes: Jeśli ``nbytes`` jest określony, przeczytaj co najwyżej tę liczbę bajtów, w przeciwnym razie przeczytaj jak najwięcej bajtów +:return: A bytes object or ``None`` on timeout""" ... -def readinto(buf: WriteableBuffer, nbytes: Optional[int] = None) -> Optional[int]: - """Read bytes into the ``buf``. +def readinto(buf: WriteableBuffer, nbytes: Optional[int]=None) -> Optional[int]: + """Przeczytaj bajty do ``buf``. - Example: ``uart.readinto(input_buffer)`` +Example: ``uart.readinto(input_buffer)`` - :param buf: The buffer to write to. - :param nbytes: If ``nbytes`` is specified then read at most that many bytes, otherwise read ``len(buf)`` bytes. - :return: number of bytes read and stored into ``buf`` or ``None`` on timeout. - """ +:param buf: Bufor do zapisu. +:param nbytes: Jeśli ``nbytes`` jest określony, przeczytaj co najwyżej tę liczbę bajtów, w przeciwnym razie przeczytaj ``len(buf)`` bajtów. +:return: number of bytes read and stored into ``buf`` or ``None`` on timeout.""" ... def readline() -> Optional[bytes]: - """Read a line, ending in a newline character. + """Przeczytaj wiersz kończący się znakiem nowej linii. - Example: ``uart.readline()`` +Example: ``uart.readline()`` - :return: The line read or ``None`` on timeout. The newline character is included in the returned bytes. - """ +:return: The line read or ``None`` on timeout. The newline character is included in the returned bytes.""" ... def write(buf: Union[bytes, str]) -> Optional[int]: - """Write a buffer to the bus. + """Zapisz bufor na magistrali. - Example: ``uart.write('hello world')`` +Example: ``uart.write('hello world')`` - :param buf: A bytes object or a string. - :return: The number of bytes written, or ``None`` on timeout. +:param buf: Obiekt bajtów lub łańcuch. +:return: The number of bytes written, or ``None`` on timeout. - Examples:: +Examples:: - uart.write('hello world') - uart.write(b'hello world') - uart.write(bytes([1, 2, 3])) - """ - ... + uart.write('hello world') + uart.write(b'hello world') + uart.write(bytes([1, 2, 3]))""" + ... \ No newline at end of file diff --git a/lang/pl/typeshed/stdlib/micropython.pyi b/lang/pl/typeshed/stdlib/micropython.pyi index 7a6079f..7e87975 100644 --- a/lang/pl/typeshed/stdlib/micropython.pyi +++ b/lang/pl/typeshed/stdlib/micropython.pyi @@ -1,144 +1,132 @@ -"""MicroPython internals.""" - +"""Wewnątrz MicroPythona. (microPython)""" from typing import Any, TypeVar, overload - -_T = TypeVar("_T") +_T = TypeVar('_T') def const(expr: _T) -> _T: - """Used to declare that the expression is a constant so that the compiler can - optimise it. + """Służy do zadeklarowania, że wyrażenie jest stałą tak, że kompilator może +je zoptymalizować. - The use of this function should be as follows:: +The use of this function should be as follows:: - from micropython import const - CONST_X = const(123) - CONST_Y = const(2 * CONST_X + 1) + from micropython import const + CONST_X = const(123) + CONST_Y = const(2 * CONST_X + 1) - Constants declared this way are still accessible as global variables from - outside the module they are declared in. On the other hand, if a constant - begins with an underscore then it is hidden, it is not available as a - global variable, and does not take up any memory during execution. +Constants declared this way are still accessible as global variables from +outside the module they are declared in. On the other hand, if a constant +begins with an underscore then it is hidden, it is not available as a +global variable, and does not take up any memory during execution. - :param expr: A constant expression. - """ +:param expr: Wyrażenie stałe.""" ... @overload def opt_level() -> int: - """Get the current optimisation level for the compilation of scripts. + """Uzyskaj obecny poziom optymalizacji dla kompilacji skryptów. - Example: ``micropython.opt_level()`` +Example: ``micropython.opt_level()`` - The optimisation level controls the following compilation features: +The optimisation level controls the following compilation features: - - Assertions: at level 0 assertion statements are enabled and compiled - into the bytecode; at levels 1 and higher assertions are not compiled. +- Assertions: at level 0 assertion statements are enabled and compiled + into the bytecode; at levels 1 and higher assertions are not compiled. - - Built-in ``__debug__`` variable: at level 0 this variable expands to - True; at levels 1 and higher it expands to False. +- Built-in ``__debug__`` variable: at level 0 this variable expands to + True; at levels 1 and higher it expands to False. - - Source-code line numbers: at levels 0, 1 and 2 source-code line number - are stored along with the bytecode so that exceptions can report the - line number they occurred at; at levels 3 and higher line numbers are - not stored. +- Source-code line numbers: at levels 0, 1 and 2 source-code line number + are stored along with the bytecode so that exceptions can report the + line number they occurred at; at levels 3 and higher line numbers are + not stored. - :return: An integer representing the current level. - """ +:return: An integer representing the current level.""" ... @overload def opt_level(level: int) -> None: - """Sets the optimisation level for subsequent compilation of scripts. + """Ustawia poziom optymalizacji dla późniejszej kompilacji skryptów. - Example: ``micropython.opt_level(1)`` +Example: ``micropython.opt_level(1)`` - The optimisation level controls the following compilation features: +The optimisation level controls the following compilation features: - - Assertions: at level 0 assertion statements are enabled and compiled - into the bytecode; at levels 1 and higher assertions are not compiled. +- Assertions: at level 0 assertion statements are enabled and compiled + into the bytecode; at levels 1 and higher assertions are not compiled. - - Built-in ``__debug__`` variable: at level 0 this variable expands to - True; at levels 1 and higher it expands to False. +- Built-in ``__debug__`` variable: at level 0 this variable expands to + True; at levels 1 and higher it expands to False. - - Source-code line numbers: at levels 0, 1 and 2 source-code line number - are stored along with the bytecode so that exceptions can report the - line number they occurred at; at levels 3 and higher line numbers are - not stored. +- Source-code line numbers: at levels 0, 1 and 2 source-code line number + are stored along with the bytecode so that exceptions can report the + line number they occurred at; at levels 3 and higher line numbers are + not stored. - The default optimisation level is usually level 0. +The default optimisation level is usually level 0. - :param level: An integer optimisation level. - """ +:param level: Poziom optymalizacji całkowity.""" ... -def mem_info(verbose: Any = None) -> None: - """Print information about currently used memory. +def mem_info(verbose: Any=None) -> None: + """Drukuj informacje o aktualnie używanej pamięci. - Example: ``micropython.mem_info()`` +Example: ``micropython.mem_info()`` - :param verbose: If the ``verbose`` argument is given then extra information is printed. - """ +:param verbose: Jeśli dany jest argument ``verbose``, drukowane są dodatkowe informacje.""" ... -def qstr_info(verbose: Any = None) -> None: - """Print information about currently interned strings. +def qstr_info(verbose: Any=None) -> None: + """Drukuj informacje o aktualnie internowanych łańcuchach. - Example: ``micropython.qstr_info()`` +Example: ``micropython.qstr_info()`` - :param verbose: If the ``verbose`` argument is given then extra information is printed. +:param verbose: Jeśli dany jest argument ``verbose``, drukowane są dodatkowe informacje. - The information that is printed is implementation dependent, but currently - includes the number of interned strings and the amount of RAM they use. In - verbose mode it prints out the names of all RAM-interned strings. - """ +The information that is printed is implementation dependent, but currently +includes the number of interned strings and the amount of RAM they use. In +verbose mode it prints out the names of all RAM-interned strings.""" ... def stack_use() -> int: - """Return an integer representing the current amount of stack that is being - used. + """Zwróć liczbę całkowitą reprezentującą aktualną wielkość używanego stosu - Example: ``micropython.stack_use()`` +Example: ``micropython.stack_use()`` - The absolute value of this is not particularly useful, rather it - should be used to compute differences in stack usage at different points. +The absolute value of this is not particularly useful, rather it +should be used to compute differences in stack usage at different points. - :return: An integer representing current stack use. - """ +:return: An integer representing current stack use.""" ... def heap_lock() -> None: - """Lock the heap. + """Zablokuj stos. - Example: ``micropython.heap_lock()`` +Example: ``micropython.heap_lock()`` - When locked no memory allocation can occur and a ``MemoryError`` will be - raised if any heap allocation is attempted. - """ +When locked no memory allocation can occur and a ``MemoryError`` will be +raised if any heap allocation is attempted.""" ... def heap_unlock() -> None: - """Unlock the heap. + """Odblokuj stos. - Example: ``micropython.heap_unlock()`` +Example: ``micropython.heap_unlock()`` - When locked no memory allocation can occur and a ``MemoryError`` will be - raised if any heap allocation is attempted. - """ +When locked no memory allocation can occur and a ``MemoryError`` will be +raised if any heap allocation is attempted.""" ... def kbd_intr(chr: int) -> None: - """Set the character that will raise a ``KeyboardInterrupt`` exception. + """Ustaw znak, który zgłosi wyjątek ``KeyboardInterrupt``. - Example: ``micropython.kbd_intr(-1)`` +Example: ``micropython.kbd_intr(-1)`` - :param chr: Character code to raise the interrupt or -1 to disable capture of Ctrl-C. +:param chr: Kod znaku, aby zwiększyć przerwę lub -1, aby wyłączyć przechwytywanie Ctrl-C. - By default this is set to 3 during script execution, corresponding to Ctrl-C. - Passing -1 to this function will disable capture of Ctrl-C, and passing 3 - will restore it. +By default this is set to 3 during script execution, corresponding to Ctrl-C. +Passing -1 to this function will disable capture of Ctrl-C, and passing 3 +will restore it. - This function can be used to prevent the capturing of Ctrl-C on the - incoming stream of characters that is usually used for the REPL, in case - that stream is used for other purposes. - """ - ... +This function can be used to prevent the capturing of Ctrl-C on the +incoming stream of characters that is usually used for the REPL, in case +that stream is used for other purposes.""" + ... \ No newline at end of file diff --git a/lang/pl/typeshed/stdlib/music.pyi b/lang/pl/typeshed/stdlib/music.pyi index 5f4778b..cee40a5 100644 --- a/lang/pl/typeshed/stdlib/music.pyi +++ b/lang/pl/typeshed/stdlib/music.pyi @@ -1,167 +1,128 @@ -"""Create and play melodies. -""" +"""Twórz i graj w melodie.""" from typing import Optional, Tuple, Union, List - from .microbit import MicroBitDigitalPin, pin0 - DADADADUM: Tuple[str, ...] -"""Melody: the opening to Beethoven’s 5th Symphony in C minor.""" - +"""Melodia: otwarcie 5. symfonii Beethovena w C minor""" ENTERTAINER: Tuple[str, ...] -"""Melody: the opening fragment of Scott Joplin’s Ragtime classic “The Entertainer”.""" - +"""Melodia: fragment otwierający klasyczny Scott Joplin Ragtime "The Entertainer".""" PRELUDE: Tuple[str, ...] -"""Melody: the opening of the first Prelude in C Major of J.S.Bach’s 48 Preludes and Fugues.""" - +"""Melodia: otwarcie pierwszego Preludium w C Major, 48 preludiów i Fug J.S.Bacha.""" ODE: Tuple[str, ...] -"""Melody: the “Ode to Joy” theme from Beethoven’s 9th Symphony in D minor.""" - +"""Melodia: motyw Ody do radości z 9. Symfonii Beethovena w D minor.""" NYAN: Tuple[str, ...] -"""Melody: the Nyan Cat theme (http://www.nyan.cat/). +"""Melodia: motyw Nyan Kot (http://www.nyan.cat/). The composer is unknown. This is fair use for educational porpoises (as they say in New York).""" - RINGTONE: Tuple[str, ...] -"""Melody: something that sounds like a mobile phone ringtone. +"""Melodia: coś, co brzmi jak dzwonek telefonu komórkowego. To be used to indicate an incoming message. """ - FUNK: Tuple[str, ...] -"""Melody: a funky bass line for secret agents and criminal masterminds.""" - +"""Melody: funkowa linia basu dla tajnych agentów i geniuszy kryminalnych.""" BLUES: Tuple[str, ...] -"""Melody: a boogie-woogie 12-bar blues walking bass.""" - +"""Melodia: 12-taktowy bluesowy chodzący bas w stylu boogie-woogie.""" BIRTHDAY: Tuple[str, ...] -"""Melody: “Happy Birthday to You…” +"""Melodia: "Wszystkiego najlepszego…" For copyright status see: http://www.bbc.co.uk/news/world-us-canada-34332853 """ - WEDDING: Tuple[str, ...] -"""Melody: the bridal chorus from Wagner’s opera “Lohengrin”.""" - +"""Melodia: chór panny młodej z opery Wagnera „Lohengrin”. (ślub)""" FUNERAL: Tuple[str, ...] -"""Melody: the “funeral march” otherwise known as Frédéric Chopin’s Piano Sonata No. 2 in B♭ minor, Op. 35.""" - +"""Melodia: »Marsz pogrzebowy« znany jako Sonata Fortepianowa No. 2 w B♭ minor, Op. 35 Fryderyka Chopina. (pogrzeb)""" PUNCHLINE: Tuple[str, ...] -"""Melody: a fun fragment that signifies a joke has been made.""" - +"""Melodia: zabawny fragment oznaczający, że zażartowano.""" PYTHON: Tuple[str, ...] -"""Melody: John Philip Sousa’s march “Liberty Bell” aka, the theme for “Monty Python’s Flying Circus” (after which the Python programming language is named).""" - +"""Melodia: Marsz John Philip Sousa „Liberty Bell” aka, motyw „Monty Python Flating Circus” (po którym nazwano język programowania Pythona).""" BADDY: Tuple[str, ...] -"""Melody: silent movie era entrance of a baddy.""" - +"""Melodia: wejście złego człowieka do ery kina niemego.""" CHASE: Tuple[str, ...] -"""Melody: silent movie era chase scene.""" - +"""Melodia: scena pościgu z epoki kina niemego.""" BA_DING: Tuple[str, ...] -"""Melody: a short signal to indicate something has happened.""" - +"""Melodia: krótki sygnał informujący, że coś się wydarzyło.""" WAWAWAWAA: Tuple[str, ...] -"""Melody: a very sad trombone.""" - +"""Melodia: bardzo smutny puzon.""" JUMP_UP: Tuple[str, ...] -"""Melody: for use in a game, indicating upward movement.""" - +"""Melodia: do użytku w grze, wskazujący ruch w górę.""" JUMP_DOWN: Tuple[str, ...] -"""Melody: for use in a game, indicating downward movement.""" - +"""Melodia: do użytku w grze, wskazujący ruch w górę.""" POWER_UP: Tuple[str, ...] -"""Melody: a fanfare to indicate an achievement unlocked.""" - +"""Melodia: fanfara oznaczająca odblokowanie osiągnięcia.""" POWER_DOWN: Tuple[str, ...] -"""Melody: a sad fanfare to indicate an achievement lost.""" +"""Melodia: smutna fanfara oznaczająca utracenie osiągnięcia.""" -def set_tempo(ticks: int = 4, bpm: int = 120) -> None: - """Sets the approximate tempo for playback. +def set_tempo(ticks: int=4, bpm: int=120) -> None: + """Ustawia przybliżone tempo dla odtwarzania. - Example: ``music.set_tempo(bpm=120)`` +Example: ``music.set_tempo(bpm=120)`` - :param ticks: The number of ticks constituting a beat. - :param bpm: An integer determining how many beats per minute. +:param ticks: Liczba taktów składających się na uderzenie. +:param bpm: Liczba całkowita określająca liczbę uderzeń na minutę. - Suggested default values allow the following useful behaviour: +Suggested default values allow the following useful behaviour: - - music.set_tempo() – reset the tempo to default of ticks = 4, bpm = 120 - - music.set_tempo(ticks=8) – change the “definition” of a beat - - music.set_tempo(bpm=180) – just change the tempo +- music.set_tempo() – reset the tempo to default of ticks = 4, bpm = 120 +- music.set_tempo(ticks=8) – change the “definition” of a beat +- music.set_tempo(bpm=180) – just change the tempo - To work out the length of a tick in milliseconds is very simple arithmetic: - 60000/bpm/ticks_per_beat. For the default values that’s - 60000/120/4 = 125 milliseconds or 1 beat = 500 milliseconds. - """ +To work out the length of a tick in milliseconds is very simple arithmetic: +60000/bpm/ticks_per_beat. For the default values that’s +60000/120/4 = 125 milliseconds or 1 beat = 500 milliseconds.""" ... def get_tempo() -> Tuple[int, int]: - """Gets the current tempo as a tuple of integers: ``(ticks, bpm)``. + """Pobiera bieżące tempo jako parę liczb całkowitych: ``(ticks, bpm)``. - Example: ``ticks, beats = music.get_tempo()`` +Example: ``ticks, beats = music.get_tempo()`` - :return: The temp as a tuple with two integer values, the ticks then the beats per minute. - """ +:return: The temp as a tuple with two integer values, the ticks then the beats per minute.""" ... -def play( - music: Union[str, List[str], Tuple[str, ...]], - pin: Optional[MicroBitDigitalPin] = pin0, - wait: bool = True, - loop: bool = False, -) -> None: - """Plays music. +def play(music: Union[str, List[str], Tuple[str, ...]], pin: Optional[MicroBitDigitalPin]=pin0, wait: bool=True, loop: bool=False) -> None: + """Odtwarzaj muzykę. - Example: ``music.play(music.NYAN)`` +Example: ``music.play(music.NYAN)`` - :param music: music specified in `a special notation `_ - :param pin: the output pin for use with an external speaker (default ``pin0``), ``None`` for no sound. - :param wait: If ``wait`` is set to ``True``, this function is blocking. - :param loop: If ``loop`` is set to ``True``, the tune repeats until ``stop`` is called or the blocking call is interrupted. +:param music: muzyka określona w `specjalnej notacji `_ +:param pin: pin wyjściowy do użycia z zewnętrznym głośnikiem (domyślnie ``pin0``), ``None`` dla braku dźwięku. +:param wait: Jeśli ``wait`` jest ustawiony na ``True``, ta funkcja jest blokowana. +:param loop: Jeśli ``loop`` jest ustawiony na ``True``, melodia powtarza się, aż ``stop`` jest wywołana lub połączenie blokujące zostanie przerwane. - Many built-in melodies are defined in this module. - """ +Many built-in melodies are defined in this module.""" ... -def pitch( - frequency: int, - duration: int = -1, - pin: Optional[MicroBitDigitalPin] = pin0, - wait: bool = True, -) -> None: - """Play a note. +def pitch(frequency: int, duration: int=-1, pin: Optional[MicroBitDigitalPin]=pin0, wait: bool=True) -> None: + """Zagraj nutę. - Example: ``music.pitch(185, 1000)`` +Example: ``music.pitch(185, 1000)`` - :param frequency: An integer frequency - :param duration: A millisecond duration. If negative then sound is continuous until the next call or a call to ``stop``. - :param pin: Optional output pin (default ``pin0``). - :param wait: If ``wait`` is set to ``True``, this function is blocking. +:param frequency: Częstotliwość całkowitoliczbowa +:param duration: Czas trwania w milisekundach. Jeśli ujemny, to dźwięk jest ciągły aż do następnego połączenia lub połączenia z ``stop``. +:param pin: Opcjonalny pin wyjściowy (domyślny ``pin0``). +:param wait: Jeśli ``wait`` jest ustawiony na ``True``, ta funkcja jest blokowana. - For example, if the frequency is set to 440 and the length to - 1000 then we hear a standard concert A for one second. +For example, if the frequency is set to 440 and the length to +1000 then we hear a standard concert A for one second. - You can only play one pitch on one pin at any one time. - """ +You can only play one pitch on one pin at any one time.""" ... -def stop(pin: Optional[MicroBitDigitalPin] = pin0) -> None: - """Stops all music playback on the built-in speaker and any pin outputting sound. +def stop(pin: Optional[MicroBitDigitalPin]=pin0) -> None: + """Zatrzymuje odtwarzanie muzyki na wbudowanym głośniku i jakimkolwiek pinie wyjściowym dźwięku. - Example: ``music.stop()`` +Example: ``music.stop()`` - :param pin: An optional argument can be provided to specify a pin, e.g. ``music.stop(pin1)``. - """ +:param pin: Opcjonalny argument może być podany do określenia pinu, np. ``music.stop(pin1)``.""" def reset() -> None: - """Resets ticks, bpm, duration and octave to their default values. + """Resetuje takty, bpm, czas trwania i oktawę do ich wartości domyślnych. - Example: ``music.reset()`` +Example: ``music.reset()`` - Values: - - ``ticks = 4`` - - ``bpm = 120`` - - ``duration = 4`` - - ``octave = 4`` - """ - ... +Values: +- ``ticks = 4`` +- ``bpm = 120`` +- ``duration = 4`` +- ``octave = 4``""" + ... \ No newline at end of file diff --git a/lang/pl/typeshed/stdlib/neopixel.pyi b/lang/pl/typeshed/stdlib/neopixel.pyi index 2d5a749..822e46b 100644 --- a/lang/pl/typeshed/stdlib/neopixel.pyi +++ b/lang/pl/typeshed/stdlib/neopixel.pyi @@ -1,82 +1,81 @@ -"""Individually addressable RGB and RGBW LED strips. -""" +"""Indywidualnie adresowalne paski LED RGB i RGBW.""" from .microbit import MicroBitDigitalPin from typing import Tuple class NeoPixel: - def __init__(self, pin: MicroBitDigitalPin, n: int, bpp: int = 3) -> None: - """Initialise a new strip of neopixel LEDs controlled via a pin. - Example: ``np = neopixel.NeoPixel(pin0, 8)`` + def __init__(self, pin: MicroBitDigitalPin, n: int, bpp: int=3) -> None: + """Zainicjuj nowy pasek neopikselowych diod LED sterowanych za pomocą pinu. - To support RGBW neopixels, a third argument can be passed to - ``NeoPixel`` to indicate the number of bytes per pixel (``bpp``). - For RGBW, this is is 4 rather than the default of 3 for RGB and GRB. +Example: ``np = neopixel.NeoPixel(pin0, 8)`` - Each pixel is addressed by a position (starting from 0). Neopixels are - given RGB (red, green, blue) / RGBW (red, green, blue, white) values - between 0-255 as a tuple. For example, in RGB, ``(255,255,255)`` is - white. In RGBW, ``(255,255,255,0)`` or ``(0,0,0,255)`` is white. +To support RGBW neopixels, a third argument can be passed to +``NeoPixel`` to indicate the number of bytes per pixel (``bpp``). +For RGBW, this is is 4 rather than the default of 3 for RGB and GRB. - See `the online docs `_ for warnings and other advice. +Each pixel is addressed by a position (starting from 0). Neopixels are +given RGB (red, green, blue) / RGBW (red, green, blue, white) values +between 0-255 as a tuple. For example, in RGB, ``(255,255,255)`` is +white. In RGBW, ``(255,255,255,0)`` or ``(0,0,0,255)`` is white. - :param pin: The pin controlling the neopixel strip. - :param n: The number of neopixels in the strip. - :param bpp: Bytes per pixel. For RGBW neopixel support, pass 4 rather than the default of 3 for RGB and GRB. - """ +See `the online docs `_ for warnings and other advice. + +:param pin: Pin kontrolujący pasek neopikseli. +:param n: Liczba neopikseli w pasku. +:param bpp: Bajty na piksel. W przypadku obsługi neopikseli RGBW należy przekazać 4 zamiast domyślnych 3 dla RGB i GRB.""" ... + def clear(self) -> None: - """Clear all the pixels. + """Wyczyść wszystkie piksele. - Example: ``np.clear()`` - """ +Example: ``np.clear()``""" ... + def show(self) -> None: - """Show the pixels. + """Pokaż piksele. - Example: ``np.show()`` +Example: ``np.show()`` - Must be called for any updates to become visible. - """ +Must be called for any updates to become visible.""" ... + def write(self) -> None: - """Show the pixels (micro:bit V2 only). + """Pokaż piksele (tylko micro:bit V2). - Example: ``np.write()`` +Example: ``np.write()`` - Must be called for any updates to become visible. +Must be called for any updates to become visible. - Equivalent to ``show``. - """ +Equivalent to ``show``.""" ... + def fill(self, colour: Tuple[int, ...]) -> None: - """Colour all pixels a given RGB/RGBW value (micro:bit V2 only). + """Pokoloruj wszystkie piksele określoną wartością RGB/RGBW (tylko micro:bit V2). - Example: ``np.fill((0, 0, 255))`` +Example: ``np.fill((0, 0, 255))`` - :param colour: A tuple of the same length as the number of bytes per pixel (bpp). +:param colour: Krotka o takiej samej długości jak liczba bajtów na piksel (bpp). - Use in conjunction with ``show()`` to update the neopixels. - """ +Use in conjunction with ``show()`` to update the neopixels.""" ... + def __setitem__(self, key: int, value: Tuple[int, ...]) -> None: - """Set a pixel colour. + """Ustaw kolor pikseli. - Example: ``np[0] = (255, 0, 0)`` +Example: ``np[0] = (255, 0, 0)`` + +:param key: Liczba pikseli. +:param value: Kolor""" - :param key: The pixel number. - :param value: The colour. - """ def __getitem__(self, key: int) -> Tuple[int, ...]: - """Get a pixel colour. + """Uzyskaj kolor piksela. + +Example: ``r, g, b = np[0]`` - Example: ``r, g, b = np[0]`` +:param key: Liczba pikseli. +:return: The colour tuple.""" - :param key: The pixel number. - :return: The colour tuple. - """ def __len__(self) -> int: - """Get length of this pixel strip. + """Uzyskaj długość tego paska pikseli. - Example: ``len(np)`` - """ +Example: ``len(np)``""" \ No newline at end of file diff --git a/lang/pl/typeshed/stdlib/os.pyi b/lang/pl/typeshed/stdlib/os.pyi index 2f2db77..dec924c 100644 --- a/lang/pl/typeshed/stdlib/os.pyi +++ b/lang/pl/typeshed/stdlib/os.pyi @@ -1,73 +1,63 @@ -"""Access the file system. -""" - +"""Uzyskaj dostęp do systemu plików.""" from typing import Tuple from typing import List def listdir() -> List[str]: - """List files. + """Lista plików. - Example: ``os.listdir()`` +Example: ``os.listdir()`` - :return: A list of the names of all the files contained within the local - persistent on-device file system. - """ +:return: A list of the names of all the files contained within the local +persistent on-device file system.""" ... def remove(filename: str) -> None: - """Remove (delete) a file. + """Usuń (usuń) plik. - Example: ``os.remove('data.txt')`` +Example: ``os.remove('data.txt')`` - :param filename: The file to delete. +:param filename: Plik do usunięcia. - If the file does not exist an ``OSError`` exception will occur. - """ +If the file does not exist an ``OSError`` exception will occur.""" ... def size(filename: str) -> int: - """Returns the size of a file. + """Zwraca rozmiar pliku. - Example: ``os.size('data.txt')`` +Example: ``os.size('data.txt')`` - :param filename: The file - :return: The size in bytes. +:param filename: Plik +:return: The size in bytes. - If the file does not exist an ``OSError`` exception will occur. - """ +If the file does not exist an ``OSError`` exception will occur.""" class uname_result(Tuple[str, str, str, str, str]): - """Result of ``os.uname()``""" + """Wynik ``os.uname()``""" sysname: str - """Operating system name.""" - + """Nazwa systemu operacyjnego.""" nodename: str - """Name of machine on network (implementation-defined).""" - + """Nazwa maszyny w sieci (zdefiniowana w implementacji).""" release: str - """Operating system release.""" - + """Wydanie systemu operacyjnego.""" version: str - """Operating system version.""" - + """Wersja systemu operacyjnego""" machine: str - """Hardware identifier.""" + """Identyfikator sprzętu.""" def uname() -> uname_result: - """Returns information identifying the current operating system. + """Zwraca informacje identyfikujące bieżący system operacyjny. - Example: ``os.uname()`` +Example: ``os.uname()`` - The return value is an object with five attributes: +The return value is an object with five attributes: - - ``sysname`` - operating system name - - ``nodename`` - name of machine on network (implementation-defined) - - ``release`` - operating system release - - ``version`` - operating system version - - ``machine`` - hardware identifier +- ``sysname`` - operating system name +- ``nodename`` - name of machine on network (implementation-defined) +- ``release`` - operating system release +- ``version`` - operating system version +- ``machine`` - hardware identifier - There is no underlying operating system in MicroPython. As a result the - information returned by the ``uname`` function is mostly useful for - versioning details. - """ - ... +There is no underlying operating system in MicroPython. As a result the +information returned by the ``uname`` function is mostly useful for +versioning details.""" + ... \ No newline at end of file diff --git a/lang/pl/typeshed/stdlib/radio.pyi b/lang/pl/typeshed/stdlib/radio.pyi index 8dd0267..bc27b9e 100644 --- a/lang/pl/typeshed/stdlib/radio.pyi +++ b/lang/pl/typeshed/stdlib/radio.pyi @@ -1,152 +1,130 @@ -"""Communicate between micro:bits with the built-in radio. -""" - +"""Komunikuj się pomiędzy micro:bitami za pomocą wbudowanego radia.""" from _typeshed import WriteableBuffer from typing import Optional, Tuple - RATE_1MBIT: int -"""Constant used to indicate a throughput of 1 MBit a second.""" - +"""Stała używana do wskazania przepustowości 1 MBit na sekundę.""" RATE_2MBIT: int -"""Constant used to indicate a throughput of 2 MBit a second.""" +"""Stała używana do wskazania przepustowości 2 MBit na sekundę.""" def on() -> None: - """Turns the radio on. + """Włącza radio - Example: ``radio.on()`` +Example: ``radio.on()`` - This needs to be explicitly called since the radio draws power and takes - up memory that you may otherwise need. - """ +This needs to be explicitly called since the radio draws power and takes +up memory that you may otherwise need.""" ... def off() -> None: - """Turns off the radio, saving power and memory. + """Wyłącza radio, oszczędzając energię i pamięć. - Example: ``radio.off()`` - """ +Example: ``radio.off()``""" ... -def config( - length: int = 32, - queue: int = 3, - channel: int = 7, - power: int = 6, - address: int = 0x75626974, - group: int = 0, - data_rate: int = RATE_1MBIT, -) -> None: - """Configures the radio. - - Example: ``radio.config(group=42)`` - - The default configuration is suitable for most use. - - :param length: (default=32) defines the maximum length, in bytes, of a message sent via the radio. - It can be up to 251 bytes long (254 - 3 bytes for S0, LENGTH and S1 preamble). - :param queue: (default=3) specifies the number of messages that can be stored on the incoming message queue. - If there are no spaces left on the queue for incoming messages, then the incoming message is dropped. - :param channel: (default=7) an integer value from 0 to 83 (inclusive) that defines an arbitrary "channel" to which the radio is tuned. - Messages will be sent via this channel and only messages received via this channel will be put onto the incoming message queue. Each step is 1MHz wide, based at 2400MHz. - :param power: (default=6) is an integer value from 0 to 7 (inclusive) to indicate the strength of signal used when broadcasting a message. - The higher the value the stronger the signal, but the more power is consumed by the device. The numbering translates to positions in the following list of dBm (decibel milliwatt) values: -30, -20, -16, -12, -8, -4, 0, 4. - :param address: (default=0x75626974) an arbitrary name, expressed as a 32-bit address, that's used to filter incoming packets at the hardware level, keeping only those that match the address you set. - The default used by other micro:bit related platforms is the default setting used here. - :param group: (default=0) an 8-bit value (0-255) used with the ``address`` when filtering messages. - Conceptually, "address" is like a house/office address and "group" is like the person at that address to which you want to send your message. - :param data_rate: (default=``radio.RATE_1MBIT``) indicates the speed at which data throughput takes place. - Can be one of the following constants defined in the ``radio`` module: ``RATE_250KBIT``, ``RATE_1MBIT`` or ``RATE_2MBIT``. - - If ``config`` is not called then the defaults described above are assumed. - """ +def config(length: int=32, queue: int=3, channel: int=7, power: int=6, address: int=1969383796, group: int=0, data_rate: int=RATE_1MBIT) -> None: + """Konfiguruje radio. + +Example: ``radio.config(group=42)`` + +The default configuration is suitable for most use. + +:param length: (default=32) definiuje maksymalną długość w bajtach wiadomości wysyłanej przez radio. +Może mieć długość do 251 bajtów (254 - 3 bajty dla S0, LENGTH i S1). +:param queue: (default=3) określa liczbę wiadomości, które mogą być przechowywane w kolejce przychodzących wiadomości. +Jeśli w kolejce na wiadomości przychodzące nie ma już wolnych miejsc, wiadomość przychodząca jest odrzucana. +:param channel: (default=7) wartość całkowita od 0 do 83 (włącznie), która definiuje dowolny „kanał”, do którego dostrojone jest radio. +Wiadomości będą wysyłane za pośrednictwem tego kanału i tylko wiadomości otrzymane za pośrednictwem tego kanału zostaną umieszczone w kolejce wiadomości przychodzących. Każdy stopień ma szerokość 1 MHz w oparciu o częstotliwość 2400 MHz. +:param power: (default=6) jest liczb całkowitą od 0 do 7 (włącznie) do oznaczenia siły sygnału używanego podczas nadawania wiadomości. +Im wyższa wartość, tym silniejszy jest sygnał, ale tym większa moc jest zużywana przez urządzenie. Numeracja przekłada się na pozycje w następującym wykazie wartości dBm (decybel miliwat): -30, -20, -16, -12, -8, -4, 0, 4. +:param address: (default=0x75626974) dowolna nazwa wyrażona jako 32-bitowy adres, używana do filtrowania przychodzących pakietów na poziomie sprzętowym, zatrzymując tylko te, które odpowiadają ustawionemu adresowi. +Domyślnym ustawieniem używanym przez inne platformy powiązane z micro:bitem jest ustawienie domyślne używane tutaj. +:param group: (default=0) 8-bitowa wartość (0-255) używana wraz z ``address`` podczas filtrowania wiadomości. +Koncepcyjnie, "adres" jest jak adres domu/biura, a "grupa" jest jak osoba pod tym adresem, na który chcesz wysłać swoją wiadomość. +:param data_rate: (default=``radio.RATE_1MBIT``) wskazuje prędkość, z jaką odbywa się przesyłanie danych. +Może być jedną z następujących stałych zdefiniowanych w module ``radio``:``RATE_250KBIT``, ``RATE_1MBIT`` lub ``RATE_2MBIT``. + +If ``config`` is not called then the defaults described above are assumed.""" ... def reset() -> None: - """Reset the settings to their default values. + """Resetuj ustawienia do ich wartości domyślnych. - Example: ``radio.reset()`` +Example: ``radio.reset()`` - The defaults as as per the ``config`` function above. - """ +The defaults as as per the ``config`` function above.""" ... def send_bytes(message: bytes) -> None: - """Sends a message containing bytes. + """Wysyła wiadomość zawierającą bajty. - Example: ``radio.send_bytes(b'hello')`` +Example: ``radio.send_bytes(b'hello')`` - :param message: The bytes to send. - """ +:param message: Bajty do wysłania.""" ... def receive_bytes() -> Optional[bytes]: - """Receive the next incoming message on the message queue. + """Otrzymuj następną przychodzącą wiadomość w kolejce wiadomości. - Example: ``radio.receive_bytes()`` +Example: ``radio.receive_bytes()`` - :return: The message bytes if any, otherwise ``None``. - """ +:return: The message bytes if any, otherwise ``None``.""" ... def receive_bytes_into(buffer: WriteableBuffer) -> Optional[int]: - """Copy the next incoming message on the message queue into a buffer. + """Skopiuj następną wiadomość przychodzącą do kolejki wiadomości w buforze. - Example: ``radio.receive_bytes_info(buffer)`` +Example: ``radio.receive_bytes_info(buffer)`` - :param buffer: The target buffer. The message is truncated if larger than the buffer. - :return: ``None`` if there are no pending messages, otherwise it returns the length of the message (which might be more than the length of the buffer). - """ +:param buffer: Bufor docelowy. Wiadomość jest obcinana, jeśli jest większa niż bufor. +:return: ``None`` if there are no pending messages, otherwise it returns the length of the message (which might be more than the length of the buffer).""" ... def send(message: str) -> None: - """Sends a message string. + """Wysyła łańcuch wiadomości. - Example: ``radio.send('hello')`` +Example: ``radio.send('hello')`` - This is the equivalent of ``radio.send_bytes(bytes(message, 'utf8'))`` but with ``b'\x01\x00\x01'`` - prepended to the front (to make it compatible with other platforms that target the micro:bit). +This is the equivalent of ``radio.send_bytes(bytes(message, 'utf8'))`` but with ``b'\x01\x00\x01'`` +prepended to the front (to make it compatible with other platforms that target the micro:bit). - :param message: The string to send. - """ +:param message: Łańcuch do wysłania.""" ... def receive() -> Optional[str]: - """Works in exactly the same way as ``receive_bytes`` but returns whatever was sent. + """Działa dokładnie w taki sam sposób, jak ``receive_bytes``, ale zwraca cokolwiek zostało wysłane. (odbierz) - Example: ``radio.receive()`` +Example: ``radio.receive()`` - Equivalent to ``str(receive_bytes(), 'utf8')`` but with a check that the the first - three bytes are ``b'\x01\x00\x01'`` (to make it compatible with other platforms that - may target the micro:bit). +Equivalent to ``str(receive_bytes(), 'utf8')`` but with a check that the the first +three bytes are ``b'\x01\x00\x01'`` (to make it compatible with other platforms that +may target the micro:bit). - :return: The message with the prepended bytes stripped and converted to a string. +:return: The message with the prepended bytes stripped and converted to a string. - A ``ValueError`` exception is raised if conversion to string fails. - """ +A ``ValueError`` exception is raised if conversion to string fails.""" ... def receive_full() -> Optional[Tuple[bytes, int, int]]: - """Returns a tuple containing three values representing the next incoming message on the message queue. + """Zwraca krotkę zawierającą trzy wartości reprezentujące następną wiadomość przychodzącą do kolejki wiadomości. - Example: ``radio.receive_full()`` +Example: ``radio.receive_full()`` - If there are no pending messages then ``None`` is returned. +If there are no pending messages then ``None`` is returned. - The three values in the tuple represent: +The three values in the tuple represent: - - the next incoming message on the message queue as bytes. - - the RSSI (signal strength): a value between 0 (strongest) and -255 (weakest) as measured in dBm. - - a microsecond timestamp: the value returned by ``time.ticks_us()`` when the message was received. +- the next incoming message on the message queue as bytes. +- the RSSI (signal strength): a value between 0 (strongest) and -255 (weakest) as measured in dBm. +- a microsecond timestamp: the value returned by ``time.ticks_us()`` when the message was received. - For example:: +For example:: - details = radio.receive_full() - if details: - msg, rssi, timestamp = details + details = radio.receive_full() + if details: + msg, rssi, timestamp = details - This function is useful for providing information needed for triangulation - and/or trilateration with other micro:bit devices. +This function is useful for providing information needed for triangulation +and/or trilateration with other micro:bit devices. - :return: ``None`` if there is no message, otherwise a tuple of length three with the bytes, strength and timestamp values. - """ - ... +:return: ``None`` if there is no message, otherwise a tuple of length three with the bytes, strength and timestamp values.""" + ... \ No newline at end of file diff --git a/lang/pl/typeshed/stdlib/random.pyi b/lang/pl/typeshed/stdlib/random.pyi index a2c2ef3..c6431c6 100644 --- a/lang/pl/typeshed/stdlib/random.pyi +++ b/lang/pl/typeshed/stdlib/random.pyi @@ -1,93 +1,81 @@ -"""Generate random numbers. -""" +"""Generuj liczb losowe. (losowy)""" from typing import TypeVar, Sequence, Union, overload def getrandbits(n: int) -> int: - """Generate an integer with ``n`` random bits. + """Wygeneruj liczbę całkowitą z ``n`` losowymi bitami. - Example: ``random.getrandbits(1)`` +Example: ``random.getrandbits(1)`` - :param n: A value between 1-30 (inclusive). - """ +:param n: Wartość między 1–30 (włącznie).""" ... def seed(n: int) -> None: - """Initialize the random number generator. + """Zainicjuj generator liczb losowych. - Example: ``random.seed(0)`` +Example: ``random.seed(0)`` - :param n: The integer seed +:param n: Całkowity zarodek - This will give you reproducibly deterministic randomness from a given starting - state (``n``). - """ +This will give you reproducibly deterministic randomness from a given starting +state (``n``).""" ... def randint(a: int, b: int) -> int: - """Choose a random integer between ``a`` and ``b`` inclusive. + """Wybierz losową liczbę całkowitą pomiędzy ``a`` i ``b`` włącznie. - Example: ``random.randint(0, 9)`` +Example: ``random.randint(0, 9)`` - :param a: Start value for the range (inclusive) - :param b: End value for the range (inclusive) +:param a: Wartość początkowa dla zakresu (włącznie) +:param b: Wartość końcowa dla zakresu (wyłącznie) - Alias for ``randrange(a, b + 1)``. - """ +Alias for ``randrange(a, b + 1)``.""" ... @overload def randrange(stop: int) -> int: - """Choose a randomly selected integer between zero and up to (but not - including) ``stop``. + """Wybierz losowo wybraną liczbę całkowitą między zero aż do (ale nie +włącznie) ``stop``. - Example: ``random.randrange(10)`` +Example: ``random.randrange(10)`` - :param stop: End value for the range (exclusive) - """ +:param stop: Wartość końcowa zakresu (wyłącznie)""" ... @overload -def randrange(start: int, stop: int, step: int = 1) -> int: - """ - Choose a randomly selected element from ``range(start, stop, step)``. +def randrange(start: int, stop: int, step: int=1) -> int: + """Wybierz losowo wybrany element z ``range(start, stop, step)``. - Example: ``random.randrange(0, 10)`` +Example: ``random.randrange(0, 10)`` - :param start: The start of the range (inclusive) - :param stop: The end of the range (exclusive) - :param step: The step. - """ +:param start: Początek zakresu (włącznie) +:param stop: Koniec zakresu (wyłącznie) +:param step: Krok""" ... - -_T = TypeVar("_T") +_T = TypeVar('_T') def choice(seq: Sequence[_T]) -> _T: - """Choose a random element from the non-empty sequence ``seq``. + """Wybierz losowy element z niepustego cigu ``seq``. - Example: ``random.choice([Image.HAPPY, Image.SAD])`` +Example: ``random.choice([Image.HAPPY, Image.SAD])`` - :param seq: A sequence. +:param seq: Cig. - If ``seq`` is empty, raises ``IndexError``. - """ +If ``seq`` is empty, raises ``IndexError``.""" ... def random() -> float: - """Generate a random floating point number in the range [0.0, 1.0). + """Wygeneruj losową liczbę zmiennopozycyjną w zakresie [0.0, 1.0). - Example: ``random.random()`` +Example: ``random.random()`` - :return: The random floating point number - """ +:return: The random floating point number""" ... def uniform(a: float, b: float) -> float: - """ - Return a random floating point number between ``a`` and ``b`` inclusive. + """Zwróć losową liczbę zmiennopozycyjnłą między ``a`` i ``b``. - Example: ``random.uniform(0, 9)`` +Example: ``random.uniform(0, 9)`` - :param a: Start value for the range (inclusive) - :param b: End value for the range (inclusive) - """ - ... +:param a: Wartość początkowa dla zakresu (włącznie) +:param b: Wartość końcowa dla zakresu (wyłącznie)""" + ... \ No newline at end of file diff --git a/lang/pl/typeshed/stdlib/speech.pyi b/lang/pl/typeshed/stdlib/speech.pyi index 349d188..cf7dced 100644 --- a/lang/pl/typeshed/stdlib/speech.pyi +++ b/lang/pl/typeshed/stdlib/speech.pyi @@ -1,106 +1,79 @@ -"""Make the micro:bit talk, sing and make other speech like sounds. -""" - +"""Spraw, by micro:bit mówił, śpiewał i tworzył inne dźwięki podobne do mowy.""" from typing import Optional from .microbit import MicroBitDigitalPin, pin0 def translate(words: str) -> str: - """Translate English words to phonemes. + """Tłumacz angielskie słowa na fonemy. - Example: ``speech.translate('hello world')`` +Example: ``speech.translate('hello world')`` - :param words: A string of English words. - :return: A string containing a best guess at the appropriate phonemes to pronounce. - The output is generated from this `text to phoneme translation table `_. +:param words: Łańcuch słów angielskich. +:return: A string containing a best guess at the appropriate phonemes to pronounce. +The output is generated from this `text to phoneme translation table `_. - This function should be used to generate a first approximation of phonemes - that can be further hand-edited to improve accuracy, inflection and - emphasis. +This function should be used to generate a first approximation of phonemes +that can be further hand-edited to improve accuracy, inflection and +emphasis. - See `the online documentation `_ for detailed information. - """ +See `the online documentation `_ for detailed information.""" ... -def pronounce( - phonemes: str, - pitch: int = 64, - speed: int = 72, - mouth: int = 128, - throat: int = 128, - pin: Optional[MicroBitDigitalPin] = pin0, -) -> None: - """Pronounce phonemes. - - Example: ``speech.pronounce(' /HEHLOW WERLD')`` - - :param phonemes: The string of phonemes to pronounce - :param pitch: A number representing the pitch of the voice - :param speed: A number representing the speed of the voice - :param mouth: A number representing the mouth of the voice - :param throat: A number representing the throat of the voice - :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. - If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. - - Override the optional pitch, speed, mouth and throat settings to change the - timbre (quality) of the voice. - - See `the online documentation `_ for detailed information. - """ - ... +def pronounce(phonemes: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: Optional[MicroBitDigitalPin]=pin0) -> None: + """Wymów fonemy. + +Example: ``speech.pronounce(' /HEHLOW WERLD')`` + +:param phonemes: Łańcuch fonemów do wymówienia +:param pitch: Liczba reprezentująca wysokość głosu +:param speed: Liczba reprezentująca szybkość głosu +:param mouth: Liczba reprezentująca usta głosu +:param throat: Liczba reprezentująca gardło głosu +:param pin: Opcjonalny argument do określenia pinu wyjściowego może być użyty do nadpisania domyślnej wartości ``pin0``. +Jeśli nie chcemy, aby jakikolwiek dźwięk wydobywał się z pinów, możemy użyć ``pin=None``. Tylko micro:bit V2. -def say( - words: str, - pitch: int = 64, - speed: int = 72, - mouth: int = 128, - throat: int = 128, - pin: MicroBitDigitalPin = pin0, -) -> None: - """Say English words. - - Example: ``speech.say('hello world')`` - - :param words: The string of words to say. - :param pitch: A number representing the pitch of the voice - :param speed: A number representing the speed of the voice - :param mouth: A number representing the mouth of the voice - :param throat: A number representing the throat of the voice - :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. - If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. - - The result is semi-accurate for English. Override the optional pitch, speed, - mouth and throat settings to change the timbre (quality) of the voice. - - This is a short-hand equivalent of: - ``speech.pronounce(speech.translate(words))`` - - See `the online documentation `_ for detailed information. - """ +Override the optional pitch, speed, mouth and throat settings to change the +timbre (quality) of the voice. + +See `the online documentation `_ for detailed information.""" ... -def sing( - phonemes: str, - pitch: int = 64, - speed: int = 72, - mouth: int = 128, - throat: int = 128, - pin: MicroBitDigitalPin = pin0, -) -> None: - """Sing phonemes. - - Example: ``speech.sing(' /HEHLOW WERLD')`` - - :param phonemes: The string of words to sing. - :param pitch: A number representing the pitch of the voice - :param speed: A number representing the speed of the voice - :param mouth: A number representing the mouth of the voice - :param throat: A number representing the throat of the voice - :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. - If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. - - Override the optional pitch, speed, mouth and throat settings to change - the timbre (quality) of the voice. - - See `the online documentation `_ for detailed information. - """ +def say(words: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: MicroBitDigitalPin=pin0) -> None: + """Powiedz angielskie słowa. + +Example: ``speech.say('hello world')`` + +:param words: Łańcuch słów do powiedzenia. +:param pitch: Liczba reprezentująca wysokość głosu +:param speed: Liczba reprezentująca szybkość głosu +:param mouth: Liczba reprezentująca usta głosu +:param throat: Liczba reprezentująca gardło głosu +:param pin: Opcjonalny argument do określenia pinu wyjściowego może być użyty do nadpisania domyślnej wartości ``pin0``. +Jeśli nie chcemy, aby jakikolwiek dźwięk wydobywał się z pinów, możemy użyć ``pin=None``. Tylko micro:bit V2. + +The result is semi-accurate for English. Override the optional pitch, speed, +mouth and throat settings to change the timbre (quality) of the voice. + +This is a short-hand equivalent of: +``speech.pronounce(speech.translate(words))`` + +See `the online documentation `_ for detailed information.""" ... + +def sing(phonemes: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: MicroBitDigitalPin=pin0) -> None: + """Zaśpiewaj fonemy. + +Example: ``speech.sing(' /HEHLOW WERLD')`` + +:param phonemes: Łańcuch słów do zaśpiewania. +:param pitch: Liczba reprezentująca wysokość głosu +:param speed: Liczba reprezentująca szybkość głosu +:param mouth: Liczba reprezentująca usta głosu +:param throat: Liczba reprezentująca gardło głosu +:param pin: Opcjonalny argument do określenia pinu wyjściowego może być użyty do nadpisania domyślnej wartości ``pin0``. +Jeśli nie chcemy, aby jakikolwiek dźwięk wydobywał się z pinów, możemy użyć ``pin=None``. Tylko micro:bit V2. + +Override the optional pitch, speed, mouth and throat settings to change +the timbre (quality) of the voice. + +See `the online documentation `_ for detailed information.""" + ... \ No newline at end of file diff --git a/lang/pl/typeshed/stdlib/struct.pyi b/lang/pl/typeshed/stdlib/struct.pyi index 53b3e0b..ea3d443 100644 --- a/lang/pl/typeshed/stdlib/struct.pyi +++ b/lang/pl/typeshed/stdlib/struct.pyi @@ -1,65 +1,56 @@ -"""Pack and unpack primitive data types. -""" - +"""Pakuj i rozpakowuj prymitywne typy danych.""" from _typeshed import ReadableBuffer, WriteableBuffer from typing import Any, Tuple, Union def calcsize(fmt: str) -> int: - """Get the number of bytes needed to store the given ``fmt``. + """Uzyskaj liczbę bajtów potrzebnych do przechowywania podanego ``fmt``. - Example: ``struct.calcsize('hf')`` +Example: ``struct.calcsize('hf')`` - :param fmt: A format string. - :return The number of bytes needed to store such a value. - """ +:param fmt: Łańcuch formatu. +:return The number of bytes needed to store such a value.""" ... def pack(fmt: str, v1: Any, *vn: Any) -> bytes: - """Pack values according to a format string. + """Upakuj wartości zgodnie z łńcuchem formatu. - Example: ``struct.pack('hf', 1, 3.1415)`` +Example: ``struct.pack('hf', 1, 3.1415)`` - :param fmt: The format string. - :param v1: The first value. - :param *vn: The remaining values. - :return A bytes object encoding the values. - """ +:param fmt: Łańcuch formatu. +:param v1: Pierwsza wartość. +:param *vn: Pozostałe wartości. +:return A bytes object encoding the values.""" ... -def pack_into( - fmt: str, buffer: WriteableBuffer, offset: int, v1: Any, *vn: Any -) -> None: - """Pack values according to a format string. +def pack_into(fmt: str, buffer: WriteableBuffer, offset: int, v1: Any, *vn: Any) -> None: + """Upakuj wartości zgodnie z łńcuchem formatu. - Example: ``struct.pack_info('hf', buffer, 1, 3.1415)`` +Example: ``struct.pack_info('hf', buffer, 1, 3.1415)`` - :param fmt: The format string. - :param buffer: The target buffer to write into. - :param offset: The offset into the buffer. May be negative to count from the end of the buffer. - :param v1: The first value. - :param *vn: The remaining values. - """ +:param fmt: Łańcuch formatu. +:param buffer: Bufor docelowy do zapisu. +:param offset: Przesunięcie do bufora. Wartość ujemna może być liczona od końca bufora. +:param v1: (w1) Pierwsza wartość. +:param *vn: Pozostałe wartości.""" ... def unpack(fmt: str, data: ReadableBuffer) -> Tuple[Any, ...]: - """Unpack data according to a format string. + """Rozpakuj dane zgodnie z łańcuchem formatu. - Example: ``v1, v2 = struct.unpack('hf', buffer)`` +Example: ``v1, v2 = struct.unpack('hf', buffer)`` - :param fmt: The format string. - :param data: The data. - :return: A tuple of the unpacked values. - """ +:param fmt: Łańcuch formatu. +:param data: Dane +:return: A tuple of the unpacked values.""" ... -def unpack_from(fmt: str, buffer: ReadableBuffer, offset: int = 0) -> Tuple: - """Unpack data from a buffer according to a format string. +def unpack_from(fmt: str, buffer: ReadableBuffer, offset: int=0) -> Tuple: + """Rozpakuj dane z buforu zgodnie z łańcuchem formatu. - Example: ``v1, v2 = struct.unpack_from('hf', buffer)`` +Example: ``v1, v2 = struct.unpack_from('hf', buffer)`` - :param fmt: The format string. - :param buffer: The source buffer to read from. - :param offset: The offset into the buffer. May be negative to count from the end of the buffer. - :return: A tuple of the unpacked values. - """ - ... +:param fmt: Łańcuch formatu. +:param buffer: Bufor źródłowy do odczytu. +:param offset: Przesunięcie do bufora. Wartość ujemna może być liczona od końca bufora. +:return: A tuple of the unpacked values.""" + ... \ No newline at end of file diff --git a/lang/pl/typeshed/stdlib/sys.pyi b/lang/pl/typeshed/stdlib/sys.pyi index 320bac9..c0683cb 100644 --- a/lang/pl/typeshed/stdlib/sys.pyi +++ b/lang/pl/typeshed/stdlib/sys.pyi @@ -1,43 +1,36 @@ -"""System specific functions""" - +"""Funkcje specyficzne dla systemu""" from typing import Any, Dict, List, NoReturn, TextIO, Tuple -def exit(retval: object = ...) -> NoReturn: - """Terminate current program with a given exit code. +def exit(retval: object=...) -> NoReturn: + """Zakończ bieżący program z podanym kodem wyjścia. - Example: ``sys.exit(1)`` +Example: ``sys.exit(1)`` - This function raises a ``SystemExit`` exception. If an argument is given, its - value given as an argument to ``SystemExit``. +This function raises a ``SystemExit`` exception. If an argument is given, its +value given as an argument to ``SystemExit``. - :param retval: The exit code or message. - """ +:param retval: Kod lub wiadomość wyjściowa.""" ... def print_exception(exc: Exception) -> None: - """ - Print an exception with a traceback. - - Example: ``sys.print_exception(e)`` + """Wydrukuj wyjątek ze śledzeniem. - :param exc: The exception to print +Example: ``sys.print_exception(e)`` - This is simplified version of a function which appears in the - ``traceback`` module in CPython. - """ +:param exc: Wyjątek do wydrukowania +This is simplified version of a function which appears in the +``traceback`` module in CPython.""" argv: List[str] -"""A mutable list of arguments the current program was started with.""" - +"""Zmienna lista argumentów, od których uruchomiono bieżący program.""" byteorder: str -"""The byte order of the system (``"little"`` or ``"big"``).""" +"""Kolejność bajtów systemu (``"little"`` lub ``"big"``).""" class _implementation: name: str version: Tuple[int, int, int] - implementation: _implementation -"""Object with information about the current Python implementation. +"""Obiekt z informacjami o bieżącej implementacji Pythona. For MicroPython, it has following attributes: @@ -51,13 +44,12 @@ minimal ports). CPython mandates more attributes for this object, but the actual useful bare minimum is implemented in MicroPython. """ - maxsize: int """ -Maximum value which a native integer type can hold on the current platform, -or maximum value representable by MicroPython integer type, if it's smaller -than platform max value (that is the case for MicroPython ports without -long int support). +Maksymalna wartość, jaką może przechowywać natywny typ całkowity na bieżącej platformie, +lub maksymalna wartość reprezentowana przez typ całkowity MicroPythona, jeśli jest mniejsza +niż maksymalna wartość platformy (tak jest w przypadku portów MicroPython bez +wsparcia long int). This attribute is useful for detecting "bitness" of a platform (32-bit vs 64-bit, etc.). It's recommended to not compare this attribute to some @@ -77,17 +69,14 @@ value directly, but instead count number of bits in it:: # (e.g. 31) due to peculiarities described above, so use "> 16", # "> 32", "> 64" style of comparisons. """ - modules: Dict[str, Any] -"""Dictionary of loaded modules. +"""Słownik załadowanych modułów. On some ports, it may not include builtin modules.""" - path: List[str] -"""A mutable list of directories to search for imported modules.""" - +"""Zmienna lista katalogów do wyszukiwania importowanych modułów.""" platform: str -"""The platform that MicroPython is running on. +"""Platforma na której działa MicroPython. For OS/RTOS ports, this is usually an identifier of the OS, e.g. ``"linux"``. For baremetal ports it is an identifier of a board, e.g. ``"pyboard"`` for @@ -97,13 +86,11 @@ distinguish one board from another. If you need to check whether your program runs on MicroPython (vs other Python implementation), use ``sys.implementation`` instead. """ - version: str -"""Python language version that this implementation conforms to, as a string.""" - +"""Wersja Pythona, z którą ta implementacja jest zgodna, jako łańcuch.""" version_info: Tuple[int, int, int] -"""Python language version that this implementation conforms to, as a tuple of ints. +"""Wersja Pythona, z którą ta implementacja jest zgodna, jako krotka typu int. Only the first three version numbers (major, minor, micro) are supported and they can be referenced only by index, not by name. -""" +""" \ No newline at end of file diff --git a/lang/pl/typeshed/stdlib/time.pyi b/lang/pl/typeshed/stdlib/time.pyi index 598c483..cc4cf6e 100644 --- a/lang/pl/typeshed/stdlib/time.pyi +++ b/lang/pl/typeshed/stdlib/time.pyi @@ -1,132 +1,117 @@ -"""Measure time and add delays to programs. -""" - +"""Zmierz czas i dodaj opóźnienia do programów.""" from typing import Union def sleep(seconds: Union[int, float]) -> None: - """ - Delay a number of seconds. + """Opóźnij kilka sekund. - Example: ``time.sleep(1)`` +Example: ``time.sleep(1)`` - :param seconds: The number of seconds to sleep for. - Use a floating-point number to sleep for a fractional number of seconds. - """ +:param seconds: Liczba sekund snu. +Użyj liczby zmiennopozycyjnej, aby spać przez ułamkową część sekund.""" ... def sleep_ms(ms: int) -> None: - """ - Delay for given number of milliseconds. + """Opóźnij o podaną liczbę milisekund. - Example: ``time.sleep_ms(1_000_000)`` +Example: ``time.sleep_ms(1_000_000)`` - :param ms: The number of milliseconds delay (>= 0). - """ +:param ms: Liczba milisekund opóźnienia (>= 0).""" ... def sleep_us(us: int) -> None: - """ - Delay for given number of microseconds. + """Opóźnij o podaną liczbę milisekund. - Example: ``time.sleep_us(1000)`` +Example: ``time.sleep_us(1000)`` - :param us: The number of microseconds delay (>= 0). - """ +:param us: Liczba milisekund opóźnienia (>= 0).""" ... def ticks_ms() -> int: - """ - Get an increasing, millisecond counter with an arbitrary reference point, - that wraps around after some value. + """Uzyskaj rosnący licznik milisekundowy z dowolnym punktem odniesienia, +który zawija się po pewnej wartości. - Example: ``time.ticks_ms()`` +Example: ``time.ticks_ms()`` - :return: The counter value in milliseconds. - """ +:return: The counter value in milliseconds.""" ... def ticks_us() -> int: - """ - Get an increasing, microsecond counter with an arbitrary reference point, - that wraps around after some value. + """Uzyskaj rosnący licznik milisekundowy z dowolnym punktem odniesienia, +który zawija się po pewnej wartości. - Example: ``time.ticks_us()`` +Example: ``time.ticks_us()`` - :return: The counter value in microseconds. - """ +:return: The counter value in microseconds.""" ... def ticks_add(ticks: int, delta: int) -> int: - """ - Offset ticks value by a given number, which can be either positive or - negative. + """Przesunięcie zaznacza wartość o podaną liczbę, która może być dodatnia lub +negatywny. +. - Example: ``time.ticks_add(time.ticks_ms(), 200)`` +Example: ``time.ticks_add(time.ticks_ms(), 200)`` - Given a ticks value, this function allows to calculate ticks - value delta ticks before or after it, following modular-arithmetic - definition of tick values. +Given a ticks value, this function allows to calculate ticks +value delta ticks before or after it, following modular-arithmetic +definition of tick values. - :param ticks: A ticks value - :param delta: An integer offset +:param ticks: Wartość ticków +:param delta: Przesunięcie o liczbę całkowitą - Example:: +Example:: - # Find out what ticks value there was 100ms ago - print(ticks_add(time.ticks_ms(), -100)) + # Find out what ticks value there was 100ms ago + print(ticks_add(time.ticks_ms(), -100)) - # Calculate deadline for operation and test for it - deadline = ticks_add(time.ticks_ms(), 200) - while ticks_diff(deadline, time.ticks_ms()) > 0: - do_a_little_of_something() + # Calculate deadline for operation and test for it + deadline = ticks_add(time.ticks_ms(), 200) + while ticks_diff(deadline, time.ticks_ms()) > 0: + do_a_little_of_something() - # Find out TICKS_MAX used by this port - print(ticks_add(0, -1)) - """ + # Find out TICKS_MAX used by this port + print(ticks_add(0, -1))""" ... def ticks_diff(ticks1: int, ticks2: int) -> int: - """ - Measure ticks difference between values returned from - ``time.ticks_ms()`` or ``ticks_us()``, as a signed value - which may wrap around. - - Example: ``time.ticks_diff(scheduled_time, now)`` - - :param ticks1: The value to subtract from - :param ticks2: The value to subtract - - The argument order is the same as for subtraction operator, - ``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. - - ``ticks_diff()`` is designed to accommodate various usage - patterns, among them: - - Polling with timeout. In this case, the order of events is known, and you - will deal only with positive results of :func:`time.ticks_diff()`:: - - # Wait for GPIO pin to be asserted, but at most 500us - start = time.ticks_us() - while pin.value() == 0: - if time.ticks_diff(time.ticks_us(), start) > 500: - raise TimeoutError - - - Scheduling events. In this case, :func:`time.ticks_diff()` result may be - negative if an event is overdue:: - - # This code snippet is not optimized - now = time.ticks_ms() - scheduled_time = task.scheduled_time() - if ticks_diff(scheduled_time, now) > 0: - print("Too early, let's nap") - sleep_ms(ticks_diff(scheduled_time, now)) - task.run() - elif ticks_diff(scheduled_time, now) == 0: - print("Right at time!") - task.run() - elif ticks_diff(scheduled_time, now) < 0: - print("Oops, running late, tell task to run faster!") - task.run(run_faster=True) - """ - ... + """Zmierz różnicę ticków między wartościami zwróconymi z +``time.ticks_ms()`` lub ``ticks_us()``, jako wartość ze znakiem, +która może się zawijać. + +Example: ``time.ticks_diff(scheduled_time, now)`` + +:param ticks1: Wartość do odejmowania od +:param ticks2: Wartość do odejmowania + +The argument order is the same as for subtraction operator, +``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. + +``ticks_diff()`` is designed to accommodate various usage +patterns, among them: + +Polling with timeout. In this case, the order of events is known, and you +will deal only with positive results of :func:`time.ticks_diff()`:: + + # Wait for GPIO pin to be asserted, but at most 500us + start = time.ticks_us() + while pin.value() == 0: + if time.ticks_diff(time.ticks_us(), start) > 500: + raise TimeoutError + + +Scheduling events. In this case, :func:`time.ticks_diff()` result may be +negative if an event is overdue:: + + # This code snippet is not optimized + now = time.ticks_ms() + scheduled_time = task.scheduled_time() + if ticks_diff(scheduled_time, now) > 0: + print("Too early, let's nap") + sleep_ms(ticks_diff(scheduled_time, now)) + task.run() + elif ticks_diff(scheduled_time, now) == 0: + print("Right at time!") + task.run() + elif ticks_diff(scheduled_time, now) < 0: + print("Oops, running late, tell task to run faster!") + task.run(run_faster=True)""" + ... \ No newline at end of file diff --git a/lang/zh-cn/typeshed/stdlib/gc.pyi b/lang/zh-cn/typeshed/stdlib/gc.pyi index 1370abf..ca5a757 100644 --- a/lang/zh-cn/typeshed/stdlib/gc.pyi +++ b/lang/zh-cn/typeshed/stdlib/gc.pyi @@ -1,73 +1,68 @@ -"""Control the garbage collector""" - +"""控制垃圾回收器 (垃圾回收(gc))""" from typing import overload def enable() -> None: - """Enable automatic garbage collection.""" + """启用自动垃圾回收机制。""" ... def disable() -> None: - """Disable automatic garbage collection. + """禁用自动垃圾回收机制。 - Heap memory can still be allocated, - and garbage collection can still be initiated manually using ``gc.collect``.""" +Heap memory can still be allocated, +and garbage collection can still be initiated manually using ``gc.collect``.""" def collect() -> None: - """Run a garbage collection.""" + """执行一次垃圾回收。""" ... def mem_alloc() -> int: - """Get the number of bytes of heap RAM that are allocated. + """获取分配的堆内存的字节数。 - :return: The number of bytes allocated. +:return: The number of bytes allocated. - This function is MicroPython extension. - """ +This function is MicroPython extension.""" ... def mem_free() -> int: - """Get the number of bytes of available heap RAM, or -1 if this amount is not known. + """获取可用堆内存的字节数,如果此数量未知,则返回值为 -1。 - :return: The number of bytes free. +:return: The number of bytes free. - This function is MicroPython extension. - """ +This function is MicroPython extension.""" ... @overload def threshold() -> int: - """Query the additional GC allocation threshold. + """查询额外的垃圾回收分配阈值。 - :return: The GC allocation threshold. +:return: The GC allocation threshold. - This function is a MicroPython extension. CPython has a similar - function - ``set_threshold()``, but due to different GC - implementations, its signature and semantics are different. - """ +This function is a MicroPython extension. CPython has a similar +function - ``set_threshold()``, but due to different GC +implementations, its signature and semantics are different.""" ... @overload def threshold(amount: int) -> None: - """Set the additional GC allocation threshold. - - Normally, a collection is triggered only when a new allocation - cannot be satisfied, i.e. on an out-of-memory (OOM) condition. - If this function is called, in addition to OOM, a collection - will be triggered each time after ``amount`` bytes have been - allocated (in total, since the previous time such an amount of bytes - have been allocated). ``amount`` is usually specified as less than the - full heap size, with the intention to trigger a collection earlier than when the - heap becomes exhausted, and in the hope that an early collection will prevent - excessive memory fragmentation. This is a heuristic measure, the effect - of which will vary from application to application, as well as - the optimal value of the ``amount`` parameter. - - A value of -1 means a disabled allocation threshold. - - This function is a MicroPython extension. CPython has a similar - function - ``set_threshold()``, but due to different GC - implementations, its signature and semantics are different. - - :param amount: The number of bytes after which a garbage collection should be triggered. - """ - ... + """设置额外的垃圾回收分配阈值。 + +Normally, a collection is triggered only when a new allocation +cannot be satisfied, i.e. on an out-of-memory (OOM) condition. +If this function is called, in addition to OOM, a collection +will be triggered each time after ``amount`` bytes have been +allocated (in total, since the previous time such an amount of bytes +have been allocated). ``amount`` is usually specified as less than the +full heap size, with the intention to trigger a collection earlier than when the +heap becomes exhausted, and in the hope that an early collection will prevent +excessive memory fragmentation. This is a heuristic measure, the effect +of which will vary from application to application, as well as +the optimal value of the ``amount`` parameter. + +A value of -1 means a disabled allocation threshold. + +This function is a MicroPython extension. CPython has a similar +function - ``set_threshold()``, but due to different GC +implementations, its signature and semantics are different. + +:param amount: 触发进行垃圾回收的字节数。""" + ... \ No newline at end of file diff --git a/lang/zh-cn/typeshed/stdlib/log.pyi b/lang/zh-cn/typeshed/stdlib/log.pyi index c9870fa..39efb49 100644 --- a/lang/zh-cn/typeshed/stdlib/log.pyi +++ b/lang/zh-cn/typeshed/stdlib/log.pyi @@ -1,104 +1,89 @@ -"""Log data to your micro:bit V2.""" - +"""将数据记录到您的 micro:bit V2。 (日志)""" from typing import Literal, Mapping, Optional, Union, overload - MILLISECONDS = 1 -"""Milliseconds timestamp format.""" - +"""毫秒时间戳格式。 (毫秒)""" SECONDS = 10 -"""Seconds timestamp format.""" - +"""秒时间戳格式。 (秒)""" MINUTES = 600 -"""Minutes timestamp format.""" - +"""分钟时间戳格式。 (分钟)""" HOURS = 36000 -"""Hours timestamp format.""" - +"""小时时间戳格式。 (小时)""" DAYS = 864000 -"""Days timestamp format.""" +"""日期时间戳格式。 (天)""" -def set_labels( - *labels: str, timestamp: Optional[Literal[1, 10, 36000, 864000]] = SECONDS -) -> None: - """Set up the log file header. +def set_labels(*labels: str, timestamp: Optional[Literal[1, 10, 36000, 864000]]=SECONDS) -> None: + """设置日志文件头。 - Example: ``log.set_labels('X', 'Y', 'Z', timestamp=log.MINUTES)`` +Example: ``log.set_labels('X', 'Y', 'Z', timestamp=log.MINUTES)`` - Ideally this function should be called a single time, before any data is - logged, to configure the data table header once. +Ideally this function should be called a single time, before any data is +logged, to configure the data table header once. - If a log file already exists when the program starts, or if this function - is called multiple times, it will check the labels already defined in the - log file. If this function call contains any new labels not already - present, it will generate a new header row with the additional columns. +If a log file already exists when the program starts, or if this function +is called multiple times, it will check the labels already defined in the +log file. If this function call contains any new labels not already +present, it will generate a new header row with the additional columns. - By default the first column contains a timestamp for each row. The time - unit can be selected via the timestamp argument. +By default the first column contains a timestamp for each row. The time +unit can be selected via the timestamp argument. - :param *labels: Any number of positional arguments, each corresponding to an entry in the log header. - :param timestamp: Select the timestamp unit that will be automatically added as the first column in every row. Timestamp values can be one of ``log.MILLISECONDS``, ``log.SECONDS``, ``log.MINUTES``, ``log.HOURS``, ``log.DAYS`` or ``None`` to disable the timestamp. The default value is ``log.SECONDS``. - """ +:param *labels: (*标签) 任何数量的位置参数,每个对应于日志头中的一个标题。 +:param timestamp: 选择将自动添加为每行第一列的时间戳单位。 时间戳值可以是 ``log.MILLISECONDS``, ``log.SECONDS``, ``log.MINUTES``, ``log.HOURS``, ``log.DAYS`` ,或者 ``None`` 来禁用时间戳。 默认值是 ``log.SECONDS``。""" ... @overload -def add( - data_dictionary: Optional[Mapping[str, Union[str, int, float]]], -) -> None: - """Add a data row to the log by passing a dictionary of headers and values. +def add(data_dictionary: Optional[Mapping[str, Union[str, int, float]]]) -> None: + """通过传递包含标题和值的字典将数据行添加到日志中。 - Example: ``log.add({ 'temp': temperature() })`` +Example: ``log.add({ 'temp': temperature() })`` - Each call to this function adds a row to the log. +Each call to this function adds a row to the log. - New labels not previously specified via the set_labels function, or by a - previous call to this function, will trigger a new header entry to be added - to the log with the extra labels. +New labels not previously specified via the set_labels function, or by a +previous call to this function, will trigger a new header entry to be added +to the log with the extra labels. - Labels previously specified and not present in a call to this function will - be skipped with an empty value in the log row. +Labels previously specified and not present in a call to this function will +be skipped with an empty value in the log row. - :param data_dictionary: The data to log as a dictionary with a key for each header. - """ +:param data_dictionary: (数据词典) 要记录为词典的数据,每个标题都有一个键。""" ... @overload def add(**kwargs: Union[str, int, float]) -> None: - """Add a data row to the log using keyword arguments. + """使用关键字参数将数据行添加到日志中。 - Example: ``log.add(temp=temperature())`` +Example: ``log.add(temp=temperature())`` - Each call to this function adds a row to the log. +Each call to this function adds a row to the log. - New labels not previously specified via the set_labels function, or by a - previous call to this function, will trigger a new header entry to be added - to the log with the extra labels. +New labels not previously specified via the set_labels function, or by a +previous call to this function, will trigger a new header entry to be added +to the log with the extra labels. - Labels previously specified and not present in a call to this function will - be skipped with an empty value in the log row. - """ +Labels previously specified and not present in a call to this function will +be skipped with an empty value in the log row.""" ... def delete(full=False): - """Deletes the contents of the log, including headers. + """删除日志的内容,包括标题。 - Example: ``log.delete()`` +Example: ``log.delete()`` - To add the log headers again the ``set_labels`` function should to be called after this function. +To add the log headers again the ``set_labels`` function should to be called after this function. - There are two erase modes; “full” completely removes the data from the physical storage, - and “fast” invalidates the data without removing it. +There are two erase modes; “full” completely removes the data from the physical storage, +and “fast” invalidates the data without removing it. - :param full: ``True`` selects a “full” erase and ``False`` selects the “fast” erase method. - """ +:param full: ``True`` 选择“完全”擦除, ``False`` 选择“快速”擦除方法。""" ... def set_mirroring(serial: bool): - """Configure mirroring of the data logging activity to the serial output. + """配置将数据日志活动镜像到串行输出。 - Example: ``log.set_mirroring(True)`` +Example: ``log.set_mirroring(True)`` - Serial mirroring is disabled by default. When enabled, it will print to serial each row logged into the log file. +Serial mirroring is disabled by default. When enabled, it will print to serial each row logged into the log file. - :param serial: ``True`` enables mirroring data to the serial output. - """ - ... +:param serial: ``True`` 启用了将数据镜像到串行输出。""" + ... \ No newline at end of file diff --git a/lang/zh-cn/typeshed/stdlib/machine.pyi b/lang/zh-cn/typeshed/stdlib/machine.pyi index 2e82f5b..9ebcbc0 100644 --- a/lang/zh-cn/typeshed/stdlib/machine.pyi +++ b/lang/zh-cn/typeshed/stdlib/machine.pyi @@ -1,97 +1,84 @@ -"""Low-level utilities. -""" +"""低级实用程序。 (机器)""" from typing import Any from .microbit import MicroBitDigitalPin def unique_id() -> bytes: - """Get a byte string with a unique identifier of a board. + """获取具有板的唯一标识符的字节字符串。 - Example: ``machine.unique_id()`` +Example: ``machine.unique_id()`` - :return: An identifier that varies from one board instance to another. - """ +:return: An identifier that varies from one board instance to another.""" ... def reset() -> None: - """Reset the device in a manner similar to pushing the external RESET button. + """以类似于按下外部 RESET (重置)按钮的方式重置设备。 - Example: ``machine.reset()`` - """ +Example: ``machine.reset()``""" ... def freq() -> int: - """Get the CPU frequency in hertz. + """以赫兹为单位获取 CPU 频率。 - Example: ``machine.freq()`` +Example: ``machine.freq()`` - :return: The CPU frequency. - """ +:return: The CPU frequency.""" ... def disable_irq() -> Any: - """Disable interrupt requests. + """禁止中断请求。 - Example: ``interrupt_state = machine.disable_irq()`` +Example: ``interrupt_state = machine.disable_irq()`` - :return: the previous IRQ state which should be considered an opaque value +:return: the previous IRQ state which should be considered an opaque value - The return value should be passed to the ``enable_irq`` function to restore - interrupts to their original state. - """ +The return value should be passed to the ``enable_irq`` function to restore +interrupts to their original state.""" ... def enable_irq(state: Any) -> None: - """Re-enable interrupt requests. + """重新启用中断请求。 - Example: ``machine.enable_irq(interrupt_state)`` +Example: ``machine.enable_irq(interrupt_state)`` - :param state: The value that was returned from the most recent call to the ``disable_irq`` function. - """ +:param state: 最近一次调用 ``disable_irq`` 函数得到的返回值。""" ... -def time_pulse_us( - pin: MicroBitDigitalPin, pulse_level: int, timeout_us: int = 1000000 -) -> int: - """Time a pulse on a pin. +def time_pulse_us(pin: MicroBitDigitalPin, pulse_level: int, timeout_us: int=1000000) -> int: + """对引脚上的脉冲计时。 - Example: ``time_pulse_us(pin0, 1)`` +Example: ``time_pulse_us(pin0, 1)`` - If the current input value of the pin is different to ``pulse_level``, the - function first waits until the pin input becomes equal to - ``pulse_level``, then times the duration that the pin is equal to - ``pulse_level``. If the pin is already equal to ``pulse_level`` then timing - starts straight away. +If the current input value of the pin is different to ``pulse_level``, the +function first waits until the pin input becomes equal to +``pulse_level``, then times the duration that the pin is equal to +``pulse_level``. If the pin is already equal to ``pulse_level`` then timing +starts straight away. - :param pin: The pin to use - :param pulse_level: 0 to time a low pulse or 1 to time a high pulse - :param timeout_us: A microsecond timeout - :return: The duration of the pulse in microseconds, or -1 for a timeout waiting for the level to match ``pulse_level``, or -2 on timeout waiting for the pulse to end - """ +:param pin: (引脚) 要使用的引脚 +:param pulse_level: 0 来计时低脉冲或 1 来计时高脉冲。 +:param timeout_us: 微秒超时 +:return: The duration of the pulse in microseconds, or -1 for a timeout waiting for the level to match ``pulse_level``, or -2 on timeout waiting for the pulse to end""" ... class mem: - """The class for the ``mem8``, ``mem16`` and ``mem32`` memory views.""" + """``mem8``、 ``mem16`` 和 ``mem32`` 内存视图的类。""" def __getitem__(self, address: int) -> int: - """Access a value from memory. + """从内存中获取一个值。 - :param address: The memory address. - :return: The value at that address as an integer. - """ +:param address: (地址) 内存地址。 +:return: The value at that address as an integer.""" ... + def __setitem__(self, address: int, value: int) -> None: - """Set a value at the given address. + """在给定地址处设置一个值。 - :param address: The memory address. - :param value: The integer value to set. - """ +:param address: (地址) 内存地址。 +:param value: 要设置的整数值。""" ... - mem8: mem -"""8-bit (byte) view of memory.""" - +"""8 位(字节) 内存视图。""" mem16: mem -"""16-bit view of memory.""" - +"""16 位内存视图。""" mem32: mem -"""32-bit view of memory.""" +"""32 位内存视图。""" \ No newline at end of file diff --git a/lang/zh-cn/typeshed/stdlib/math.pyi b/lang/zh-cn/typeshed/stdlib/math.pyi index f82d4de..95acc4f 100644 --- a/lang/zh-cn/typeshed/stdlib/math.pyi +++ b/lang/zh-cn/typeshed/stdlib/math.pyi @@ -1,273 +1,246 @@ -"""Mathematical functions. -""" - +"""数学函数。 (数学)""" from typing import Tuple def acos(x: float) -> float: - """Calculate the inverse cosine. + """计算反余弦。 - Example: ``math.acos(1)`` +Example: ``math.acos(1)`` - :param x: A number - :return: The inverse cosine of ``x`` - """ +:param x: 一个数字 +:return: The inverse cosine of ``x``""" ... def asin(x: float) -> float: - """Calculate the inverse sine. + """计算反正弦值。 - Example: ``math.asin(0)`` +Example: ``math.asin(0)`` - :param x: A number - :return: The inverse sine of ``x`` - """ +:param x: 一个数字 +:return: The inverse sine of ``x``""" ... def atan(x: float) -> float: - """Calculate the inverse tangent. + """计算反正切。 - Example: ``math.atan(0)`` +Example: ``math.atan(0)`` - :param x: A number - :return: The inverse tangent of ``x`` - """ +:param x: 一个数字 +:return: The inverse tangent of ``x``""" ... def atan2(y: float, x: float) -> float: - """Calculate the principal value of the inverse tangent of ``y/x``. + """计算 ``y/x`` 的反正切的主值。 - Example: ``math.atan2(0, -1)`` +Example: ``math.atan2(0, -1)`` - :param y: A number - :param x: A number - :return: The principal value of the inverse tangent of ``y/x`` - """ +:param y: 一个数字 +:param x: 一个数字 +:return: The principal value of the inverse tangent of ``y/x``""" ... def ceil(x: float) -> float: - """Round a number towards positive infinity. + """将数字向正无穷大取整(向上取整) - Example: ``math.ceil(0.1)`` +Example: ``math.ceil(0.1)`` - :param x: A number - :return: ``x`` rounded towards positive infinity. - """ +:param x: 一个数字 +:return: ``x`` rounded towards positive infinity.""" ... def copysign(x: float, y: float) -> float: - """Calculate ``x`` with the sign of ``y``. + """获取 ``y`` 的符号和 ``x`` 的绝对值。 - Example: ``math.copysign(1, -1)`` +Example: ``math.copysign(1, -1)`` - :param x: A number - :param y: The source of the sign for the return value - :return: ``x`` with the sign of ``y`` - """ +:param x: 一个数字 +:param y: 返回值的符号来源 +:return: ``x`` with the sign of ``y``""" ... def cos(x: float) -> float: - """Calculate the cosine of ``x``. + """计算 ``x`` 的余弦。 - Example: ``math.cos(0)`` +Example: ``math.cos(0)`` - :param x: A number - :return: The cosine of ``x`` - """ +:param x: 一个数字 +:return: The cosine of ``x``""" ... def degrees(x: float) -> float: - """Convert radians to degrees. + """将弧度转换为度。 - Example: ``math.degrees(2 * math.pi)`` +Example: ``math.degrees(2 * math.pi)`` - :param x: A value in radians - :return: The value converted to degrees""" +:param x: 一个以弧度为单位的值 +:return: The value converted to degrees""" ... def exp(x: float) -> float: - """Calculate the exponential of ``x``. + """计算 E 的 ``x`` 指数。 - Example: ``math.exp(1)`` +Example: ``math.exp(1)`` - :param x: A number - :return: The exponential of ``x``. - """ +:param x: 一个数字 +:return: The exponential of ``x``.""" ... def fabs(x: float) -> float: - """Return the absolute value of ``x``. + """返回 ``x`` 的绝对值。 - Example: ``math.fabs(-0.1)`` +Example: ``math.fabs(-0.1)`` - :param x: A number - :return: The absolute value of ``x`` - """ +:param x: 一个数字 +:return: The absolute value of ``x``""" ... def floor(x: float) -> int: - """Round a number towards negative infinity. + """将数字向负无穷大取整(向下取整)。 (向下取整) - Example: ``math.floor(0.9)`` +Example: ``math.floor(0.9)`` - :param x: A number - :return: ``x`` rounded towards negative infinity. - """ +:param x: 一个数字 +:return: ``x`` rounded towards negative infinity.""" ... def fmod(x: float, y: float) -> float: - """Calculate the remainder of ``x/y``. + """计算 ``x/y`` 的余数。 (浮点余数) - Example: ``math.fmod(10, 3)`` +Example: ``math.fmod(10, 3)`` - :param x: The numerator - :param y: The denominator - """ +:param x: 分子 +:param y: 分母""" ... def frexp(x: float) -> Tuple[float, int]: - """Decomposes a floating-point number into its mantissa and exponent. + """将一个浮点数分解为其尾数和指数。 (浮点指数) - Example: ``mantissa, exponent = math.frexp(2)`` +Example: ``mantissa, exponent = math.frexp(2)`` - The returned value is the tuple ``(m, e)`` such that ``x == m * 2**e`` - exactly. If ``x == 0`` then the function returns ``(0.0, 0)``, otherwise - the relation ``0.5 <= abs(m) < 1`` holds. +The returned value is the tuple ``(m, e)`` such that ``x == m * 2**e`` +exactly. If ``x == 0`` then the function returns ``(0.0, 0)``, otherwise +the relation ``0.5 <= abs(m) < 1`` holds. - :param x: A floating-point number - :return: A tuple of length two containing its mantissa then exponent - """ +:param x: 一个浮点数 +:return: A tuple of length two containing its mantissa then exponent""" ... def isfinite(x: float) -> bool: - """Check if a value is finite. + """检查值是否有限。 (是有限的) - Example: ``math.isfinite(float('inf'))`` +Example: ``math.isfinite(float('inf'))`` - :param x: A number. - :return: ``True`` if ``x`` is finite, ``False`` otherwise. - """ +:param x: 一个数字。 +:return: ``True`` if ``x`` is finite, ``False`` otherwise.""" ... def isinf(x: float) -> bool: - """Check if a value is infinite. + """检查值是否无限。 (是无限的) - Example: ``math.isinf(float('-inf'))`` +Example: ``math.isinf(float('-inf'))`` - :param x: A number. - :return: ``True`` if ``x`` is infinite, ``False`` otherwise. - """ +:param x: 一个数字。 +:return: ``True`` if ``x`` is infinite, ``False`` otherwise.""" ... def isnan(x: float) -> bool: - """Check if a value is not-a-number (NaN). + """检查一个值是否不是一个数字 (NaN)。 (不是数字) - Example: ``math.isnan(float('nan'))`` +Example: ``math.isnan(float('nan'))`` - :param x: A number - :return: ``True`` if ``x`` is not-a-number (NaN), ``False`` otherwise.""" +:param x: 一个数字 +:return: ``True`` if ``x`` is not-a-number (NaN), ``False`` otherwise.""" ... def ldexp(x: float, exp: int) -> float: - """Calculate ``x * (2**exp)``. + """计算 ``x * (2**exp)`` 。 (加载指数) - Example: ``math.ldexp(0.5, 2)`` +Example: ``math.ldexp(0.5, 2)`` - :param x: A number - :param exp: Integer exponent - :return: ``x * (2**exp)`` - """ +:param x: 一个数字 +:param exp: 整数指数 +:return: ``x * (2**exp)``""" ... -def log(x: float, base: float = e) -> float: - """Calculate the logarithm of ``x`` to the given base (defaults to natural logorithm). +def log(x: float, base: float=e) -> float: + """计算给定底数 ``x`` 的对数(默认为自然对数)。 (日志) - Example: ``math.log(math.e)`` +Example: ``math.log(math.e)`` - With one argument, return the natural logarithm of x (to base e). +With one argument, return the natural logarithm of x (to base e). - With two arguments, return the logarithm of x to the given base, calculated as ``log(x)/log(base)``. +With two arguments, return the logarithm of x to the given base, calculated as ``log(x)/log(base)``. - :param x: A number - :param base: The base to use - :return: The natural logarithm of ``x`` - """ +:param x: 一个数字 +:param base: 要使用的底数 +:return: The natural logarithm of ``x``""" ... def modf(x: float) -> Tuple[float, float]: - """Calculate the fractional and integral parts of ``x``. + """计算 ``x`` 的小数和整数部分。 (浮点取模) - Example: ``fractional, integral = math.modf(1.5)`` +Example: ``fractional, integral = math.modf(1.5)`` - :param x: A number - :return: A tuple of two floats representing the fractional then integral parts of ``x``. +:param x: 一个数字 +:return: A tuple of two floats representing the fractional then integral parts of ``x``. - Both the fractional and integral values have the same sign as ``x``. - """ +Both the fractional and integral values have the same sign as ``x``.""" ... def pow(x: float, y: float) -> float: - """Returns ``x`` to the power of ``y``. + """返回 ``x`` 的 ``y``次幂。 (幂数) - Example: ``math.pow(4, 0.5)`` +Example: ``math.pow(4, 0.5)`` - :param x: A number - :param y: The exponent - :return: ``x`` to the power of ``y`` - """ +:param x: 一个数字 +:param y: 指数值 +:return: ``x`` to the power of ``y``""" ... def radians(x: float) -> float: - """Convert a degrees to radians. + """将度数转换为弧度。 - Example: ``math.radians(360)`` +Example: ``math.radians(360)`` - :param x: A value in degrees - :return: The value converted to radians - """ +:param x: 以度为单位的值 +:return: The value converted to radians""" ... def sin(x: float) -> float: - """Calculate the sine of ``x``. + """计算 ``x`` 的正弦值。 (正弦) - Example: ``math.sin(math.pi/2)`` +Example: ``math.sin(math.pi/2)`` - :param x: A number - :return: The sine of ``x`` - """ +:param x: 一个数字 +:return: The sine of ``x``""" ... def sqrt(x: float) -> float: - """Calculate the square root of ``x``. + """计算 ``x`` 的平方根。 (平方根) - Example: ``math.sqrt(4)`` +Example: ``math.sqrt(4)`` - :param x: A number - :return: The square root of ``x`` - """ +:param x: 一个数字 +:return: The square root of ``x``""" ... def tan(x: float) -> float: - """Calculate the tangent of ``x``. + """计算 ``x`` 的正切。 (正切) - Example: ``math.tan(0)`` +Example: ``math.tan(0)`` - :param x: A number - :return: The tangent of ``x``. - """ +:param x: 一个数字 +:return: The tangent of ``x``.""" ... def trunc(x: float) -> int: - """Round a number towards 0. + """将数字向 0 舍入。 (截断) - Example: ``math.trunc(-0.9)`` +Example: ``math.trunc(-0.9)`` - :param x: A number - :return: ``x`` rounded towards zero. - """ +:param x: 一个数字 +:return: ``x`` rounded towards zero.""" ... - e: float -"""Base of the natural logarithm""" - +"""自然对数的底数""" pi: float -"""The ratio of a circle's circumference to its diameter""" +"""圆的周长与其直径的比值""" \ No newline at end of file diff --git a/lang/zh-cn/typeshed/stdlib/microbit/__init__.pyi b/lang/zh-cn/typeshed/stdlib/microbit/__init__.pyi index f12158f..092c20e 100644 --- a/lang/zh-cn/typeshed/stdlib/microbit/__init__.pyi +++ b/lang/zh-cn/typeshed/stdlib/microbit/__init__.pyi @@ -1,11 +1,6 @@ -"""Pins, images, sounds, temperature and volume. -""" - +"""引脚、图像、声音、温度和音量。 (Microbit)""" from typing import Any, Callable, List, Optional, Tuple, Union, overload - from _typeshed import ReadableBuffer - -# V2 only from . import accelerometer as accelerometer from . import audio as audio from . import compass as compass @@ -16,831 +11,696 @@ from . import speaker as speaker from . import spi as spi from . import uart as uart -def run_every( - callback: Optional[Callable[[], None]] = None, - days: int = 0, - h: int = 0, - min: int = 0, - s: int = 0, - ms: int = 0, -) -> Callable[[Callable[[], None]], Callable[[], None]]: - """Schedule to run a function at the interval specified by the time arguments **V2 only**. +def run_every(callback: Optional[Callable[[], None]]=None, days: int=0, h: int=0, min: int=0, s: int=0, ms: int=0) -> Callable[[Callable[[], None]], Callable[[], None]]: + """计划以时间参数指定的时间间隔运行函数**仅限V2** 。 (周期性运行) - Example: ``run_every(my_logging, min=5)`` +Example: ``run_every(my_logging, min=5)`` - ``run_every`` can be used in two ways: +``run_every`` can be used in two ways: - As a Decorator - placed on top of the function to schedule. For example:: +As a Decorator - placed on top of the function to schedule. For example:: - @run_every(h=1, min=20, s=30, ms=50) - def my_function(): - # Do something here + @run_every(h=1, min=20, s=30, ms=50) + def my_function(): + # Do something here - As a Function - passing the callback as a positional argument. For example:: +As a Function - passing the callback as a positional argument. For example:: - def my_function(): - # Do something here - run_every(my_function, s=30) + def my_function(): + # Do something here + run_every(my_function, s=30) - Each argument corresponds to a different time unit and they are additive. - So ``run_every(min=1, s=30)`` schedules the callback every minute and a half. +Each argument corresponds to a different time unit and they are additive. +So ``run_every(min=1, s=30)`` schedules the callback every minute and a half. - When an exception is thrown inside the callback function it deschedules the - function. To avoid this you can catch exceptions with ``try/except``. +When an exception is thrown inside the callback function it deschedules the +function. To avoid this you can catch exceptions with ``try/except``. - :param callback: Function to call at the provided interval. Omit when using as a decorator. - :param days: Sets the day mark for the scheduling. - :param h: Sets the hour mark for the scheduling. - :param min: Sets the minute mark for the scheduling. - :param s: Sets the second mark for the scheduling. - :param ms: Sets the millisecond mark for the scheduling. - """ +:param callback: 在提供的时间间隔内调用的函数。用作装饰器时省略。 +:param days: (天) 设置定时计划的日期标记。 +:param h: 设置定时计划的小时标记。 +:param min: (分钟) 设置定时计划的分钟标记。 +:param s: (秒) 设置定时计划的秒标记。 +:param ms: (毫秒) 设置定时计划的毫秒标记。""" def panic(n: int) -> None: - """Enter a panic mode. + """进入 panic (恐慌)模式。 (恐慌) - Example: ``panic(127)`` +Example: ``panic(127)`` - :param n: An arbitrary integer <= 255 to indicate a status. +:param n: 一个 <= 255 的任意整数,以表示一个状态。 - Requires restart. - """ +Requires restart.""" def reset() -> None: - """Restart the board.""" - + """重启主板。""" @overload def scale(value: float, from_: Tuple[float, float], to: Tuple[int, int]) -> int: - """Converts a value from a range to an integer range. + """将一个数值从一个范围转换为整数范围。 (范围) - Example: ``volume = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255))`` +Example: ``volume = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255))`` - For example, to convert an accelerometer X value to a speaker volume. +For example, to convert an accelerometer X value to a speaker volume. - If one of the numbers in the ``to`` parameter is a floating point - (i.e a decimal number like ``10.0``), this function will return a - floating point number. +If one of the numbers in the ``to`` parameter is a floating point +(i.e a decimal number like ``10.0``), this function will return a +floating point number. - temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0)) + temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0)) - :param value: A number to convert. - :param from_: A tuple to define the range to convert from. - :param to: A tuple to define the range to convert to. - :return: The ``value`` converted to the ``to`` range. - """ +:param value: 要转换的数字。 +:param from_: (从) 一个元组,用于定义要转换的范围。 +:param to: (至) 一个元组,用于定义要转换到的范围。 +:return: The ``value`` converted to the ``to`` range.""" @overload def scale(value: float, from_: Tuple[float, float], to: Tuple[float, float]) -> float: - """Converts a value from a range to a floating point range. + """将一个数值从一个范围转换为浮点数范围。 (范围) - Example: ``temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0))`` +Example: ``temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0))`` - For example, to convert temperature from a Celsius scale to Fahrenheit. +For example, to convert temperature from a Celsius scale to Fahrenheit. - If one of the numbers in the ``to`` parameter is a floating point - (i.e a decimal number like ``10.0``), this function will return a - floating point number. - If they are both integers (i.e ``10``), it will return an integer:: +If one of the numbers in the ``to`` parameter is a floating point +(i.e a decimal number like ``10.0``), this function will return a +floating point number. +If they are both integers (i.e ``10``), it will return an integer:: - returns_int = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255)) + returns_int = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255)) - :param value: A number to convert. - :param from_: A tuple to define the range to convert from. - :param to: A tuple to define the range to convert to. - :return: The ``value`` converted to the ``to`` range. - """ +:param value: 要转换的数字。 +:param from_: (从) 一个元组,用于定义要转换的范围。 +:param to: (至) 一个元组,用于定义要转换到的范围。 +:return: The ``value`` converted to the ``to`` range.""" def sleep(n: float) -> None: - """Wait for ``n`` milliseconds. + """等待 ``n`` 毫秒。 (休眠) - Example: ``sleep(1000)`` +Example: ``sleep(1000)`` - :param n: The number of milliseconds to wait +:param n: 要等待的毫秒数 - One second is 1000 milliseconds, so:: +One second is 1000 milliseconds, so:: - microbit.sleep(1000) + microbit.sleep(1000) - will pause the execution for one second. - """ +will pause the execution for one second.""" def running_time() -> int: - """Get the running time of the board. + """获取主板的运行时间。 - :return: The number of milliseconds since the board was switched on or restarted. - """ +:return: The number of milliseconds since the board was switched on or restarted.""" def temperature() -> int: - """Get the temperature of the micro:bit in degrees Celsius.""" + """以摄氏度为单位获取 micro:bit 的温度。""" def set_volume(v: int) -> None: - """Sets the volume. + """设置音量。 - Example: ``set_volume(127)`` +Example: ``set_volume(127)`` - :param v: a value between 0 (low) and 255 (high). +:param v: 一个介于 0 (低) 和 255 (高) 之间的值。 - Out of range values will be clamped to 0 or 255. +Out of range values will be clamped to 0 or 255. - **V2** only. - """ +**V2** only.""" ... class Button: - """The class for the buttons ``button_a`` and ``button_b``.""" + """按钮 ``button_a`` 和 ``button_b`` 的类。""" def is_pressed(self) -> bool: - """Check if the button is pressed. + """检查按钮是否被按下。 - :return: ``True`` if the specified button ``button`` is pressed, and ``False`` otherwise. - """ +:return: ``True`` if the specified button ``button`` is pressed, and ``False`` otherwise.""" ... + def was_pressed(self) -> bool: - """Check if the button was pressed since the device started or the last time this method was called. + """检查按钮自设备启动以来或者上次调用此方法之后是否被按下。 - Calling this method will clear the press state so - that the button must be pressed again before this method will return - ``True`` again. +Calling this method will clear the press state so +that the button must be pressed again before this method will return +``True`` again. - :return: ``True`` if the specified button ``button`` was pressed, and ``False`` otherwise - """ +:return: ``True`` if the specified button ``button`` was pressed, and ``False`` otherwise""" ... + def get_presses(self) -> int: - """Get the running total of button presses, and resets this total - to zero before returning. + """获得按钮被按下的总计次数,并在返回之前将该总计次数重置为 0。 - :return: The number of presses since the device started or the last time this method was called - """ +:return: The number of presses since the device started or the last time this method was called""" ... - button_a: Button -"""The left button ``Button`` object.""" - +"""左键 ``Button`` 对象。 (按钮 a)""" button_b: Button -"""The right button ``Button`` object.""" +"""右键 ``Button`` 对象。 (按钮 b)""" class MicroBitDigitalPin: - """A digital pin. - - Some pins support analog and touch features using the ``MicroBitAnalogDigitalPin`` and ``MicroBitTouchPin`` subclasses. - """ + """数字引脚。 (Microbit 数字引脚) +Some pins support analog and touch features using the ``MicroBitAnalogDigitalPin`` and ``MicroBitTouchPin`` subclasses.""" NO_PULL: int PULL_UP: int PULL_DOWN: int + def read_digital(self) -> int: - """Get the digital value of the pin. + """获取引脚的数字值。 - Example: ``value = pin0.read_digital()`` +Example: ``value = pin0.read_digital()`` - :return: 1 if the pin is high, and 0 if it's low. - """ +:return: 1 if the pin is high, and 0 if it's low.""" ... + def write_digital(self, value: int) -> None: - """Set the digital value of the pin. + """设置引脚的数字值。 - Example: ``pin0.write_digital(1)`` +Example: ``pin0.write_digital(1)`` - :param value: 1 to set the pin high or 0 to set the pin low""" +:param value: 1 将引脚设置为高电平,或 0 将引脚设置为低电平""" ... + def set_pull(self, value: int) -> None: - """Set the pull state to one of three possible values: ``PULL_UP``, ``PULL_DOWN`` or ``NO_PULL``. + """将拉取状态设置为以下三个可能的值之一:``PULL_UP``、``PULL_DOWN`` 或 N``NO_PULL``。 - Example: ``pin0.set_pull(pin0.PULL_UP)`` +Example: ``pin0.set_pull(pin0.PULL_UP)`` - :param value: The pull state from the relevant pin, e.g. ``pin0.PULL_UP``. - """ +:param value: 相关引脚的拉取状态,例如: ``pin0.PULL_UP``。""" ... + def get_pull(self) -> int: - """Get the pull state on a pin. + """获取引脚上的拉取状态。 - Example: ``pin0.get_pull()`` +Example: ``pin0.get_pull()`` - :return: ``NO_PULL``, ``PULL_DOWN``, or ``PULL_UP`` +:return: ``NO_PULL``, ``PULL_DOWN``, or ``PULL_UP`` - These are set using the ``set_pull()`` method or automatically configured - when a pin mode requires it. - """ +These are set using the ``set_pull()`` method or automatically configured +when a pin mode requires it.""" ... + def get_mode(self) -> str: - """Returns the pin mode. + """返回引脚模式。 - Example: ``pin0.get_mode()`` +Example: ``pin0.get_mode()`` - When a pin is used for a specific function, like - writing a digital value, or reading an analog value, the pin mode - changes. +When a pin is used for a specific function, like +writing a digital value, or reading an analog value, the pin mode +changes. - :return: ``"unused"``, ``"analog"``, ``"read_digital"``, ``"write_digital"``, ``"display"``, ``"button"``, ``"music"``, ``"audio"``, ``"touch"``, ``"i2c"``, or ``"spi"`` - """ +:return: ``"unused"``, ``"analog"``, ``"read_digital"``, ``"write_digital"``, ``"display"``, ``"button"``, ``"music"``, ``"audio"``, ``"touch"``, ``"i2c"``, or ``"spi"``""" ... + def write_analog(self, value: int) -> None: - """Output a PWM signal on the pin, with the duty cycle proportional to ``value``. + """在引脚上输出 PWM 信号,占空比为 ``value``。 + +Example: ``pin0.write_analog(254)`` - Example: ``pin0.write_analog(254)`` +:param value: 介于 0(0% 占空比)和 1023(100% 占空比)之间的整数或浮点数。""" - :param value: 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. + """将输出的 PWM 信号的周期设置为 ``period``(单位:毫秒)。 - Example: ``pin0.set_analog_period(10)`` +Example: ``pin0.set_analog_period(10)`` + +:param period: 以毫秒为单位的周期,最小有效值为 1 毫秒。""" - :param period: The period in milliseconds with a minimum valid value of 1ms. - """ def set_analog_period_microseconds(self, period: int) -> None: - """Set the period of the PWM signal being output to ``period`` in microseconds. + """将输出的 PWM 信号的周期设置为 ``period``(单位:微秒)。 - Example: ``pin0.set_analog_period_microseconds(512)`` +Example: ``pin0.set_analog_period_microseconds(512)`` - :param period: The period in microseconds with a minimum valid value of 256µs. - """ +:param period: 以微秒为单位的周期,最小有效值为 256 毫秒。""" class MicroBitAnalogDigitalPin(MicroBitDigitalPin): - """A pin with analog and digital features.""" + """带有模拟和数字功能的引脚。""" def read_analog(self) -> int: - """Read the voltage applied to the pin. + """读取应用于引脚的电压。 - Example: ``pin0.read_analog()`` +Example: ``pin0.read_analog()`` - :return: An integer between 0 (meaning 0V) and 1023 (meaning 3.3V). - """ +:return: An integer between 0 (meaning 0V) and 1023 (meaning 3.3V).""" class MicroBitTouchPin(MicroBitAnalogDigitalPin): - """A pin with analog, digital and touch features.""" - + """带有模拟、数字和触摸功能的引脚。""" CAPACITIVE: int RESISTIVE: int + def is_touched(self) -> bool: - """Check if the pin is being touched. + """检查引脚是否被触摸。 - Example: ``pin0.is_touched()`` +Example: ``pin0.is_touched()`` - The default touch mode for the pins on the edge connector is ``resistive``. - The default for the logo pin **V2** is ``capacitive``. +The default touch mode for the pins on the edge connector is ``resistive``. +The default for the logo pin **V2** is ``capacitive``. - **Resistive touch** - This test is done by measuring how much resistance there is between the - pin and ground. A low resistance gives a reading of ``True``. To get - a reliable reading using a finger you may need to touch the ground pin - with another part of your body, for example your other hand. +**Resistive touch** +This test is done by measuring how much resistance there is between the +pin and ground. A low resistance gives a reading of ``True``. To get +a reliable reading using a finger you may need to touch the ground pin +with another part of your body, for example your other hand. - **Capacitive touch** - This test is done by interacting with the electric field of a capacitor - using a finger as a conductor. `Capacitive touch - `_ - does not require you to make a ground connection as part of a circuit. +**Capacitive touch** +This test is done by interacting with the electric field of a capacitor +using a finger as a conductor. `Capacitive touch +`_ +does not require you to make a ground connection as part of a circuit. - :return: ``True`` if the pin is being touched with a finger, otherwise return ``False``. - """ +:return: ``True`` if the pin is being touched with a finger, otherwise return ``False``.""" ... + def set_touch_mode(self, value: int) -> None: - """Set the touch mode for the pin. + """设置引脚的触摸模式。 - Example: ``pin0.set_touch_mode(pin0.CAPACITIVE)`` +Example: ``pin0.set_touch_mode(pin0.CAPACITIVE)`` - The default touch mode for the pins on the edge connector is - ``resistive``. The default for the logo pin **V2** is ``capacitive``. +The default touch mode for the pins on the edge connector is +``resistive``. The default for the logo pin **V2** is ``capacitive``. - :param value: ``CAPACITIVE`` or ``RESISTIVE`` from the relevant pin. - """ +:param value: 来自相关引脚的 ``CAPACITIVE`` 或 ``RESISTIVE``。""" ... - pin0: MicroBitTouchPin -"""Pin with digital, analog and touch features.""" - +"""具有数字、模拟和触摸功能的引脚。 (引脚0)""" pin1: MicroBitTouchPin -"""Pin with digital, analog and touch features.""" - +"""具有数字、模拟和触摸功能的引脚。 (引脚1)""" pin2: MicroBitTouchPin -"""Pin with digital, analog and touch features.""" - +"""具有数字、模拟和触摸功能的引脚。 (引脚2)""" pin3: MicroBitAnalogDigitalPin -"""Pin with digital and analog features.""" - +"""具有数字和模拟功能的引脚。 (引脚3)""" pin4: MicroBitAnalogDigitalPin -"""Pin with digital and analog features.""" - +"""具有数字和模拟功能的引脚。 (引脚4)""" pin5: MicroBitDigitalPin -"""Pin with digital features.""" - +"""具有数字功能的引脚。 (引脚5)""" pin6: MicroBitDigitalPin -"""Pin with digital features.""" - +"""具有数字功能的引脚。 (引脚6)""" pin7: MicroBitDigitalPin -"""Pin with digital features.""" - +"""具有数字功能的引脚。 (引脚7)""" pin8: MicroBitDigitalPin -"""Pin with digital features.""" - +"""具有数字功能的引脚。 (引脚8)""" pin9: MicroBitDigitalPin -"""Pin with digital features.""" - +"""具有数字功能的引脚。 (引脚9)""" pin10: MicroBitAnalogDigitalPin -"""Pin with digital and analog features.""" - +"""具有数字和模拟功能的引脚。 (引脚10)""" pin11: MicroBitDigitalPin -"""Pin with digital features.""" - +"""具有数字功能的引脚。 (引脚11)""" pin12: MicroBitDigitalPin -"""Pin with digital features.""" - +"""具有数字功能的引脚。 (引脚12)""" pin13: MicroBitDigitalPin -"""Pin with digital features.""" - +"""具有数字功能的引脚。 (引脚13)""" pin14: MicroBitDigitalPin -"""Pin with digital features.""" - +"""具有数字功能的引脚。 (引脚14)""" pin15: MicroBitDigitalPin -"""Pin with digital features.""" - +"""具有数字功能的引脚。 (引脚15)""" pin16: MicroBitDigitalPin -"""Pin with digital features.""" - +"""具有数字功能的引脚。 (引脚16)""" pin19: MicroBitDigitalPin -"""Pin with digital features.""" - +"""具有数字功能的引脚。 (引脚19)""" pin20: MicroBitDigitalPin -"""Pin with digital features.""" - +"""具有数字功能的引脚。 (引脚20)""" pin_logo: MicroBitTouchPin -"""A touch sensitive logo pin on the front of the micro:bit, which by default is set to capacitive touch mode.""" - +"""micro:bit 正面的触摸感应标志引脚,默认设置为电容式触摸模式。 (引脚标志)""" pin_speaker: MicroBitAnalogDigitalPin -"""A pin to address the micro:bit speaker. +"""用于对 micro:bit 扬声器寻址的引脚。 (扬声器引脚) This API is intended only for use in Pulse-Width Modulation pin operations e.g. pin_speaker.write_analog(128). """ class Image: - """An image to show on the micro:bit LED display. + """在 micro:bit LED 显示屏上显示的图像。 (图像) - Given an image object it's possible to display it via the ``display`` API:: - - display.show(Image.HAPPY) - """ +Given an image object it's possible to display it via the ``display`` API:: + display.show(Image.HAPPY)""" HEART: Image - """Heart image.""" - + """心形图像 (心形)""" HEART_SMALL: Image - """Small heart image.""" - + """小的心形图像。 (小的心形)""" HAPPY: Image - """Happy face image.""" - + """快乐的脸部图像。 (快乐)""" SMILE: Image - """Smiling mouth image.""" - + """微笑的脸部图像。 (微笑)""" SAD: Image - """Sad face image.""" - + """难过的脸部图像。 (难过)""" CONFUSED: Image - """Confused face image.""" - + """困惑的面部图像。 (困惑)""" ANGRY: Image - """Angry face image.""" - + """愤怒的脸部图像。 (愤怒)""" ASLEEP: Image - """Sleeping face image.""" - + """睡着的脸部图像。 (睡着)""" SURPRISED: Image - """Surprised face image.""" - + """惊讶的脸部图像。 (惊讶)""" SILLY: Image - """Silly face image.""" - + """傻傻的脸部图像。 (傻的)""" FABULOUS: Image - """Sunglasses face image.""" - + """戴墨镜的脸部图像。 (极好的)""" MEH: Image - """Unimpressed face image.""" - + """印象平平的脸部图像 (不感兴趣的)""" YES: Image - """Tick image.""" - + """对勾图像。 (是的)""" NO: Image - """Cross image.""" - + """打叉图像。 (不是)""" CLOCK12: Image - """Image with line pointing to 12 o'clock.""" - + """指针指向 12 点钟位置的图像。 (时钟12点)""" CLOCK11: Image - """Image with line pointing to 11 o'clock.""" - + """指针指向 11 点钟位置的图像。 (时钟11点)""" CLOCK10: Image - """Image with line pointing to 10 o'clock.""" - + """指针指向 10 点钟位置的图像。 (时钟10点)""" CLOCK9: Image - """Image with line pointing to 9 o'clock.""" - + """指针指向 9 点钟位置的图像。 (时钟9点)""" CLOCK8: Image - """Image with line pointing to 8 o'clock.""" - + """指针指向 8 点钟位置的图像。 (时钟8点)""" CLOCK7: Image - """Image with line pointing to 7 o'clock.""" - + """指针指向 7 点钟位置的图像。 (时钟7点)""" CLOCK6: Image - """Image with line pointing to 6 o'clock.""" - + """指针指向 6 点钟位置的图像。 (时钟6点)""" CLOCK5: Image - """Image with line pointing to 5 o'clock.""" - + """指针指向 5 点钟位置的图像。 (时钟5点)""" CLOCK4: Image - """Image with line pointing to 4 o'clock.""" - + """指针指向 4 点钟位置的图像。 (时钟4点)""" CLOCK3: Image - """Image with line pointing to 3 o'clock.""" - + """指针指向 3 点钟位置的图像。 (时钟3点)""" CLOCK2: Image - """Image with line pointing to 2 o'clock.""" - + """指针指向 2 点钟位置的图像。 (时钟2点)""" CLOCK1: Image - """Image with line pointing to 1 o'clock.""" - + """指针指向 1 点钟位置的图像。 (时钟1点)""" ARROW_N: Image - """Image of arrow pointing north.""" - + """指向北方的箭头的图像。 (箭头(指向北))""" ARROW_NE: Image - """Image of arrow pointing north east.""" - + """指向东北方的箭头的图像。 (箭头(指向东北))""" ARROW_E: Image - """Image of arrow pointing east.""" - + """指向东方的箭头的图像。 (箭头(指向东))""" ARROW_SE: Image - """Image of arrow pointing south east.""" - + """指向东南方的箭头的图像。 (箭头(指向东南))""" ARROW_S: Image - """Image of arrow pointing south.""" - + """指向南方的箭头图像。 (箭头(指向南))""" ARROW_SW: Image - """Image of arrow pointing south west.""" - + """指向西南方的箭头的图像。 (箭头(指向西南))""" ARROW_W: Image - """Image of arrow pointing west.""" - + """指向西方的箭头的图像。 (箭头(指向西))""" ARROW_NW: Image - """Image of arrow pointing north west.""" - + """指向西北方的箭头的图像。 (箭头(指向西北))""" TRIANGLE: Image - """Image of a triangle pointing up.""" - + """向上的三角形图像。 (三角)""" TRIANGLE_LEFT: Image - """Image of a triangle in the left corner.""" - + """左角的三角形图像。 (左三角)""" CHESSBOARD: Image - """Alternate LEDs lit in a chessboard pattern.""" - + """按棋盘式交替点亮 LED。 (国际象棋棋盘)""" DIAMOND: Image - """Diamond image.""" - + """钻石图像。 (菱形)""" DIAMOND_SMALL: Image - """Small diamond image.""" - + """小钻石图像。 (小的菱形)""" SQUARE: Image - """Square image.""" - + """方形图像。 (正方形)""" SQUARE_SMALL: Image - """Small square image.""" - + """小的方形图像。 (小方形)""" RABBIT: Image - """Rabbit image.""" - + """兔子图像。 (兔子)""" COW: Image - """Cow image.""" - + """奶牛图像。 (牛)""" MUSIC_CROTCHET: Image - """Crotchet note image.""" - + """音乐音符图像 (音乐音符)""" MUSIC_QUAVER: Image - """Quaver note image.""" - + """八分音符图像。 (八分音符)""" MUSIC_QUAVERS: Image - """Pair of quavers note image.""" - + """一对八分音符图像。 (一对八分音符)""" PITCHFORK: Image - """Pitchfork image.""" - + """干草叉图像。 (干草叉)""" XMAS: Image - """Christmas tree image.""" - + """圣诞树图像。 (圣诞节)""" PACMAN: Image - """Pac-Man arcade character image.""" - + """吃豆人游戏角色图像。 (吃豆人)""" TARGET: Image - """Target image.""" - + """目标图像 (目标)""" TSHIRT: Image - """T-shirt image.""" - + """T 恤图像。 (T恤)""" ROLLERSKATE: Image - """Rollerskate image.""" - + """轮滑图像。 (轮滑)""" DUCK: Image - """Duck image.""" - + """鸭子图像。 (鸭子)""" HOUSE: Image - """House image.""" - + """房子图像。 (房子)""" TORTOISE: Image - """Tortoise image.""" - + """乌龟图像。 (乌龟)""" BUTTERFLY: Image - """Butterfly image.""" - + """蝴蝶图像 (蝴蝶)""" STICKFIGURE: Image - """Stick figure image.""" - + """火柴人图像。 (简笔人物画)""" GHOST: Image - """Ghost image.""" - + """幽灵图像。 (幽灵)""" SWORD: Image - """Sword image.""" - + """利剑图像。 (剑)""" GIRAFFE: Image - """Giraffe image.""" - + """长颈鹿图像。 (长颈鹿)""" SKULL: Image - """Skull image.""" - + """骷髅图像。 (骷髅)""" UMBRELLA: Image - """Umbrella image.""" - + """雨伞图像。 (雨伞)""" SNAKE: Image - """Snake image.""" - + """蛇图像。 (蛇)""" SCISSORS: Image - """Scissors image.""" - + """剪刀图像。 (剪刀)""" ALL_CLOCKS: List[Image] - """A list containing all the CLOCK_ images in sequence.""" - + """按顺序包含所有 CLOCK_ 图像的列表(时钟)。 (所有时钟)""" ALL_ARROWS: List[Image] - """A list containing all the ARROW_ images in sequence.""" + """按顺序包含所有 ARROW_ 图像的列表(箭头)。 (所有箭头)""" + @overload def __init__(self, string: str) -> None: - """Create an image from a string describing which LEDs are lit. + """根据描述点亮 LED 的字符串来创建一幅图像。 - ``string`` has to consist of digits 0-9 arranged into lines, - describing the image, for example:: +``string`` has to consist of digits 0-9 arranged into lines, +describing the image, for example:: - image = Image("90009:" - "09090:" - "00900:" - "09090:" - "90009") + 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 newlines (\\n) insead of the colons. +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 newlines (\\n) insead of the colons. - :param string: The string describing the image. - """ +:param string: 描述图像的字符串。""" ... + @overload - def __init__( - self, width: int = 5, height: int = 5, buffer: ReadableBuffer = None - ) -> None: - """Create an empty image with ``width`` columns and ``height`` rows. + def __init__(self, width: int=5, height: int=5, buffer: ReadableBuffer=None) -> None: + """创建一幅具有 ``width`` 列和 ``height`` 行的空白图像。 - :param width: Optional width of the image - :param height: Optional height of the image - :param buffer: Optional array or bytes of ``width``×``height`` integers in range 0-9 to initialize the image +:param width: (宽度) 可选的图像宽度 +:param height: (高度) 可选的图像高度 +:param buffer: (缓冲区) 用可选数组或在 0-9 范围内的 ``width`` × ``height`` 整数字节来初始化图像 - Examples:: +Examples:: - Image(2, 2, b'\x08\x08\x08\x08') - Image(2, 2, bytearray([9,9,9,9])) + Image(2, 2, b'\x08\x08\x08\x08') + Image(2, 2, bytearray([9,9,9,9])) - These create 2 x 2 pixel images at full brightness. - """ +These create 2 x 2 pixel images at full brightness.""" ... + def width(self) -> int: - """Get the number of columns. + """获取列数。 (宽度) - :return: The number of columns in the image - """ +:return: The number of columns in the image""" ... + def height(self) -> int: - """Get the number of rows. + """获取行数。 (高度) - :return: The number of rows in the image - """ +:return: The number of rows in the image""" ... + def set_pixel(self, x: int, y: int, value: int) -> None: - """Set the brightness of a pixel. + """设置像素亮度。 - Example: ``my_image.set_pixel(0, 0, 9)`` +Example: ``my_image.set_pixel(0, 0, 9)`` - :param x: The column number - :param y: The row number - :param value: The brightness as an integer between 0 (dark) and 9 (bright) +:param x: 列号 +:param y: 行号 +:param value: 用 0(暗)和 9(亮)之间的整数来代表亮度 - This method will raise an exception when called on any of the built-in - read-only images, like ``Image.HEART``. - """ +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: - """Get the brightness of a pixel. + """获取一个像素的亮度。 - Example: ``my_image.get_pixel(0, 0)`` +Example: ``my_image.get_pixel(0, 0)`` - :param x: The column number - :param y: The row number - :return: The brightness as an integer between 0 and 9. - """ +:param x: 列号 +:param y: 行号 +:return: The brightness as an integer between 0 and 9.""" ... + def shift_left(self, n: int) -> Image: - """Create a new image by shifting the picture left. + """通过向左移动图片来创建新图像。 - Example: ``Image.HEART_SMALL.shift_left(1)`` +Example: ``Image.HEART_SMALL.shift_left(1)`` - :param n: The number of columns to shift by - :return: The shifted image - """ +:param n: 要移动的列数 +:return: The shifted image""" ... + def shift_right(self, n: int) -> Image: - """Create a new image by shifting the picture right. + """通过向右移动图片来创建新图像。 - Example: ``Image.HEART_SMALL.shift_right(1)`` +Example: ``Image.HEART_SMALL.shift_right(1)`` - :param n: The number of columns to shift by - :return: The shifted image - """ +:param n: 要移动的列数 +:return: The shifted image""" ... + def shift_up(self, n: int) -> Image: - """Create a new image by shifting the picture up. + """通过向上移动图片来创建新图像。 - Example: ``Image.HEART_SMALL.shift_up(1)`` +Example: ``Image.HEART_SMALL.shift_up(1)`` - :param n: The number of rows to shift by - :return: The shifted image - """ +:param n: 要移动的行数 +:return: The shifted image""" ... + def shift_down(self, n: int) -> Image: - """Create a new image by shifting the picture down. + """通过向下移动图片来创建新图像。 - Example: ``Image.HEART_SMALL.shift_down(1)`` +Example: ``Image.HEART_SMALL.shift_down(1)`` - :param n: The number of rows to shift by - :return: The shifted image - """ +:param n: 要移动的行数 +:return: The shifted image""" ... + def crop(self, x: int, y: int, w: int, h: int) -> Image: - """Create a new image by cropping the picture. + """通过裁剪图片来创建一幅新图像。 (裁剪) - Example: ``Image.HEART.crop(1, 1, 3, 3)`` +Example: ``Image.HEART.crop(1, 1, 3, 3)`` - :param x: The crop offset column - :param y: The crop offset row - :param w: The crop width - :param h: The crop height - :return: The new image - """ +:param x: 裁剪偏移列 +:param y: 裁剪偏移行 +:param w: 裁剪宽度 +:param h: 裁剪高度 +:return: The new image""" ... + def copy(self) -> Image: - """Create an exact copy of the image. + """创建图像的精确副本。 (复制) - Example: ``Image.HEART.copy()`` +Example: ``Image.HEART.copy()`` - :return: The new image - """ +:return: The new image""" ... + def invert(self) -> Image: - """Create a new image by inverting the brightness of the pixels in the - source image. + """通过反转源图像中像素的亮度来创建一幅新图像。 (反转) - Example: ``Image.SMALL_HEART.invert()`` +Example: ``Image.SMALL_HEART.invert()`` - :return: The new image. - """ +:return: The new image.""" ... + def fill(self, value: int) -> None: - """Set the brightness of all the pixels in the image. + """设置图像中所有像素的亮度。 (填充) - Example: ``my_image.fill(5)`` +Example: ``my_image.fill(5)`` - :param value: The new brightness as a number between 0 (dark) and 9 (bright). +:param value: 新亮度为 0 (暗) 和 9 (明) 之间的数字。 - This method will raise an exception when called on any of the built-in - read-only images, like ``Image.HEART``. - """ +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 an area from another image into this image. - - Example: ``my_image.blit(Image.HEART, 1, 1, 3, 3, 1, 1)`` - - :param src: The source image - :param x: The starting column offset in the source image - :param y: The starting row offset in the source image - :param w: The number of columns to copy - :param h: The number of rows to copy - :param xdest: The column offset to modify in this image - :param ydest: The row offset to modify in this image - - Pixels outside the source image are treated as having a brightness 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 blit(self, src: Image, x: int, y: int, w: int, h: int, xdest: int=0, ydest: int=0) -> None: + """复制另一幅图像的一部分区域到这幅图像。 + +Example: ``my_image.blit(Image.HEART, 1, 1, 3, 3, 1, 1)`` + +:param src: (来源) 源图像 +:param x: 源图像的起始列偏移量 +:param y: 源图像的起始行偏移量 +:param w: 要复制的列数 +:param h: 要复制的行数 +:param xdest: (x偏离量) 此图像中要修改的列偏移量 +:param ydest: (y偏离量) 此图像中要修改的行偏移量 + +Pixels outside the source image are treated as having a brightness 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. + """通过将两幅图像每个像素的亮度值相加来创建一幅新图像。 - Example: ``Image.HEART + Image.HAPPY`` +Example: ``Image.HEART + Image.HAPPY`` - :param other: The image to add. - """ +:param other: (其他) 要添加的图像。""" ... + def __sub__(self, other: Image) -> Image: - """Create a new image by subtracting the brightness values of the - other image from this image. + """通过从此图像中减去另一幅图像的亮度值来创建一幅新图像。 (减去) - Example: ``Image.HEART - Image.HEART_SMALL`` +Example: ``Image.HEART - Image.HEART_SMALL`` - :param other: The image to subtract. - """ +:param other: (其他) 要减去的图像。""" ... + def __mul__(self, n: float) -> Image: - """Create a new image by multiplying the brightness of each pixel by - ``n``. + """通过将每个像素的亮度乘以 ``n`` 来创建一幅新图像。 (相乘) - Example: ``Image.HEART * 0.5`` +Example: ``Image.HEART * 0.5`` - :param n: The value to multiply by. - """ +:param n: 要相乘的数值。""" ... + def __truediv__(self, n: float) -> Image: - """Create a new image by dividing the brightness of each pixel by - ``n``. + """通过将每个像素的亮度除以 ``n`` 来创建一幅新图像。 (除以) - Example: ``Image.HEART / 2`` +Example: ``Image.HEART / 2`` - :param n: The value to divide by. - """ +:param n: 要除以的数值。""" ... class SoundEvent: LOUD: SoundEvent - """Represents the transition of sound events, from ``quiet`` to ``loud`` like clapping or shouting.""" - + """表示声音事件从``quiet``到``loud``的过渡,如拍手或者喊叫。 (大声)""" QUIET: SoundEvent - """Represents the transition of sound events, from ``loud`` to ``quiet`` like speaking or background music.""" + """表示声音事件从``loud``到``quiet``的过渡,如说话或者背景音乐。 (安静)""" class Sound: - """The built-in sounds can be called using ``audio.play(Sound.NAME)``.""" - + """可以使用 ``audio.play(Sound.NAME)`` 调用内置声音。 (声音)""" GIGGLE: Sound - """Giggling sound.""" - + """咯咯的声音。 (咯咯笑)""" HAPPY: Sound - """Happy sound.""" - + """快乐的声音。 (快乐)""" HELLO: Sound - """Greeting sound.""" - + """问候声。 (你好)""" MYSTERIOUS: Sound - """Mysterious sound.""" - + """神秘的声音 (神秘的)""" SAD: Sound - """Sad sound.""" - + """悲伤的声音。 (难过)""" SLIDE: Sound - """Sliding sound.""" - + """滑动声。 (滑动)""" SOARING: Sound - """Soaring sound.""" - + """翱翔的声音。 (高昂)""" SPRING: Sound - """Spring sound.""" - + """春天的声音。 (弹簧)""" TWINKLE: Sound - """Twinkling sound.""" - + """闪烁的声音。 (闪烁)""" YAWN: Sound - """Yawning sound.""" + """打哈欠的声音。 (打哈欠)""" \ No newline at end of file diff --git a/lang/zh-cn/typeshed/stdlib/microbit/accelerometer.pyi b/lang/zh-cn/typeshed/stdlib/microbit/accelerometer.pyi index bac82c0..bae4607 100644 --- a/lang/zh-cn/typeshed/stdlib/microbit/accelerometer.pyi +++ b/lang/zh-cn/typeshed/stdlib/microbit/accelerometer.pyi @@ -1,115 +1,103 @@ -"""Measure the acceleration of the micro:bit and recognise gestures. -""" - +"""测量 micro:bit 的加速度并识别手势。 (加速度传感器)""" from typing import Tuple def get_x() -> int: - """Get the acceleration measurement in the ``x`` axis in milli-g. + """获取 ``x`` 轴上的加速度测量值(以 milli-g 为单位)。 - Example: ``accelerometer.get_x()`` +Example: ``accelerometer.get_x()`` - :return: A positive or negative integer depending on direction in the range +/- 2000mg. - """ +:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" ... def get_y() -> int: - """Get the acceleration measurement in the ``y`` axis in milli-g. + """获取 ``y`` 轴上的加速度测量值(以 milli-g 为单位)。 - Example: ``accelerometer.get_y()`` +Example: ``accelerometer.get_y()`` - :return: A positive or negative integer depending on direction in the range +/- 2000mg. - """ +:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" ... def get_z() -> int: - """Get the acceleration measurement in the ``z`` axis in milli-g. + """获取 ``z`` 轴上的加速度测量值(以 milli-g 为单位)。 - Example: ``accelerometer.get_z()`` +Example: ``accelerometer.get_z()`` - :return: A positive or negative integer depending on direction in the range +/- 2000mg. - """ +:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" ... def get_values() -> Tuple[int, int, int]: - """Get the acceleration measurements in all axes at once as a tuple. + """一次获取所有轴上的加速度测量值作为元组。 - Example: ``x, y, z = accelerometer.get_values()`` +Example: ``x, y, z = accelerometer.get_values()`` - :return: a three-element tuple of integers ordered as X, Y, Z, each value a positive or negative integer depending on direction in the range +/- 2000mg - """ +:return: a three-element tuple of integers ordered as X, Y, Z, each value a positive or negative integer depending on direction in the range +/- 2000mg""" ... def get_strength() -> int: - """Get the acceleration measurement of all axes combined, as a positive integer. This is the Pythagorean sum of the X, Y and Z axes. + """以正整数形式获取所有轴组合的加速度测量值。这是 X、Y 和 Z 轴的毕达哥拉斯(Pythagorean)和。 (获取强度) - Example: ``accelerometer.get_strength()`` +Example: ``accelerometer.get_strength()`` - :return: The combined acceleration strength of all the axes, in milli-g. - """ +:return: The combined acceleration strength of all the axes, in milli-g.""" ... def current_gesture() -> str: - """Get the name of the current gesture. + """获取当前手势的名称。 - Example: ``accelerometer.current_gesture()`` +Example: ``accelerometer.current_gesture()`` - 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. +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. - :return: The current gesture - """ +:return: The current gesture""" ... def is_gesture(name: str) -> bool: - """Check if the named gesture is currently active. + """检查命名手势当前是否处于活动状态。 - Example: ``accelerometer.is_gesture('shake')`` +Example: ``accelerometer.is_gesture('shake')`` - 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. +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. - :param name: The gesture name. - :return: ``True`` if the gesture is active, ``False`` otherwise. - """ +:param name: 手势名称。 +:return: ``True`` if the gesture is active, ``False`` otherwise.""" ... def was_gesture(name: str) -> bool: - """Check if the named gesture was active since the last call. + """检查命名手势自上次调用后是否处于活动状态。 - Example: ``accelerometer.was_gesture('shake')`` +Example: ``accelerometer.was_gesture('shake')`` - 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. +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. - :param name: The gesture name. - :return: ``True`` if the gesture was active since the last call, ``False`` otherwise. - """ +:param name: 手势名称。 +:return: ``True`` if the gesture was active since the last call, ``False`` otherwise.""" def get_gestures() -> Tuple[str, ...]: - """Return a tuple of the gesture history. + """返回手势历史的元组。 - Example: ``accelerometer.get_gestures()`` +Example: ``accelerometer.get_gestures()`` - Clears the gesture history before returning. +Clears the gesture history before returning. - Gestures are not updated in the background so there needs to be constant - calls to some accelerometer method to do the gesture detection. Usually - gestures can be detected using a loop with a small :func:`microbit.sleep` delay. +Gestures are not updated in the background so there needs to be constant +calls to some accelerometer method to do the gesture detection. Usually +gestures can be detected using a loop with a small :func:`microbit.sleep` delay. - :return: The history as a tuple, most recent last. - """ +:return: The history as a tuple, most recent last.""" ... def set_range(value: int) -> None: - """Set the accelerometer sensitivity range, in g (standard gravity), to the closest values supported by the hardware, so it rounds to either ``2``, ``4``, or ``8`` g. + """将加速度计灵敏度范围(以 g(标准重力)为单位)设置为硬件支持的最接近的值,因此它会取近似值为 ``2``、``4`` 或 ``8`` g。 (设置范围) - Example: ``accelerometer.set_range(8)`` +Example: ``accelerometer.set_range(8)`` - :param value: New range for the accelerometer, an integer in ``g``. - """ +:param value: 加速度计的新范围,``g`` 中的整数。""" \ No newline at end of file diff --git a/lang/zh-cn/typeshed/stdlib/microbit/audio.pyi b/lang/zh-cn/typeshed/stdlib/microbit/audio.pyi index 3b1e327..3c1d5ea 100644 --- a/lang/zh-cn/typeshed/stdlib/microbit/audio.pyi +++ b/lang/zh-cn/typeshed/stdlib/microbit/audio.pyi @@ -1,160 +1,124 @@ -"""Play sounds using the micro:bit (import ``audio`` for V1 compatibility). -""" - +"""使用 micro:bit 播放声音(导入 ``audio`` 以兼容 V1)。 (音频)""" from ..microbit import MicroBitDigitalPin, Sound, pin0 from typing import ClassVar, Iterable, Union -def play( - source: Union[Iterable[AudioFrame], Sound, SoundEffect], - wait: bool = True, - pin: MicroBitDigitalPin = pin0, - return_pin: Union[MicroBitDigitalPin, None] = None, -) -> None: - """Play a built-in sound, sound effect or custom audio frames. +def play(source: Union[Iterable[AudioFrame], Sound, SoundEffect], wait: bool=True, pin: MicroBitDigitalPin=pin0, return_pin: Union[MicroBitDigitalPin, None]=None) -> None: + """播放内置声音、音效或自定义音频帧。 (播放) - Example: ``audio.play(Sound.GIGGLE)`` +Example: ``audio.play(Sound.GIGGLE)`` - :param source: A built-in ``Sound`` such as ``Sound.GIGGLE``, a ``SoundEffect`` or sample data as an iterable of ``AudioFrame`` objects. - :param wait: If ``wait`` is ``True``, this function will block until the sound is complete. - :param pin: An optional argument to specify the output pin can be used to override the default of ``pin0``. If we do not want any sound to play we can use ``pin=None``. - :param return_pin: Specifies a differential edge connector pin to connect to an external speaker instead of ground. This is ignored for the **V2** revision. - """ +:param source: (来源) 内置的 ``Sound``,例如 ``Sound.GIGGLE``、``SoundEffect`` 或作为 ``AudioFrame`` 的可迭代对象的样本数据。 +:param wait: (等待) 如果 ``wait`` 为 ``True``, 此函数将会阻塞直到声音完成。 +:param pin: (引脚) 可选参数, 用于指定可覆盖默认 ``pin0`` 的输出引脚。 如果不想播放任何声音,可以使用 ``pin=None``。 +:param return_pin: 指定一个差分边缘连接器引脚以连接到外部扬声器而不是接地。对于 **V2** 修订版,这将被忽略。""" def is_playing() -> bool: - """Check whether a sound is playing. + """检查是否在播放声音。 - Example: ``audio.is_playing()`` +Example: ``audio.is_playing()`` - :return: ``True`` if audio is playing, otherwise ``False``.""" +:return: ``True`` if audio is playing, otherwise ``False``.""" ... def stop() -> None: - """Stop all audio playback. + """停止所有音频播放。 (停止) - Example: ``audio.stop()`` - """ +Example: ``audio.stop()``""" ... class SoundEffect: - """A sound effect, composed by a set of parameters configured via the constructor or attributes.""" - + """一种音效,由一组通过构造函数或属性配置的参数组成。 (音效)""" WAVEFORM_SINE: ClassVar[int] - """Sine wave option used for the ``waveform`` parameter.""" - + """用于 ``waveform`` 参数的正弦波选项。 (波形正弦)""" WAVEFORM_SAWTOOTH: ClassVar[int] - """Sawtooth wave option used for the ``waveform`` parameter.""" - + """用于 ``waveform`` 参数的锯齿波选项。 (波形锯齿)""" WAVEFORM_TRIANGLE: ClassVar[int] - """Triangle wave option used for the ``waveform`` parameter.""" - + """用于 ``waveform`` 参数的三角波选项。 (波形三角)""" WAVEFORM_SQUARE: ClassVar[int] - """Square wave option used for the ``waveform`` parameter.""" - + """用于 ``waveform`` 参数的方波选项。 (方波)""" WAVEFORM_NOISE: ClassVar[int] - """Noise option used for the ``waveform`` parameter.""" - + """用于 ``waveform`` 参数的噪声选项。 (波形噪声)""" SHAPE_LINEAR: ClassVar[int] - """Linear interpolation option used for the ``shape`` parameter.""" - + """用于 ``shape`` 参数的线性插值选项。 (形状线性)""" SHAPE_CURVE: ClassVar[int] - """Curve interpolation option used for the ``shape`` parameter.""" - + """用于 ``shape`` 参数的曲线插值选项。 (形状曲线)""" SHAPE_LOG: ClassVar[int] - """Logarithmic interpolation option used for the ``shape`` parameter.""" - + """用于 ``shape`` 参数的对数插值选项。 (形状日志)""" FX_NONE: ClassVar[int] - """No effect option used for the ``fx`` parameter.""" - + """没有用于 ``fx`` 参数的效果选项。 (fx 无)""" FX_TREMOLO: ClassVar[int] - """Tremolo effect option used for the ``fx`` parameter.""" - + """用于 ``fx`` 参数的音量颤音效果选项。 (fx 音量颤音)""" FX_VIBRATO: ClassVar[int] - """Vibrato effect option used for the ``fx`` parameter.""" - + """用于 ``fx`` 参数的音高颤音效果选项。 (fx 音高颤音)""" FX_WARBLE: ClassVar[int] - """Warble effect option used for the ``fx`` parameter.""" - + """用于 ``fx`` 参数的柔和颤音效果选项。 (fx 柔和颤音)""" freq_start: int - """Start frequency in Hertz (Hz), a number between ``0`` and ``9999``""" - + """开始频率用 Hertz (Hz) 表示, 是一个 ``0`` 和 ``9999`` 之间的数字 (开始频率)""" freq_end: int - """End frequency in Hertz (Hz), a number between ``0`` and ``9999``""" - + """结束频率用 Hertz (Hz) 表示, 是一个 ``0`` 和 ``9999`` 之间的数字 (结束频率)""" duration: int - """Duration of the sound in milliseconds, a number between ``0`` and ``9999``""" - + """声音持续时间,以毫秒计, 是一个 ``0`` 和 ``9999`` 之间的数字 (持续)""" vol_start: int - """Start volume value, a number between ``0`` and ``255``""" - + """开始音量值,是一个 ``0`` 和 ``255`` 之间的数字 (开始音量值)""" vol_end: int - """End volume value, a number between ``0`` and ``255``""" - + """结束音量值,是一个 ``0`` 和 ``255`` 之间的数字 (结束音量值)""" waveform: int - """Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise)""" - + """波形类型,是下列值之一: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (随机生成噪音) (波形)""" fx: int - """Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``""" - + """对声音添加效果,下列值之一: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, 或 ``FX_NONE``""" shape: int - """The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``""" - - def __init__( - self, - freq_start: int = 500, - freq_end: int = 2500, - duration: int = 500, - vol_start: int = 255, - vol_end: int = 0, - waveform: int = WAVEFORM_SQUARE, - fx: int = FX_NONE, - shape: int = SHAPE_LOG, - ): - """Create a new sound effect. - - Example: ``my_effect = SoundEffect(duration=1000)`` - - All the parameters are optional, with default values as shown above, and - they can all be modified via attributes of the same name. For example, we - can first create an effect ``my_effect = SoundEffect(duration=1000)``, - and then change its attributes ``my_effect.duration = 500``. - - :param freq_start: Start frequency in Hertz (Hz), a number between ``0`` and ``9999``. - :param freq_end: End frequency in Hertz (Hz), a number between ``0`` and ``9999``. - :param duration: Duration of the sound in milliseconds, a number between ``0`` and ``9999``. - :param vol_start: Start volume value, a number between ``0`` and ``255``. - :param vol_end: End volume value, a number between ``0`` and ``255``. - :param waveform: Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise). - :param fx: Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``. - :param shape: The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``. - """ + """开始频率和结束频率之间的内插曲线类型,不同波形的频率变化速率不同。 以下值之一: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG`` (形状)""" + + def __init__(self, freq_start: int=500, freq_end: int=2500, duration: int=500, vol_start: int=255, vol_end: int=0, waveform: int=WAVEFORM_SQUARE, fx: int=FX_NONE, shape: int=SHAPE_LOG): + """创建新的音效。 + +Example: ``my_effect = SoundEffect(duration=1000)`` + +All the parameters are optional, with default values as shown above, and +they can all be modified via attributes of the same name. For example, we +can first create an effect ``my_effect = SoundEffect(duration=1000)``, +and then change its attributes ``my_effect.duration = 500``. + +:param freq_start: (开始频率) 开始频率用 Hertz (Hz) 表示, 是一个 ``0`` 和 ``9999`` 之间的数字. +:param freq_end: (结束频率) 结束频率用 Hertz (Hz) 表示, 是一个 ``0`` 和 ``9999`` 之间的数字. +:param duration: (持续) 声音持续时间,以毫秒计, 是一个 ``0`` 和 ``9999`` 之间的数字. +:param vol_start: (开始音量值) 开始音量值,是一个 ``0`` 和 ``255`` 之间的数字. +:param vol_end: (结束音量值) 结束音量值,是一个 ``0`` 和 ``255`` 之间的数字. +:param waveform: (波形) 波形类型,是下列值之一: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (随机生成噪音). +:param fx: 对声音添加效果,下列值之一: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, 或 ``FX_NONE``. +:param shape: (形状) 开始频率和结束频率之间的内插曲线类型,不同波形的频率变化速度不同。 以下值之一: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``.""" + def copy(self) -> SoundEffect: - """Create a copy of this ``SoundEffect``. + """创建此 ``SoundEffect`` 的副本。 (复制) - Example: ``sound_2 = sound_1.copy()`` +Example: ``sound_2 = sound_1.copy()`` - :return: A copy of the SoundEffect. - """ +:return: A copy of the SoundEffect.""" class AudioFrame: - """An ``AudioFrame`` object is a list of 32 samples each of which is a unsigned byte - (whole number between 0 and 255). + """``AudioFrame`` 对象是 一个包含 32 个样本的列表,每个样本都是一个无符号字节 +(0 到 255 之间的整数)。 (音频帧) - It takes just over 4 ms to play a single frame. +It takes just over 4 ms to play a single frame. - Example:: +Example:: - frame = AudioFrame() - for i in range(len(frame)): - frame[i] = 252 - i * 8 - """ + frame = AudioFrame() + for i in range(len(frame)): + frame[i] = 252 - i * 8""" def copyfrom(self, other: AudioFrame) -> None: - """Overwrite the data in this ``AudioFrame`` with the data from another ``AudioFrame`` instance. + """用其他 ``AudioFrame`` 实例中的数据覆盖此 ``AudioFrame`` 中的数据。 (复制) + +Example: ``my_frame.copyfrom(source_frame)`` + +:param other: (其他) 从 ``AudioFrame`` 实例中复制数据。""" + + def __len__(self) -> int: + ... - Example: ``my_frame.copyfrom(source_frame)`` + def __setitem__(self, key: int, value: int) -> None: + ... - :param other: ``AudioFrame`` instance from which to copy the data. - """ - def __len__(self) -> int: ... - def __setitem__(self, key: int, value: int) -> None: ... - def __getitem__(self, key: int) -> int: ... + def __getitem__(self, key: int) -> int: + ... \ No newline at end of file diff --git a/lang/zh-cn/typeshed/stdlib/microbit/compass.pyi b/lang/zh-cn/typeshed/stdlib/microbit/compass.pyi index c74a47b..be71499 100644 --- a/lang/zh-cn/typeshed/stdlib/microbit/compass.pyi +++ b/lang/zh-cn/typeshed/stdlib/microbit/compass.pyi @@ -1,78 +1,70 @@ -"""Use the built-in compass. -""" +"""使用内置罗盘。 (罗盘)""" def calibrate() -> None: - """Starts the calibration process. + """开始校准过程。 (校准) - Example: ``compass.calibrate()`` +Example: ``compass.calibrate()`` - 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. - """ +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: - """Check is the compass is calibrated. + """检查罗盘是否已校准。 - Example: ``compass.is_calibrated()`` +Example: ``compass.is_calibrated()`` - :return: ``True`` if the compass has been successfully calibrated, ``False`` otherwise. - """ +:return: ``True`` if the compass has been successfully calibrated, ``False`` otherwise.""" ... def clear_calibration() -> None: - """Undoes the calibration, making the compass uncalibrated again. + """取消校准,将罗盘恢复到未校准状态。 - Example: ``compass.clear_calibration()`` - """ +Example: ``compass.clear_calibration()``""" ... def get_x() -> int: - """Get the magnetic field strength on the ``x`` axis. + """获取 ``x`` 轴上的磁场强度。 - Example: ``compass.get_x()`` +Example: ``compass.get_x()`` - Call ``calibrate`` first or the results will be inaccurate. +Call ``calibrate`` first or the results will be inaccurate. - :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. - """ +:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" ... def get_y() -> int: - """Get the magnetic field strength on the ``y`` axis. + """获取 ``y`` 轴上的磁场强度。 - Example: ``compass.get_y()`` +Example: ``compass.get_y()`` - Call ``calibrate`` first or the results will be inaccurate. +Call ``calibrate`` first or the results will be inaccurate. - :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. - """ +:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" ... def get_z() -> int: - """Get the magnetic field strength on the ``z`` axis. + """获取 ``z`` 轴上的磁场强度。 - Example: ``compass.get_z()`` +Example: ``compass.get_z()`` - Call ``calibrate`` first or the results will be inaccurate. +Call ``calibrate`` first or the results will be inaccurate. - :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. - """ +:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" ... def heading() -> int: - """Get the compass heading. + """获取罗盘指向。 - Example: ``compass.heading()`` +Example: ``compass.heading()`` - :return: An integer in the range from 0 to 360, representing the angle in degrees, clockwise, with north as 0. - """ +:return: An integer in the range from 0 to 360, representing the angle in degrees, clockwise, with north as 0.""" ... def get_field_strength() -> int: - """Get the magnitude of the magnetic field around the device. + """获取设备周围磁场的强度。 (获取磁场强度) - Example: ``compass.get_field_strength()`` +Example: ``compass.get_field_strength()`` - :return: An integer indication of the magnitude of the magnetic field in nano tesla.""" - ... +:return: An integer indication of the magnitude of the magnetic field in nano tesla.""" + ... \ No newline at end of file diff --git a/lang/zh-cn/typeshed/stdlib/microbit/display.pyi b/lang/zh-cn/typeshed/stdlib/microbit/display.pyi index aa4013e..d5490e9 100644 --- a/lang/zh-cn/typeshed/stdlib/microbit/display.pyi +++ b/lang/zh-cn/typeshed/stdlib/microbit/display.pyi @@ -1,115 +1,92 @@ -"""Show text, images and animations on the 5×5 LED display. -""" - +"""在5×5的 LED 显示屏上显示文字、图像和动画。 (显示)""" from ..microbit import Image from typing import Union, overload, Iterable def get_pixel(x: int, y: int) -> int: - """Get the brightness of the LED at column ``x`` and row ``y``. + """获取第``y``行第``x``列的 LED 亮度。 - Example: ``display.get_pixel(0, 0)`` +Example: ``display.get_pixel(0, 0)`` - :param x: The display column (0..4) - :param y: The display row (0..4) - :return: A number between 0 (off) and 9 (bright) - """ +:param x: 显示屏的列(0..4) +:param y: 显示行 (0..4) +:return: A number 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``. + """设置在 ``x`` 列和 ``y`` 行的 LED 的亮度。 - Example: ``display.set_pixel(0, 0, 9)`` +Example: ``display.set_pixel(0, 0, 9)`` - :param x: The display column (0..4) - :param y: The display row (0..4) - :param value: The brightness between 0 (off) and 9 (bright) - """ +:param x: 显示屏的列(0..4) +:param y: 显示行 (0..4) +:param value: 在 0 (关闭) 和 9 (亮) 之间的亮度""" ... def clear() -> None: - """Set the brightness of all LEDs to 0 (off). + """将所有 LED 的亮度设置为 0(关闭)。 (清除) - Example: ``display.clear()`` - """ +Example: ``display.clear()``""" ... -def show( - image: Union[str, float, int, Image, Iterable[Image]], - delay: int = 400, - wait: bool = True, - loop: bool = False, - clear: bool = False, -) -> None: - """Shows images, letters or digits on the LED display. +def show(image: Union[str, float, int, Image, Iterable[Image]], delay: int=400, wait: bool=True, loop: bool=False, clear: bool=False) -> None: + """在 LED 显示屏上显示图像、字母或数字。 (显示) - Example: ``display.show(Image.HEART)`` +Example: ``display.show(Image.HEART)`` - When ``image`` is an image or a list of images then each image is displayed in turn. - If ``image`` is a string or number, each letter or digit is displayed in turn. +When ``image`` is an image or a list of images then each image is displayed in turn. +If ``image`` is a string or number, each letter or digit is displayed in turn. - :param image: A string, number, image or list of images to show. - :param delay: Each letter, digit or image is shown with ``delay`` milliseconds between them. - :param wait: If ``wait`` is ``True``, this function will block until the animation is finished, otherwise the animation will happen in the background. - :param loop: If ``loop`` is ``True``, the animation will repeat forever. - :param clear: If ``clear`` is ``True``, the display will be cleared after the sequence has finished. +:param image: (图像) 要显示的一个字符串、数字、图像或图像列表。 +:param delay: (延迟) 每个字母、数字或图像之间显示的间隔时间为 ``delay`` 毫秒。 +:param wait: (等待) 如果 ``wait`` 为 ``True``,此函数将阻塞直到动画完成,否则动画将在后台发生。 +:param loop: 如果 ``loop`` 为 ``True``, 动画将永远重复。 +:param clear: (清除) 如果 ``clear`` 是 ``True``, 则显示将在序列完成后被清除。 - The ``wait``, ``loop`` and ``clear`` arguments must be specified using their keyword. - """ +The ``wait``, ``loop`` and ``clear`` arguments must be specified using their keyword.""" ... -def scroll( - text: Union[str, float, int], - delay: int = 150, - wait: bool = True, - loop: bool = False, - monospace: bool = False, -) -> None: - """Scrolls a number or text on the LED display. - - Example: ``display.scroll('micro:bit')`` - - :param text: The string to scroll. If ``text`` is an integer or float it is first converted to a string using ``str()``. - :param delay: The ``delay`` parameter controls how fast the text is scrolling. - :param wait: If ``wait`` is ``True``, this function will block until the animation is finished, otherwise the animation will happen in the background. - :param loop: If ``loop`` is ``True``, the animation will repeat forever. - :param monospace: 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. - - The ``wait``, ``loop`` and ``monospace`` arguments must be specified - using their keyword. - """ +def scroll(text: Union[str, float, int], delay: int=150, wait: bool=True, loop: bool=False, monospace: bool=False) -> None: + """在 LED 显示屏上滚动一个数字或文本。 (滚动) + +Example: ``display.scroll('micro:bit')`` + +:param text: (文本) 要滚动的字符串。如果 ``text`` 是整数或浮点数,则首先使用 ``str()`` 将其转换为字符串。 +:param delay: (延迟) ``delay`` 参数控制文本滚动的速度。 +:param wait: (等待) 如果 ``wait`` 为 ``True``,此函数将阻塞直到动画完成,否则动画将发生在后台。 +:param loop: 如果 ``loop`` 为 ``True``, 动画将永远重复。 +:param monospace: (等宽) 如果 ``monospace`` 为 ``True``,则字符的宽度都将占用 5 个像素列,否则在滚动时每个字符之间将恰好有 1 个空白像素列。 + +The ``wait``, ``loop`` and ``monospace`` arguments must be specified +using their keyword.""" ... def on() -> None: - """Turn on the LED display. + """打开 LED 显示屏。 (打开) - Example: ``display.on()`` - """ +Example: ``display.on()``""" ... def off() -> None: - """Turn off the LED display (disabling the display allows you to re-use the GPIO pins for other purposes). + """关闭 LED 显示屏(禁用显示屏可让您将 GPIO 引脚重新用于其他用途)。 (关闭) - Example: ``display.off()`` - """ +Example: ``display.off()``""" ... def is_on() -> bool: - """Check whether the LED display is enabled. + """检查 LED 显示屏是否启用。 - Example: ``display.is_on()`` +Example: ``display.is_on()`` - :return: ``True`` if the display is on, otherwise returns ``False``. - """ +:return: ``True`` if the display is on, otherwise returns ``False``.""" ... def read_light_level() -> int: - """Read the light level. + """读取亮度。 - Example: ``display.read_light_level()`` +Example: ``display.read_light_level()`` - Uses the display's LEDs in reverse-bias mode to sense the amount of light - falling on the display. +Uses the display's LEDs in reverse-bias mode to sense the amount of light +falling on the display. - :return: An integer between 0 and 255 representing the light level, with larger meaning more light. - """ - ... +:return: An integer between 0 and 255 representing the light level, with larger meaning more light.""" + ... \ No newline at end of file diff --git a/lang/zh-cn/typeshed/stdlib/microbit/i2c.pyi b/lang/zh-cn/typeshed/stdlib/microbit/i2c.pyi index df26efa..5ad7530 100644 --- a/lang/zh-cn/typeshed/stdlib/microbit/i2c.pyi +++ b/lang/zh-cn/typeshed/stdlib/microbit/i2c.pyi @@ -1,57 +1,49 @@ -"""Communicate with devices using the I²C bus protocol. -""" - +"""使用 I²C 总线协议与设备通信。 (i2c总线协议)""" from _typeshed import ReadableBuffer from ..microbit import MicroBitDigitalPin, pin19, pin20 from typing import List -def init( - freq: int = 100000, sda: MicroBitDigitalPin = pin20, scl: MicroBitDigitalPin = pin19 -) -> None: - """Re-initialize a peripheral. +def init(freq: int=100000, sda: MicroBitDigitalPin=pin20, scl: MicroBitDigitalPin=pin19) -> None: + """重新初始化外设。 - Example: ``i2c.init()`` +Example: ``i2c.init()`` - :param freq: clock frequency - :param sda: ``sda`` pin (default 20) - :param scl: ``scl`` pin (default 19) +:param freq: 时钟频率 +:param sda: (SDA引脚) ``sda`` 引脚(默认 20) +:param scl: (SCL引脚) ``scl`` 引脚(默认 19) - On a micro:bit V1 board, changing the I²C pins from defaults will make - the accelerometer and compass stop working, as they are connected - internally to those pins. This warning does not apply to the **V2** - revision of the micro:bit as this has `separate I²C lines `_ - for the motion sensors and the edge connector. - """ +On a micro:bit V1 board, changing the I²C pins from defaults will make +the accelerometer and compass stop working, as they are connected +internally to those pins. This warning does not apply to the **V2** +revision of the micro:bit as this has `separate I²C lines `_ +for the motion sensors and the edge connector.""" ... def scan() -> List[int]: - """Scan the bus for devices. + """扫描总线以查找设备。 (扫描) - Example: ``i2c.scan()`` +Example: ``i2c.scan()`` - :return: A list of 7-bit addresses corresponding to those devices that responded to the scan. - """ +:return: A list of 7-bit addresses corresponding to those devices that responded to the scan.""" ... -def read(addr: int, n: int, repeat: bool = False) -> bytes: - """Read bytes from a device. +def read(addr: int, n: int, repeat: bool=False) -> bytes: + """从设备读取字节. (读取) - Example: ``i2c.read(0x50, 64)`` +Example: ``i2c.read(0x50, 64)`` - :param addr: The 7-bit address of the device - :param n: The number of bytes to read - :param repeat: If ``True``, no stop bit will be sent - :return: The bytes read - """ +:param addr: (地址) 设备的 7 位地址 +:param n: 要读取的字节数 +:param repeat: 如果为 ``True``,则不发送停止位 +:return: The bytes read""" ... -def write(addr: int, buf: ReadableBuffer, repeat: bool = False) -> None: - """Write bytes to a device. +def write(addr: int, buf: ReadableBuffer, repeat: bool=False) -> None: + """将字节写入设备。 (写入) - Example: ``i2c.write(0x50, bytes([1, 2, 3]))`` +Example: ``i2c.write(0x50, bytes([1, 2, 3]))`` - :param addr: The 7-bit address of the device - :param buf: A buffer containing the bytes to write - :param repeat: If ``True``, no stop bit will be sent - """ - ... +:param addr: (地址) 设备的 7 位地址 +:param buf: (缓冲区) 包含要写入的字节的缓冲区 +:param repeat: 如果为 ``True``,则不发送停止位""" + ... \ No newline at end of file diff --git a/lang/zh-cn/typeshed/stdlib/microbit/microphone.pyi b/lang/zh-cn/typeshed/stdlib/microbit/microphone.pyi index 68e8f3a..44db995 100644 --- a/lang/zh-cn/typeshed/stdlib/microbit/microphone.pyi +++ b/lang/zh-cn/typeshed/stdlib/microbit/microphone.pyi @@ -1,70 +1,62 @@ -"""Respond to sound using the built-in microphone (V2 only). -""" - +"""使用内置麦克风响应声音(仅限 V2)。 (麦克风)""" from typing import Optional, Tuple from ..microbit import SoundEvent def current_event() -> Optional[SoundEvent]: - """Get the last recorded sound event + """获取最后录制的声音事件 - Example: ``microphone.current_event()`` +Example: ``microphone.current_event()`` - :return: The event, ``SoundEvent('loud')`` or ``SoundEvent('quiet')``. - """ +:return: The event, ``SoundEvent('loud')`` or ``SoundEvent('quiet')``.""" ... def was_event(event: SoundEvent) -> bool: - """Check if a sound was heard at least once since the last call. + """检查自上次通话后是否至少听到一次声音。 (曾经是事件) - Example: ``microphone.was_event(SoundEvent.LOUD)`` +Example: ``microphone.was_event(SoundEvent.LOUD)`` - This call clears the sound history before returning. +This call clears the sound history before returning. - :param event: The event to check for, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET`` - :return: ``True`` if sound was heard at least once since the last call, otherwise ``False``. - """ +:param event: (事件) 要检查的事件,例如 ``SoundEvent.LOUD`` 或 ``SoundEvent.QUIET`` +:return: ``True`` if sound was heard at least once since the last call, otherwise ``False``.""" ... def is_event(event: SoundEvent) -> bool: - """Check the most recent sound event detected. + """检查最近检测到的声音事件。 (是事件) - Example: ``microphone.is_event(SoundEvent.LOUD)`` +Example: ``microphone.is_event(SoundEvent.LOUD)`` - This call does not clear the sound event history. +This call does not clear the sound event history. - :param event: The event to check for, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET`` - :return: ``True`` if sound was the most recent heard, ``False`` otherwise. - """ +:param event: (事件) 要检查的事件,例如 ``SoundEvent.LOUD`` 或 ``SoundEvent.QUIET`` +:return: ``True`` if sound was the most recent heard, ``False`` otherwise.""" ... def get_events() -> Tuple[SoundEvent, ...]: - """Get the sound event history as a tuple. + """以元组的形式获取声音事件历史。 - Example: ``microphone.get_events()`` +Example: ``microphone.get_events()`` - This call clears the sound history before returning. +This call clears the sound history before returning. - :return: A tuple of the event history with the most recent event last. - """ +:return: A tuple of the event history with the most recent event last.""" ... def set_threshold(event: SoundEvent, value: int) -> None: - """Set the threshold for a sound event. + """设置声音事件的阈值。 - Example: ``microphone.set_threshold(SoundEvent.LOUD, 250)`` +Example: ``microphone.set_threshold(SoundEvent.LOUD, 250)`` - A high threshold means the event will only trigger if the sound is very loud (>= 250 in the example). +A high threshold means the event will only trigger if the sound is very loud (>= 250 in the example). - :param event: A sound event, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET``. - :param value: The threshold level in the range 0-255. - """ +:param event: (事件) 声音事件,如``SoundEvent.LOUD``或``SoundEvent.QUIET``。 +:param value: 范围为0到255的阈值水平。""" ... def sound_level() -> int: - """Get the sound pressure level. + """获取声压级。 (音量) - Example: ``microphone.sound_level()`` +Example: ``microphone.sound_level()`` - :return: A representation of the sound pressure level in the range 0 to 255. - """ - ... +:return: A representation of the sound pressure level in the range 0 to 255.""" + ... \ No newline at end of file diff --git a/lang/zh-cn/typeshed/stdlib/microbit/speaker.pyi b/lang/zh-cn/typeshed/stdlib/microbit/speaker.pyi index 5a74a4d..cdc0992 100644 --- a/lang/zh-cn/typeshed/stdlib/microbit/speaker.pyi +++ b/lang/zh-cn/typeshed/stdlib/microbit/speaker.pyi @@ -1,18 +1,15 @@ -"""Control the built-in speaker (V2 only). -""" +"""控制内置扬声器(仅限 V2)。 (扬声器\u200b\u200b\u200b\u200b)""" def off() -> None: - """Turn the speaker off. + """关闭扬声器\u200b\u200b\u200b\u200b。 (关闭) - Example: ``speaker.off()`` +Example: ``speaker.off()`` - This does not disable sound output to an edge connector pin. - """ +This does not disable sound output to an edge connector pin.""" ... def on() -> None: - """Turn the speaker on. + """打开扬声器\u200b\u200b\u200b\u200b。 (打开) - Example: ``speaker.on()`` - """ - ... +Example: ``speaker.on()``""" + ... \ No newline at end of file diff --git a/lang/zh-cn/typeshed/stdlib/microbit/spi.pyi b/lang/zh-cn/typeshed/stdlib/microbit/spi.pyi index 09c4046..bbca0c1 100644 --- a/lang/zh-cn/typeshed/stdlib/microbit/spi.pyi +++ b/lang/zh-cn/typeshed/stdlib/microbit/spi.pyi @@ -1,60 +1,47 @@ -"""Communicate with devices using the serial peripheral interface (SPI) bus. -""" - +"""通过串行外设接口(SPI)总线与设备通信。 (串行外围接口(SPI))""" from _typeshed import ReadableBuffer, WriteableBuffer from ..microbit import pin13, pin14, pin15, MicroBitDigitalPin -def init( - baudrate: int = 1000000, - bits: int = 8, - mode: int = 0, - sclk: MicroBitDigitalPin = pin13, - mosi: MicroBitDigitalPin = pin15, - miso: MicroBitDigitalPin = pin14, -) -> None: - """Initialize SPI communication. - - Example: ``spi.init()`` - - For correct communication, the parameters have to be the same on both communicating devices. - - :param baudrate: The speed of communication. - :param bits: The width in bits of each transfer. Currently only ``bits=8`` is supported. However, this may change in the future. - :param mode: Determines the combination of clock polarity and phase - `see online table `_. - :param sclk: sclk pin (default 13) - :param mosi: mosi pin (default 15) - :param miso: miso pin (default 14) - """ +def init(baudrate: int=1000000, bits: int=8, mode: int=0, sclk: MicroBitDigitalPin=pin13, mosi: MicroBitDigitalPin=pin15, miso: MicroBitDigitalPin=pin14) -> None: + """初始化串行外设接口(SPI )通信。 + +Example: ``spi.init()`` + +For correct communication, the parameters have to be the same on both communicating devices. + +:param baudrate: (波特率) 通信速度。 +:param bits: (位) 每次传输的宽度(单位:bit)。目前只支持 ``bits=8``,但是未来可能支持其他宽度。 +:param mode: (模式) 决定时钟极性和相位的组合——“参见在线表格”。 +:param sclk: (SCLK) sclk 引脚(默认 13) +:param mosi: (MOSI) mosi 引脚(默认 15) +:param miso: (MISO) MISO引脚(默认值14)""" ... -def read(nbytes: int, out: int = 0) -> bytes: - """Read at most ``nbytes`` while continuously writing the single byte given by ``out``. +def read(nbytes: int, out: int=0) -> bytes: + """读取字节数。 (读取) - Example: ``spi.read(64)`` +Example: ``spi.read(64)`` - :param nbytes: Maximum number of bytes to read. - :param out: The byte value to write (default 0). - :return: The bytes read. - """ +:param nbytes: (字节数) 要读取的最大字节数。 +:param out: (写出) The byte value to write (default 0). +:return: The bytes read.""" ... def write(buffer: ReadableBuffer) -> None: - """Write bytes to the bus. + """将字节写入总线。 (写入) - Example: ``spi.write(bytes([1, 2, 3]))`` +Example: ``spi.write(bytes([1, 2, 3]))`` - :param buffer: A buffer to read data from. - """ +:param buffer: (缓冲区) 读取数据的缓冲区。""" ... def write_readinto(out: WriteableBuffer, in_: ReadableBuffer) -> None: - """Write the ``out`` buffer to the bus and read any response into the ``in_`` buffer. + """将 ``out`` 缓冲区写入总线,并将任何响应读入 ``in_`` 缓冲区。 (写并读入) - Example: ``spi.write_readinto(out_buffer, in_buffer)`` +Example: ``spi.write_readinto(out_buffer, in_buffer)`` - The length of the buffers should be the same. The buffers can be the same object. +The length of the buffers should be the same. The buffers can be the same object. - :param out: The buffer to write any response to. - :param in_: The buffer to read data from. - """ - ... +:param out: (写出) 写入任何响应的缓冲区。 +:param in_: (读入) 读取数据的缓冲区。""" + ... \ No newline at end of file diff --git a/lang/zh-cn/typeshed/stdlib/microbit/uart.pyi b/lang/zh-cn/typeshed/stdlib/microbit/uart.pyi index 2ab650f..63a5bed 100644 --- a/lang/zh-cn/typeshed/stdlib/microbit/uart.pyi +++ b/lang/zh-cn/typeshed/stdlib/microbit/uart.pyi @@ -1,96 +1,79 @@ -"""Communicate with a device using a serial interface. -""" - +"""使用串行接口与设备通信。 (通用异步收发器(UART))""" from _typeshed import WriteableBuffer from ..microbit import MicroBitDigitalPin from typing import Optional, Union - ODD: int -"""Odd parity""" - +"""奇校验 (奇数)""" EVEN: int -"""Even parity""" - -def init( - baudrate: int = 9600, - bits: int = 8, - parity: Optional[int] = None, - stop: int = 1, - tx: Optional[MicroBitDigitalPin] = None, - rx: Optional[MicroBitDigitalPin] = None, -) -> None: - """Initialize serial communication. - - Example: ``uart.init(115200, tx=pin0, rx=pin1)`` - - :param baudrate: The speed of communication. - :param bits: The size of bytes being transmitted. micro:bit only supports 8. - :param parity: How parity is checked, ``None``, ``uart.ODD`` or ``uart.EVEN``. - :param stop: The number of stop bits, has to be 1 for micro:bit. - :param tx: Transmitting pin. - :param rx: Receiving pin. - - 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. - - For more details see `the online documentation `_. - """ +"""偶校验 (偶数)""" + +def init(baudrate: int=9600, bits: int=8, parity: Optional[int]=None, stop: int=1, tx: Optional[MicroBitDigitalPin]=None, rx: Optional[MicroBitDigitalPin]=None) -> None: + """初始化串行通信。 + +Example: ``uart.init(115200, tx=pin0, rx=pin1)`` + +:param baudrate: (波特率) 通信速度。 +:param bits: (位数) 正在传输的字节大小。micro:bit 仅支持 8 字节。 +:param parity: (奇偶校验) 如何检查奇偶性,``None``、``uart.ODD`` 或 ``uart.EVEN``。 +:param stop: (停止) 停止位的数量,对于 micro:bit,必须为 1。 +:param tx: (发送引脚) 传输引脚。 +:param rx: (接收引脚) 接收引脚。 + +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. + +For more details see `the online documentation `_.""" ... def any() -> bool: - """Check if any data is waiting. + """检查是否有任何数据正在等待。 (任何) - Example: ``uart.any()`` +Example: ``uart.any()`` - :return: ``True`` if any data is waiting, else ``False``. - """ +:return: ``True`` if any data is waiting, else ``False``.""" ... -def read(nbytes: Optional[int] = None) -> Optional[bytes]: - """Read bytes. +def read(nbytes: Optional[int]=None) -> Optional[bytes]: + """读取字节。 (读取) - Example: ``uart.read()`` +Example: ``uart.read()`` - :param nbytes: If ``nbytes`` is specified then read at most that many bytes, otherwise read as many bytes as possible - :return: A bytes object or ``None`` on timeout - """ +:param nbytes: (字节数) 如果指定了 ``nbytes``,则最多读取那么多字节,否则读取尽可能多的字节 +:return: A bytes object or ``None`` on timeout""" ... -def readinto(buf: WriteableBuffer, nbytes: Optional[int] = None) -> Optional[int]: - """Read bytes into the ``buf``. +def readinto(buf: WriteableBuffer, nbytes: Optional[int]=None) -> Optional[int]: + """读取字节到 ``buf``。 (读入) - Example: ``uart.readinto(input_buffer)`` +Example: ``uart.readinto(input_buffer)`` - :param buf: The buffer to write to. - :param nbytes: If ``nbytes`` is specified then read at most that many bytes, otherwise read ``len(buf)`` bytes. - :return: number of bytes read and stored into ``buf`` or ``None`` on timeout. - """ +:param buf: (缓冲区) 要写入的缓存。 +:param nbytes: (字节数) 如果指定了 ``nbytes``,则最多读取那么多字节,否则读取 ``len(buf)`` 个字节。 +:return: number of bytes read and stored into ``buf`` or ``None`` on timeout.""" ... def readline() -> Optional[bytes]: - """Read a line, ending in a newline character. + """读取一行,以换行符结尾。 (读取一行) - Example: ``uart.readline()`` +Example: ``uart.readline()`` - :return: The line read or ``None`` on timeout. The newline character is included in the returned bytes. - """ +:return: The line read or ``None`` on timeout. The newline character is included in the returned bytes.""" ... def write(buf: Union[bytes, str]) -> Optional[int]: - """Write a buffer to the bus. + """将缓冲区写入总线。 (写入) - Example: ``uart.write('hello world')`` +Example: ``uart.write('hello world')`` - :param buf: A bytes object or a string. - :return: The number of bytes written, or ``None`` on timeout. +:param buf: (缓冲区) 一个字节对象或一个字符串。 +:return: The number of bytes written, or ``None`` on timeout. - Examples:: +Examples:: - uart.write('hello world') - uart.write(b'hello world') - uart.write(bytes([1, 2, 3])) - """ - ... + uart.write('hello world') + uart.write(b'hello world') + uart.write(bytes([1, 2, 3]))""" + ... \ No newline at end of file diff --git a/lang/zh-cn/typeshed/stdlib/micropython.pyi b/lang/zh-cn/typeshed/stdlib/micropython.pyi index 7a6079f..8d63617 100644 --- a/lang/zh-cn/typeshed/stdlib/micropython.pyi +++ b/lang/zh-cn/typeshed/stdlib/micropython.pyi @@ -1,144 +1,131 @@ -"""MicroPython internals.""" - +"""MicroPython 内设。 (MicroPython)""" from typing import Any, TypeVar, overload - -_T = TypeVar("_T") +_T = TypeVar('_T') def const(expr: _T) -> _T: - """Used to declare that the expression is a constant so that the compiler can - optimise it. + """用于声明表达式是一个常量,以便编译器可以优化它。 (常数) - The use of this function should be as follows:: +The use of this function should be as follows:: - from micropython import const - CONST_X = const(123) - CONST_Y = const(2 * CONST_X + 1) + from micropython import const + CONST_X = const(123) + CONST_Y = const(2 * CONST_X + 1) - Constants declared this way are still accessible as global variables from - outside the module they are declared in. On the other hand, if a constant - begins with an underscore then it is hidden, it is not available as a - global variable, and does not take up any memory during execution. +Constants declared this way are still accessible as global variables from +outside the module they are declared in. On the other hand, if a constant +begins with an underscore then it is hidden, it is not available as a +global variable, and does not take up any memory during execution. - :param expr: A constant expression. - """ +:param expr: (表达式) 一个常量表达式。""" ... @overload def opt_level() -> int: - """Get the current optimisation level for the compilation of scripts. + """获取脚本编译的当前优化级别。 (优化级别) - Example: ``micropython.opt_level()`` +Example: ``micropython.opt_level()`` - The optimisation level controls the following compilation features: +The optimisation level controls the following compilation features: - - Assertions: at level 0 assertion statements are enabled and compiled - into the bytecode; at levels 1 and higher assertions are not compiled. +- Assertions: at level 0 assertion statements are enabled and compiled + into the bytecode; at levels 1 and higher assertions are not compiled. - - Built-in ``__debug__`` variable: at level 0 this variable expands to - True; at levels 1 and higher it expands to False. +- Built-in ``__debug__`` variable: at level 0 this variable expands to + True; at levels 1 and higher it expands to False. - - Source-code line numbers: at levels 0, 1 and 2 source-code line number - are stored along with the bytecode so that exceptions can report the - line number they occurred at; at levels 3 and higher line numbers are - not stored. +- Source-code line numbers: at levels 0, 1 and 2 source-code line number + are stored along with the bytecode so that exceptions can report the + line number they occurred at; at levels 3 and higher line numbers are + not stored. - :return: An integer representing the current level. - """ +:return: An integer representing the current level.""" ... @overload def opt_level(level: int) -> None: - """Sets the optimisation level for subsequent compilation of scripts. + """设置后续脚本编译的优化级别。 (优化级别) - Example: ``micropython.opt_level(1)`` +Example: ``micropython.opt_level(1)`` - The optimisation level controls the following compilation features: +The optimisation level controls the following compilation features: - - Assertions: at level 0 assertion statements are enabled and compiled - into the bytecode; at levels 1 and higher assertions are not compiled. +- Assertions: at level 0 assertion statements are enabled and compiled + into the bytecode; at levels 1 and higher assertions are not compiled. - - Built-in ``__debug__`` variable: at level 0 this variable expands to - True; at levels 1 and higher it expands to False. +- Built-in ``__debug__`` variable: at level 0 this variable expands to + True; at levels 1 and higher it expands to False. - - Source-code line numbers: at levels 0, 1 and 2 source-code line number - are stored along with the bytecode so that exceptions can report the - line number they occurred at; at levels 3 and higher line numbers are - not stored. +- Source-code line numbers: at levels 0, 1 and 2 source-code line number + are stored along with the bytecode so that exceptions can report the + line number they occurred at; at levels 3 and higher line numbers are + not stored. - The default optimisation level is usually level 0. +The default optimisation level is usually level 0. - :param level: An integer optimisation level. - """ +:param level: (级别) 整数优化级别。""" ... -def mem_info(verbose: Any = None) -> None: - """Print information about currently used memory. +def mem_info(verbose: Any=None) -> None: + """打印与当前使用内存相关的信息。 - Example: ``micropython.mem_info()`` +Example: ``micropython.mem_info()`` - :param verbose: If the ``verbose`` argument is given then extra information is printed. - """ +:param verbose: (详细) 如果给出 ``verbose`` 参数,则打印额外信息。""" ... -def qstr_info(verbose: Any = None) -> None: - """Print information about currently interned strings. +def qstr_info(verbose: Any=None) -> None: + """打印与当前驻留字符串相关的信息。 (字符串信息) - Example: ``micropython.qstr_info()`` +Example: ``micropython.qstr_info()`` - :param verbose: If the ``verbose`` argument is given then extra information is printed. +:param verbose: (详细) 如果给出 ``verbose`` 参数,则打印额外信息。 - The information that is printed is implementation dependent, but currently - includes the number of interned strings and the amount of RAM they use. In - verbose mode it prints out the names of all RAM-interned strings. - """ +The information that is printed is implementation dependent, but currently +includes the number of interned strings and the amount of RAM they use. In +verbose mode it prints out the names of all RAM-interned strings.""" ... def stack_use() -> int: - """Return an integer representing the current amount of stack that is being - used. + """返回一个整数,来表示当前正在使用的堆栈数量。 (堆栈使用) - Example: ``micropython.stack_use()`` +Example: ``micropython.stack_use()`` - The absolute value of this is not particularly useful, rather it - should be used to compute differences in stack usage at different points. +The absolute value of this is not particularly useful, rather it +should be used to compute differences in stack usage at different points. - :return: An integer representing current stack use. - """ +:return: An integer representing current stack use.""" ... def heap_lock() -> None: - """Lock the heap. + """锁定堆。 (锁住堆) - Example: ``micropython.heap_lock()`` +Example: ``micropython.heap_lock()`` - When locked no memory allocation can occur and a ``MemoryError`` will be - raised if any heap allocation is attempted. - """ +When locked no memory allocation can occur and a ``MemoryError`` will be +raised if any heap allocation is attempted.""" ... def heap_unlock() -> None: - """Unlock the heap. + """解锁堆。 (解锁堆) - Example: ``micropython.heap_unlock()`` +Example: ``micropython.heap_unlock()`` - When locked no memory allocation can occur and a ``MemoryError`` will be - raised if any heap allocation is attempted. - """ +When locked no memory allocation can occur and a ``MemoryError`` will be +raised if any heap allocation is attempted.""" ... def kbd_intr(chr: int) -> None: - """Set the character that will raise a ``KeyboardInterrupt`` exception. + """设置将引发``KeyboardInterrupt``异常的字符。 (键盘中断) - Example: ``micropython.kbd_intr(-1)`` +Example: ``micropython.kbd_intr(-1)`` - :param chr: Character code to raise the interrupt or -1 to disable capture of Ctrl-C. +:param chr: (字符) 用于提高中断的字符代码;或者-1,用于禁止捕获 Ctrl-C。 - By default this is set to 3 during script execution, corresponding to Ctrl-C. - Passing -1 to this function will disable capture of Ctrl-C, and passing 3 - will restore it. +By default this is set to 3 during script execution, corresponding to Ctrl-C. +Passing -1 to this function will disable capture of Ctrl-C, and passing 3 +will restore it. - This function can be used to prevent the capturing of Ctrl-C on the - incoming stream of characters that is usually used for the REPL, in case - that stream is used for other purposes. - """ - ... +This function can be used to prevent the capturing of Ctrl-C on the +incoming stream of characters that is usually used for the REPL, in case +that stream is used for other purposes.""" + ... \ No newline at end of file diff --git a/lang/zh-cn/typeshed/stdlib/music.pyi b/lang/zh-cn/typeshed/stdlib/music.pyi index 5f4778b..061c3af 100644 --- a/lang/zh-cn/typeshed/stdlib/music.pyi +++ b/lang/zh-cn/typeshed/stdlib/music.pyi @@ -1,167 +1,128 @@ -"""Create and play melodies. -""" +"""创建并播放旋律。 (音乐)""" from typing import Optional, Tuple, Union, List - from .microbit import MicroBitDigitalPin, pin0 - DADADADUM: Tuple[str, ...] -"""Melody: the opening to Beethoven’s 5th Symphony in C minor.""" - +"""旋律:《贝多芬 C 小调第五交响曲》开场曲。""" ENTERTAINER: Tuple[str, ...] -"""Melody: the opening fragment of Scott Joplin’s Ragtime classic “The Entertainer”.""" - +"""旋律:斯科特·乔普林的拉格泰姆经典“演艺人”的开场片段。 (演艺人)""" PRELUDE: Tuple[str, ...] -"""Melody: the opening of the first Prelude in C Major of J.S.Bach’s 48 Preludes and Fugues.""" - +"""旋律:约翰·塞巴斯蒂安·巴赫48首前奏曲和赋格曲中 C 大调第一前奏曲的开场。 (序幕)""" ODE: Tuple[str, ...] -"""Melody: the “Ode to Joy” theme from Beethoven’s 9th Symphony in D minor.""" - +"""旋律:贝多芬 D 小调第九交响曲中的“欢乐颂”主题。 (欢乐颂)""" NYAN: Tuple[str, ...] -"""Melody: the Nyan Cat theme (http://www.nyan.cat/). +"""旋律:彩虹猫主题 (http://www.nyan.cat/)。 (彩虹猫) The composer is unknown. This is fair use for educational porpoises (as they say in New York).""" - RINGTONE: Tuple[str, ...] -"""Melody: something that sounds like a mobile phone ringtone. +"""旋律:听起来像手机铃声的乐曲。 (铃声) To be used to indicate an incoming message. """ - FUNK: Tuple[str, ...] -"""Melody: a funky bass line for secret agents and criminal masterminds.""" - +"""旋律:一曲为特工和犯罪主谋制作的 funky bass。 (朋克)""" BLUES: Tuple[str, ...] -"""Melody: a boogie-woogie 12-bar blues walking bass.""" - +"""旋律:布吉伍吉 12 小节布鲁斯 walking bass。 (布鲁斯)""" BIRTHDAY: Tuple[str, ...] -"""Melody: “Happy Birthday to You…” +"""旋律:“祝你生日快乐……” (生日) For copyright status see: http://www.bbc.co.uk/news/world-us-canada-34332853 """ - WEDDING: Tuple[str, ...] -"""Melody: the bridal chorus from Wagner’s opera “Lohengrin”.""" - +"""旋律:瓦格纳歌剧《罗恩格林》中的新娘合唱。 (婚礼)""" FUNERAL: Tuple[str, ...] -"""Melody: the “funeral march” otherwise known as Frédéric Chopin’s Piano Sonata No. 2 in B♭ minor, Op. 35.""" - +"""旋律:“葬礼进行曲”,也被称为弗雷德里克肖邦的 B♭ 小调第二钢琴奏鸣曲,Op. 35。 (哀乐)""" PUNCHLINE: Tuple[str, ...] -"""Melody: a fun fragment that signifies a joke has been made.""" - +"""旋律:一个有趣的片段,表示开了一个玩笑。 (笑点)""" PYTHON: Tuple[str, ...] -"""Melody: John Philip Sousa’s march “Liberty Bell” aka, the theme for “Monty Python’s Flying Circus” (after which the Python programming language is named).""" - +"""旋律:约翰·菲利普·苏萨的进行曲《自由钟》,即《巨蟒剧团之飞翔的马戏团》的主题曲(Python 编程语言以此命名)。 (Python)""" BADDY: Tuple[str, ...] -"""Melody: silent movie era entrance of a baddy.""" - +"""旋律:默片时代反面角色的入场曲。 (反面角色)""" CHASE: Tuple[str, ...] -"""Melody: silent movie era chase scene.""" - +"""旋律:无声电影时代的追逐场景。 (追逐)""" BA_DING: Tuple[str, ...] -"""Melody: a short signal to indicate something has happened.""" - +"""旋律:表示某事发生的简短信号。""" WAWAWAWAA: Tuple[str, ...] -"""Melody: a very sad trombone.""" - +"""旋律:非常悲伤的长号。""" JUMP_UP: Tuple[str, ...] -"""Melody: for use in a game, indicating upward movement.""" - +"""旋律:用于游戏中,表示向上运动。 (向上跳)""" JUMP_DOWN: Tuple[str, ...] -"""Melody: for use in a game, indicating downward movement.""" - +"""旋律:用于游戏中,表示向下运动。 (向下跳)""" POWER_UP: Tuple[str, ...] -"""Melody: a fanfare to indicate an achievement unlocked.""" - +"""旋律:表示解锁成就的号角。 (能力增强)""" POWER_DOWN: Tuple[str, ...] -"""Melody: a sad fanfare to indicate an achievement lost.""" +"""旋律:表示失去成就的悲伤号角。 (能力减弱)""" -def set_tempo(ticks: int = 4, bpm: int = 120) -> None: - """Sets the approximate tempo for playback. +def set_tempo(ticks: int=4, bpm: int=120) -> None: + """设置播放的大致节奏。 (设置节奏) - Example: ``music.set_tempo(bpm=120)`` +Example: ``music.set_tempo(bpm=120)`` - :param ticks: The number of ticks constituting a beat. - :param bpm: An integer determining how many beats per minute. +:param ticks: (刻度) 构成一个节拍的刻度数。 +:param bpm: (每分钟节拍数) 一个整数,确定每分钟有多少拍。 - Suggested default values allow the following useful behaviour: +Suggested default values allow the following useful behaviour: - - music.set_tempo() – reset the tempo to default of ticks = 4, bpm = 120 - - music.set_tempo(ticks=8) – change the “definition” of a beat - - music.set_tempo(bpm=180) – just change the tempo +- music.set_tempo() – reset the tempo to default of ticks = 4, bpm = 120 +- music.set_tempo(ticks=8) – change the “definition” of a beat +- music.set_tempo(bpm=180) – just change the tempo - To work out the length of a tick in milliseconds is very simple arithmetic: - 60000/bpm/ticks_per_beat. For the default values that’s - 60000/120/4 = 125 milliseconds or 1 beat = 500 milliseconds. - """ +To work out the length of a tick in milliseconds is very simple arithmetic: +60000/bpm/ticks_per_beat. For the default values that’s +60000/120/4 = 125 milliseconds or 1 beat = 500 milliseconds.""" ... def get_tempo() -> Tuple[int, int]: - """Gets the current tempo as a tuple of integers: ``(ticks, bpm)``. + """以整数元组的形式获取当前节奏:``(ticks, bpm)``。 (获得节奏值) - Example: ``ticks, beats = music.get_tempo()`` +Example: ``ticks, beats = music.get_tempo()`` - :return: The temp as a tuple with two integer values, the ticks then the beats per minute. - """ +:return: The temp as a tuple with two integer values, the ticks then the beats per minute.""" ... -def play( - music: Union[str, List[str], Tuple[str, ...]], - pin: Optional[MicroBitDigitalPin] = pin0, - wait: bool = True, - loop: bool = False, -) -> None: - """Plays music. +def play(music: Union[str, List[str], Tuple[str, ...]], pin: Optional[MicroBitDigitalPin]=pin0, wait: bool=True, loop: bool=False) -> None: + """播放音乐。 (播放) - Example: ``music.play(music.NYAN)`` +Example: ``music.play(music.NYAN)`` - :param music: music specified in `a special notation `_ - :param pin: the output pin for use with an external speaker (default ``pin0``), ``None`` for no sound. - :param wait: If ``wait`` is set to ``True``, this function is blocking. - :param loop: If ``loop`` is set to ``True``, the tune repeats until ``stop`` is called or the blocking call is interrupted. +:param music: (音乐) `a special notation `_中指定的音乐 +:param pin: (引脚) 用于外接扬声器的输出引脚(默认为 ``pin0``),``None`` 表示无声音。 +:param wait: (等待) 如果 ``wait`` 设置为 ``True``,则此函数阻塞。 +:param loop: 如果 ``loop`` 设置为 ``True``,曲调会重复直到调用 ``stop`` 或阻塞调用被中断。 - Many built-in melodies are defined in this module. - """ +Many built-in melodies are defined in this module.""" ... -def pitch( - frequency: int, - duration: int = -1, - pin: Optional[MicroBitDigitalPin] = pin0, - wait: bool = True, -) -> None: - """Play a note. +def pitch(frequency: int, duration: int=-1, pin: Optional[MicroBitDigitalPin]=pin0, wait: bool=True) -> None: + """播放一个音符。 (音高) - Example: ``music.pitch(185, 1000)`` +Example: ``music.pitch(185, 1000)`` - :param frequency: An integer frequency - :param duration: A millisecond duration. If negative then sound is continuous until the next call or a call to ``stop``. - :param pin: Optional output pin (default ``pin0``). - :param wait: If ``wait`` is set to ``True``, this function is blocking. +:param frequency: (频率) 整数频率 +:param duration: (持续) 一毫秒的持续时间。如果是负的,则声音将持续到下一次调用或对 ``stop`` 的调用。 +:param pin: (引脚) 可选输出引脚(默认值``pin0``)。 +:param wait: (等待) 如果 ``wait`` 设置为 ``True``,则此函数阻塞。 - For example, if the frequency is set to 440 and the length to - 1000 then we hear a standard concert A for one second. +For example, if the frequency is set to 440 and the length to +1000 then we hear a standard concert A for one second. - You can only play one pitch on one pin at any one time. - """ +You can only play one pitch on one pin at any one time.""" ... -def stop(pin: Optional[MicroBitDigitalPin] = pin0) -> None: - """Stops all music playback on the built-in speaker and any pin outputting sound. +def stop(pin: Optional[MicroBitDigitalPin]=pin0) -> None: + """停止内置扬声器播放任何音乐,并停止发出任何引脚输出的声音。 (停止) - Example: ``music.stop()`` +Example: ``music.stop()`` - :param pin: An optional argument can be provided to specify a pin, e.g. ``music.stop(pin1)``. - """ +:param pin: (引脚) 可以提供可选参数来指定一个引脚,如``music.stop(pin1)``。""" def reset() -> None: - """Resets ticks, bpm, duration and octave to their default values. + """将 ticks、bpm、duration 和 octave重置为默认值。 - Example: ``music.reset()`` +Example: ``music.reset()`` - Values: - - ``ticks = 4`` - - ``bpm = 120`` - - ``duration = 4`` - - ``octave = 4`` - """ - ... +Values: +- ``ticks = 4`` +- ``bpm = 120`` +- ``duration = 4`` +- ``octave = 4``""" + ... \ No newline at end of file diff --git a/lang/zh-cn/typeshed/stdlib/neopixel.pyi b/lang/zh-cn/typeshed/stdlib/neopixel.pyi index 2d5a749..6d53501 100644 --- a/lang/zh-cn/typeshed/stdlib/neopixel.pyi +++ b/lang/zh-cn/typeshed/stdlib/neopixel.pyi @@ -1,82 +1,81 @@ -"""Individually addressable RGB and RGBW LED strips. -""" +"""可单独寻址的 RGB 和 RGBW LED 灯带。 (Neopixel)""" from .microbit import MicroBitDigitalPin from typing import Tuple class NeoPixel: - def __init__(self, pin: MicroBitDigitalPin, n: int, bpp: int = 3) -> None: - """Initialise a new strip of neopixel LEDs controlled via a pin. - Example: ``np = neopixel.NeoPixel(pin0, 8)`` + def __init__(self, pin: MicroBitDigitalPin, n: int, bpp: int=3) -> None: + """初始化一条通过一个引脚控制的新 neopixel LED 灯带。 - To support RGBW neopixels, a third argument can be passed to - ``NeoPixel`` to indicate the number of bytes per pixel (``bpp``). - For RGBW, this is is 4 rather than the default of 3 for RGB and GRB. +Example: ``np = neopixel.NeoPixel(pin0, 8)`` - Each pixel is addressed by a position (starting from 0). Neopixels are - given RGB (red, green, blue) / RGBW (red, green, blue, white) values - between 0-255 as a tuple. For example, in RGB, ``(255,255,255)`` is - white. In RGBW, ``(255,255,255,0)`` or ``(0,0,0,255)`` is white. +To support RGBW neopixels, a third argument can be passed to +``NeoPixel`` to indicate the number of bytes per pixel (``bpp``). +For RGBW, this is is 4 rather than the default of 3 for RGB and GRB. - See `the online docs `_ for warnings and other advice. +Each pixel is addressed by a position (starting from 0). Neopixels are +given RGB (red, green, blue) / RGBW (red, green, blue, white) values +between 0-255 as a tuple. For example, in RGB, ``(255,255,255)`` is +white. In RGBW, ``(255,255,255,0)`` or ``(0,0,0,255)`` is white. - :param pin: The pin controlling the neopixel strip. - :param n: The number of neopixels in the strip. - :param bpp: Bytes per pixel. For RGBW neopixel support, pass 4 rather than the default of 3 for RGB and GRB. - """ +See `the online docs `_ for warnings and other advice. + +:param pin: (引脚) 控制 neopixel 灯带的引脚。 +:param n: 灯带中 neopixel 灯珠的数量。 +:param bpp: (每像素字节数) 每个像素的字节数。对于 RGB 和 GRB 而言,只有将该值设置为 4 而不是默认值 3,RGBW neopixel 才能支持。""" ... + def clear(self) -> None: - """Clear all the pixels. + """清除所有像素。 (清除) - Example: ``np.clear()`` - """ +Example: ``np.clear()``""" ... + def show(self) -> None: - """Show the pixels. + """显示像素。 (显示) - Example: ``np.show()`` +Example: ``np.show()`` - Must be called for any updates to become visible. - """ +Must be called for any updates to become visible.""" ... + def write(self) -> None: - """Show the pixels (micro:bit V2 only). + """显示像素(仅限 micro:bit V2)。 (写入) - Example: ``np.write()`` +Example: ``np.write()`` - Must be called for any updates to become visible. +Must be called for any updates to become visible. - Equivalent to ``show``. - """ +Equivalent to ``show``.""" ... + def fill(self, colour: Tuple[int, ...]) -> None: - """Colour all pixels a given RGB/RGBW value (micro:bit V2 only). + """用给定的 RGB/RGBW 值为所有像素着色(仅限 micro:bit V2)。 (填充) - Example: ``np.fill((0, 0, 255))`` +Example: ``np.fill((0, 0, 255))`` - :param colour: A tuple of the same length as the number of bytes per pixel (bpp). +:param colour: (颜色) 长度与每像素字节数 (bpp) 相同的元组。 - Use in conjunction with ``show()`` to update the neopixels. - """ +Use in conjunction with ``show()`` to update the neopixels.""" ... + def __setitem__(self, key: int, value: Tuple[int, ...]) -> None: - """Set a pixel colour. + """设置像素颜色 - Example: ``np[0] = (255, 0, 0)`` +Example: ``np[0] = (255, 0, 0)`` + +:param key: (键) 像素数。 +:param value: 颜色。""" - :param key: The pixel number. - :param value: The colour. - """ def __getitem__(self, key: int) -> Tuple[int, ...]: - """Get a pixel colour. + """获取像素颜色。 + +Example: ``r, g, b = np[0]`` - Example: ``r, g, b = np[0]`` +:param key: (键) 像素数。 +:return: The colour tuple.""" - :param key: The pixel number. - :return: The colour tuple. - """ def __len__(self) -> int: - """Get length of this pixel strip. + """获取此像素条的长度。 (长度) - Example: ``len(np)`` - """ +Example: ``len(np)``""" \ No newline at end of file diff --git a/lang/zh-cn/typeshed/stdlib/os.pyi b/lang/zh-cn/typeshed/stdlib/os.pyi index 2f2db77..1c6f9f9 100644 --- a/lang/zh-cn/typeshed/stdlib/os.pyi +++ b/lang/zh-cn/typeshed/stdlib/os.pyi @@ -1,73 +1,63 @@ -"""Access the file system. -""" - +"""访问文件系统。 (操作系统)""" from typing import Tuple from typing import List def listdir() -> List[str]: - """List files. + """列出文件。 (列出目录) - Example: ``os.listdir()`` +Example: ``os.listdir()`` - :return: A list of the names of all the files contained within the local - persistent on-device file system. - """ +:return: A list of the names of all the files contained within the local +persistent on-device file system.""" ... def remove(filename: str) -> None: - """Remove (delete) a file. + """移除(删除)一份文件。 (删除) - Example: ``os.remove('data.txt')`` +Example: ``os.remove('data.txt')`` - :param filename: The file to delete. +:param filename: (文件名) 要删除的文件。 - If the file does not exist an ``OSError`` exception will occur. - """ +If the file does not exist an ``OSError`` exception will occur.""" ... def size(filename: str) -> int: - """Returns the size of a file. + """返回文件的大小。 (大小) - Example: ``os.size('data.txt')`` +Example: ``os.size('data.txt')`` - :param filename: The file - :return: The size in bytes. +:param filename: (文件名) 此文件 +:return: The size in bytes. - If the file does not exist an ``OSError`` exception will occur. - """ +If the file does not exist an ``OSError`` exception will occur.""" class uname_result(Tuple[str, str, str, str, str]): - """Result of ``os.uname()``""" + """``os.uname()`` 的结果 (当前系统名称的返回结果)""" sysname: str - """Operating system name.""" - + """操作系统名称。 (系统名字)""" nodename: str - """Name of machine on network (implementation-defined).""" - + """网络上机器的名称(实现-定义)。 (节点名字)""" release: str - """Operating system release.""" - + """操作系统发布版本。 (发布)""" version: str - """Operating system version.""" - + """操作系统版本。 (版本)""" machine: str - """Hardware identifier.""" + """硬件标识符。 (机器)""" def uname() -> uname_result: - """Returns information identifying the current operating system. + """返回标识当前操作系统的信息。 (当前系统名称) - Example: ``os.uname()`` +Example: ``os.uname()`` - The return value is an object with five attributes: +The return value is an object with five attributes: - - ``sysname`` - operating system name - - ``nodename`` - name of machine on network (implementation-defined) - - ``release`` - operating system release - - ``version`` - operating system version - - ``machine`` - hardware identifier +- ``sysname`` - operating system name +- ``nodename`` - name of machine on network (implementation-defined) +- ``release`` - operating system release +- ``version`` - operating system version +- ``machine`` - hardware identifier - There is no underlying operating system in MicroPython. As a result the - information returned by the ``uname`` function is mostly useful for - versioning details. - """ - ... +There is no underlying operating system in MicroPython. As a result the +information returned by the ``uname`` function is mostly useful for +versioning details.""" + ... \ No newline at end of file diff --git a/lang/zh-cn/typeshed/stdlib/radio.pyi b/lang/zh-cn/typeshed/stdlib/radio.pyi index 8dd0267..883febe 100644 --- a/lang/zh-cn/typeshed/stdlib/radio.pyi +++ b/lang/zh-cn/typeshed/stdlib/radio.pyi @@ -1,152 +1,129 @@ -"""Communicate between micro:bits with the built-in radio. -""" - +"""使用内置无线电在 micro:bit 之间进行通信。 (无线电)""" from _typeshed import WriteableBuffer from typing import Optional, Tuple - RATE_1MBIT: int -"""Constant used to indicate a throughput of 1 MBit a second.""" - +"""用于表示每秒 1 兆字节吞吐量的常数。 (速率 1Mbit)""" RATE_2MBIT: int -"""Constant used to indicate a throughput of 2 MBit a second.""" +"""用于表示每秒 2 兆字节吞吐量的常数。 (速率 2Mbit)""" def on() -> None: - """Turns the radio on. + """打开无线电。 (打开) - Example: ``radio.on()`` +Example: ``radio.on()`` - This needs to be explicitly called since the radio draws power and takes - up memory that you may otherwise need. - """ +This needs to be explicitly called since the radio draws power and takes +up memory that you may otherwise need.""" ... def off() -> None: - """Turns off the radio, saving power and memory. + """关闭无线电以节省电量和内存。 (关闭) - Example: ``radio.off()`` - """ +Example: ``radio.off()``""" ... -def config( - length: int = 32, - queue: int = 3, - channel: int = 7, - power: int = 6, - address: int = 0x75626974, - group: int = 0, - data_rate: int = RATE_1MBIT, -) -> None: - """Configures the radio. - - Example: ``radio.config(group=42)`` - - The default configuration is suitable for most use. - - :param length: (default=32) defines the maximum length, in bytes, of a message sent via the radio. - It can be up to 251 bytes long (254 - 3 bytes for S0, LENGTH and S1 preamble). - :param queue: (default=3) specifies the number of messages that can be stored on the incoming message queue. - If there are no spaces left on the queue for incoming messages, then the incoming message is dropped. - :param channel: (default=7) an integer value from 0 to 83 (inclusive) that defines an arbitrary "channel" to which the radio is tuned. - Messages will be sent via this channel and only messages received via this channel will be put onto the incoming message queue. Each step is 1MHz wide, based at 2400MHz. - :param power: (default=6) is an integer value from 0 to 7 (inclusive) to indicate the strength of signal used when broadcasting a message. - The higher the value the stronger the signal, but the more power is consumed by the device. The numbering translates to positions in the following list of dBm (decibel milliwatt) values: -30, -20, -16, -12, -8, -4, 0, 4. - :param address: (default=0x75626974) an arbitrary name, expressed as a 32-bit address, that's used to filter incoming packets at the hardware level, keeping only those that match the address you set. - The default used by other micro:bit related platforms is the default setting used here. - :param group: (default=0) an 8-bit value (0-255) used with the ``address`` when filtering messages. - Conceptually, "address" is like a house/office address and "group" is like the person at that address to which you want to send your message. - :param data_rate: (default=``radio.RATE_1MBIT``) indicates the speed at which data throughput takes place. - Can be one of the following constants defined in the ``radio`` module: ``RATE_250KBIT``, ``RATE_1MBIT`` or ``RATE_2MBIT``. - - If ``config`` is not called then the defaults described above are assumed. - """ +def config(length: int=32, queue: int=3, channel: int=7, power: int=6, address: int=1969383796, group: int=0, data_rate: int=RATE_1MBIT) -> None: + """配置无线电。 (配置) + +Example: ``radio.config(group=42)`` + +The default configuration is suitable for most use. + +:param length: (长度) (默认值32)以字节为单位,定义了通过无线电传输消息的最大长度。 +其长度可达 251 字节(S0、LENGTH 和 S1 前导码:254-3 字节)。 +:param queue: (队列) (默认值3)规定了传入消息队列中可以存储的消息数量。 +如果队列中没有多余的空间留给传入的消息,那么传入的消息就会被丢弃。 +:param channel: (信道) (缺省值7)范围为从0到83(含83)的整数,用于定义一任意“信道”,以便将无线电调到该信道。信息通过该信道发送,并且只有通过该信道接收到的消息才被放到传入消息队列中。每一步的宽度为 1 MHz,基于 2400 MHz。 +:param power: (幂数) (默认值6)用于表示广播消息时所使用信号强度的整数值,其范围为从0到7(包含7)。 +该值越大,信号越强,但设备消耗的功率也越大。其编码转换为以下 dBm(分贝毫瓦)值列表中的不同值:-30, -20, -16, -12, -8, -4, 0, 4。 +:param address: (地址) (default=0x75626974) 任意名称,表示为 32 位地址,用于在硬件级别过滤传入的数据包,仅保留与您设置的地址匹配的数据包。 +其他 micro:bit 相关平台使用的默认设置与此处的默认设置相同。 +:param group: (群组) (默认值0)过滤消息时与 ``address`` 一起使用的 8 位的数值(0-255)。 +从概念上讲,"address”就像房屋或办公室的地址,而“group”就像住在该地址,并且你想给他或她发消息的那个人。 +:param data_rate: (数据传输速率) (默认值``radio.RATE_1MBIT``)表示数据吞吐速度。 +可以是``radio``模块中定义的以下常数之一:``RATE_250KBIT``、``RATE_1MBIT`` 或 ``RATE_2MBIT``。 + +If ``config`` is not called then the defaults described above are assumed.""" ... def reset() -> None: - """Reset the settings to their default values. + """将设置重设为默认值。 - Example: ``radio.reset()`` +Example: ``radio.reset()`` - The defaults as as per the ``config`` function above. - """ +The defaults as as per the ``config`` function above.""" ... def send_bytes(message: bytes) -> None: - """Sends a message containing bytes. + """发送一条包含字节的消息。 (发送字节) - Example: ``radio.send_bytes(b'hello')`` +Example: ``radio.send_bytes(b'hello')`` - :param message: The bytes to send. - """ +:param message: (消息) 待发送的字节。""" ... def receive_bytes() -> Optional[bytes]: - """Receive the next incoming message on the message queue. + """接收消息队列中的下一条传入消息。 (接收字节) - Example: ``radio.receive_bytes()`` +Example: ``radio.receive_bytes()`` - :return: The message bytes if any, otherwise ``None``. - """ +:return: The message bytes if any, otherwise ``None``.""" ... def receive_bytes_into(buffer: WriteableBuffer) -> Optional[int]: - """Copy the next incoming message on the message queue into a buffer. + """将消息队列中的下一条传入消息复制到缓冲区。 (接收传入的字节) - Example: ``radio.receive_bytes_info(buffer)`` +Example: ``radio.receive_bytes_info(buffer)`` - :param buffer: The target buffer. The message is truncated if larger than the buffer. - :return: ``None`` if there are no pending messages, otherwise it returns the length of the message (which might be more than the length of the buffer). - """ +:param buffer: (缓冲区) 目标缓冲区。如果消息大小大于缓冲区,则消息会被截断。 +:return: ``None`` if there are no pending messages, otherwise it returns the length of the message (which might be more than the length of the buffer).""" ... def send(message: str) -> None: - """Sends a message string. + """发送消息字符串。 (发送) - Example: ``radio.send('hello')`` +Example: ``radio.send('hello')`` - This is the equivalent of ``radio.send_bytes(bytes(message, 'utf8'))`` but with ``b'\x01\x00\x01'`` - prepended to the front (to make it compatible with other platforms that target the micro:bit). +This is the equivalent of ``radio.send_bytes(bytes(message, 'utf8'))`` but with ``b'\x01\x00\x01'`` +prepended to the front (to make it compatible with other platforms that target the micro:bit). - :param message: The string to send. - """ +:param message: (消息) 待发送的字符串。""" ... def receive() -> Optional[str]: - """Works in exactly the same way as ``receive_bytes`` but returns whatever was sent. + """按照与``receive_bytes``完全相同的工作方式,但是返回所发送的内容。 (接收) - Example: ``radio.receive()`` +Example: ``radio.receive()`` - Equivalent to ``str(receive_bytes(), 'utf8')`` but with a check that the the first - three bytes are ``b'\x01\x00\x01'`` (to make it compatible with other platforms that - may target the micro:bit). +Equivalent to ``str(receive_bytes(), 'utf8')`` but with a check that the the first +three bytes are ``b'\x01\x00\x01'`` (to make it compatible with other platforms that +may target the micro:bit). - :return: The message with the prepended bytes stripped and converted to a string. +:return: The message with the prepended bytes stripped and converted to a string. - A ``ValueError`` exception is raised if conversion to string fails. - """ +A ``ValueError`` exception is raised if conversion to string fails.""" ... def receive_full() -> Optional[Tuple[bytes, int, int]]: - """Returns a tuple containing three values representing the next incoming message on the message queue. + """返回一个包含三个数值的元组,用来代表消息队列中的下一条传入消息。 (接受完整消息) - Example: ``radio.receive_full()`` +Example: ``radio.receive_full()`` - If there are no pending messages then ``None`` is returned. +If there are no pending messages then ``None`` is returned. - The three values in the tuple represent: +The three values in the tuple represent: - - the next incoming message on the message queue as bytes. - - the RSSI (signal strength): a value between 0 (strongest) and -255 (weakest) as measured in dBm. - - a microsecond timestamp: the value returned by ``time.ticks_us()`` when the message was received. +- the next incoming message on the message queue as bytes. +- the RSSI (signal strength): a value between 0 (strongest) and -255 (weakest) as measured in dBm. +- a microsecond timestamp: the value returned by ``time.ticks_us()`` when the message was received. - For example:: +For example:: - details = radio.receive_full() - if details: - msg, rssi, timestamp = details + details = radio.receive_full() + if details: + msg, rssi, timestamp = details - This function is useful for providing information needed for triangulation - and/or trilateration with other micro:bit devices. +This function is useful for providing information needed for triangulation +and/or trilateration with other micro:bit devices. - :return: ``None`` if there is no message, otherwise a tuple of length three with the bytes, strength and timestamp values. - """ - ... +:return: ``None`` if there is no message, otherwise a tuple of length three with the bytes, strength and timestamp values.""" + ... \ No newline at end of file diff --git a/lang/zh-cn/typeshed/stdlib/random.pyi b/lang/zh-cn/typeshed/stdlib/random.pyi index a2c2ef3..0695b70 100644 --- a/lang/zh-cn/typeshed/stdlib/random.pyi +++ b/lang/zh-cn/typeshed/stdlib/random.pyi @@ -1,93 +1,80 @@ -"""Generate random numbers. -""" +"""生成随机数。 (随机数)""" from typing import TypeVar, Sequence, Union, overload def getrandbits(n: int) -> int: - """Generate an integer with ``n`` random bits. + """生成一个具有``n``个随机位的整数。 (生成随机位) - Example: ``random.getrandbits(1)`` +Example: ``random.getrandbits(1)`` - :param n: A value between 1-30 (inclusive). - """ +:param n: 一个在1到30之间(包含30)的数值。""" ... def seed(n: int) -> None: - """Initialize the random number generator. + """初始化随机数生成器。 (种子) - Example: ``random.seed(0)`` +Example: ``random.seed(0)`` - :param n: The integer seed +:param n: 整数种子 - This will give you reproducibly deterministic randomness from a given starting - state (``n``). - """ +This will give you reproducibly deterministic randomness from a given starting +state (``n``).""" ... def randint(a: int, b: int) -> int: - """Choose a random integer between ``a`` and ``b`` inclusive. + """在``a``到``b``(包含``b``)之间随机选择一个整数。 (随机整数) - Example: ``random.randint(0, 9)`` +Example: ``random.randint(0, 9)`` - :param a: Start value for the range (inclusive) - :param b: End value for the range (inclusive) +:param a: 区间起始值(包含) +:param b: 区间结束值(包含) - Alias for ``randrange(a, b + 1)``. - """ +Alias for ``randrange(a, b + 1)``.""" ... @overload def randrange(stop: int) -> int: - """Choose a randomly selected integer between zero and up to (but not - including) ``stop``. + """在零到``stop``(不含``stop``)之间随机选择一个整数。 (随机区间) - Example: ``random.randrange(10)`` +Example: ``random.randrange(10)`` - :param stop: End value for the range (exclusive) - """ +:param stop: (结束值) 区间结束值(不含)""" ... @overload -def randrange(start: int, stop: int, step: int = 1) -> int: - """ - Choose a randomly selected element from ``range(start, stop, step)``. +def randrange(start: int, stop: int, step: int=1) -> int: + """从区间``range(start, stop, step)``中随机选择一个元素。 (随机区间) - Example: ``random.randrange(0, 10)`` +Example: ``random.randrange(0, 10)`` - :param start: The start of the range (inclusive) - :param stop: The end of the range (exclusive) - :param step: The step. - """ +:param start: (起始值) 区间起始值(包含) +:param stop: (结束值) 区间结束值(不含) +:param step: (步长) 步长。""" ... - -_T = TypeVar("_T") +_T = TypeVar('_T') def choice(seq: Sequence[_T]) -> _T: - """Choose a random element from the non-empty sequence ``seq``. + """从非空序列``seq``中选择一个随机元素。 (选择) - Example: ``random.choice([Image.HAPPY, Image.SAD])`` +Example: ``random.choice([Image.HAPPY, Image.SAD])`` - :param seq: A sequence. +:param seq: (序列) 序列。 - If ``seq`` is empty, raises ``IndexError``. - """ +If ``seq`` is empty, raises ``IndexError``.""" ... def random() -> float: - """Generate a random floating point number in the range [0.0, 1.0). + """在区间[0.0, 1.0)内生成一个随机浮点数。 (随机) - Example: ``random.random()`` +Example: ``random.random()`` - :return: The random floating point number - """ +:return: The random floating point number""" ... def uniform(a: float, b: float) -> float: - """ - Return a random floating point number between ``a`` and ``b`` inclusive. + """返回一个介于``a``和``b``(包含``b``)之间的随机浮点数。 (均匀分布随机数) - Example: ``random.uniform(0, 9)`` +Example: ``random.uniform(0, 9)`` - :param a: Start value for the range (inclusive) - :param b: End value for the range (inclusive) - """ - ... +:param a: 区间起始值(包含) +:param b: 区间结束值(包含)""" + ... \ No newline at end of file diff --git a/lang/zh-cn/typeshed/stdlib/speech.pyi b/lang/zh-cn/typeshed/stdlib/speech.pyi index 349d188..edb82d7 100644 --- a/lang/zh-cn/typeshed/stdlib/speech.pyi +++ b/lang/zh-cn/typeshed/stdlib/speech.pyi @@ -1,106 +1,79 @@ -"""Make the micro:bit talk, sing and make other speech like sounds. -""" - +"""使 micro:bit 说话、唱歌和发出其他类似语音的声音。 (语音)""" from typing import Optional from .microbit import MicroBitDigitalPin, pin0 def translate(words: str) -> str: - """Translate English words to phonemes. + """把英语单词翻译成音素。 (翻译) - Example: ``speech.translate('hello world')`` +Example: ``speech.translate('hello world')`` - :param words: A string of English words. - :return: A string containing a best guess at the appropriate phonemes to pronounce. - The output is generated from this `text to phoneme translation table `_. +:param words: (单词) 一连串英语单词。 +:return: A string containing a best guess at the appropriate phonemes to pronounce. +The output is generated from this `text to phoneme translation table `_. - This function should be used to generate a first approximation of phonemes - that can be further hand-edited to improve accuracy, inflection and - emphasis. +This function should be used to generate a first approximation of phonemes +that can be further hand-edited to improve accuracy, inflection and +emphasis. - See `the online documentation `_ for detailed information. - """ +See `the online documentation `_ for detailed information.""" ... -def pronounce( - phonemes: str, - pitch: int = 64, - speed: int = 72, - mouth: int = 128, - throat: int = 128, - pin: Optional[MicroBitDigitalPin] = pin0, -) -> None: - """Pronounce phonemes. - - Example: ``speech.pronounce(' /HEHLOW WERLD')`` - - :param phonemes: The string of phonemes to pronounce - :param pitch: A number representing the pitch of the voice - :param speed: A number representing the speed of the voice - :param mouth: A number representing the mouth of the voice - :param throat: A number representing the throat of the voice - :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. - If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. - - Override the optional pitch, speed, mouth and throat settings to change the - timbre (quality) of the voice. - - See `the online documentation `_ for detailed information. - """ - ... +def pronounce(phonemes: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: Optional[MicroBitDigitalPin]=pin0) -> None: + """发出音素的声音。 (发音) + +Example: ``speech.pronounce(' /HEHLOW WERLD')`` + +:param phonemes: (音素) 要发音的音素串 +:param pitch: (音高) 代表声音音高的数字 +:param speed: (速度:) 代表声音速度的数字 +:param mouth: (嘴巴) 表示声音口型的数字 +:param throat: (喉部) 表示声音喉型的数字 +:param pin: (引脚) 可选参数,可用于指定输出引脚来覆盖 ``pin0`` 默认值。 +如果不想从引脚上播放任何声音,可以使用 ``pin=None``。仅限micro:bit V2。 -def say( - words: str, - pitch: int = 64, - speed: int = 72, - mouth: int = 128, - throat: int = 128, - pin: MicroBitDigitalPin = pin0, -) -> None: - """Say English words. - - Example: ``speech.say('hello world')`` - - :param words: The string of words to say. - :param pitch: A number representing the pitch of the voice - :param speed: A number representing the speed of the voice - :param mouth: A number representing the mouth of the voice - :param throat: A number representing the throat of the voice - :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. - If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. - - The result is semi-accurate for English. Override the optional pitch, speed, - mouth and throat settings to change the timbre (quality) of the voice. - - This is a short-hand equivalent of: - ``speech.pronounce(speech.translate(words))`` - - See `the online documentation `_ for detailed information. - """ +Override the optional pitch, speed, mouth and throat settings to change the +timbre (quality) of the voice. + +See `the online documentation `_ for detailed information.""" ... -def sing( - phonemes: str, - pitch: int = 64, - speed: int = 72, - mouth: int = 128, - throat: int = 128, - pin: MicroBitDigitalPin = pin0, -) -> None: - """Sing phonemes. - - Example: ``speech.sing(' /HEHLOW WERLD')`` - - :param phonemes: The string of words to sing. - :param pitch: A number representing the pitch of the voice - :param speed: A number representing the speed of the voice - :param mouth: A number representing the mouth of the voice - :param throat: A number representing the throat of the voice - :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. - If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. - - Override the optional pitch, speed, mouth and throat settings to change - the timbre (quality) of the voice. - - See `the online documentation `_ for detailed information. - """ +def say(words: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: MicroBitDigitalPin=pin0) -> None: + """说英语单词。 (说) + +Example: ``speech.say('hello world')`` + +:param words: (单词) 要说的词串。 +:param pitch: (音高) 代表声音音高的数字 +:param speed: (速度) 代表声音速度的数字 +:param mouth: (嘴部) 表示声音口型的数字 +:param throat: (喉部) 表示声音喉型的数字 +:param pin: (引脚) 可选参数,可用于指定输出引脚来覆盖 ``pin0`` 默认值。 +如果不想从引脚上播放任何声音,可以使用 ``pin=None``。仅限micro:bit V2。 + +The result is semi-accurate for English. Override the optional pitch, speed, +mouth and throat settings to change the timbre (quality) of the voice. + +This is a short-hand equivalent of: +``speech.pronounce(speech.translate(words))`` + +See `the online documentation `_ for detailed information.""" ... + +def sing(phonemes: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: MicroBitDigitalPin=pin0) -> None: + """唱音素。 (唱歌) + +Example: ``speech.sing(' /HEHLOW WERLD')`` + +:param phonemes: (音素) 要唱的词串。 +:param pitch: (音高) 代表声音音高的数字 +:param speed: (速度) 代表声音速度的数字 +:param mouth: (嘴部) 表示声音口型的数字 +:param throat: (喉部) 表示声音喉型的数字 +:param pin: (引脚) 可选参数,可用于指定输出引脚来覆盖 ``pin0`` 默认值。 +如果不想从引脚上播放任何声音,可以使用 ``pin=None``。仅限micro:bit V2。 + +Override the optional pitch, speed, mouth and throat settings to change +the timbre (quality) of the voice. + +See `the online documentation `_ for detailed information.""" + ... \ No newline at end of file diff --git a/lang/zh-cn/typeshed/stdlib/struct.pyi b/lang/zh-cn/typeshed/stdlib/struct.pyi index 53b3e0b..e67b12e 100644 --- a/lang/zh-cn/typeshed/stdlib/struct.pyi +++ b/lang/zh-cn/typeshed/stdlib/struct.pyi @@ -1,65 +1,56 @@ -"""Pack and unpack primitive data types. -""" - +"""打包和解包原始数据类型。 (结构)""" from _typeshed import ReadableBuffer, WriteableBuffer from typing import Any, Tuple, Union def calcsize(fmt: str) -> int: - """Get the number of bytes needed to store the given ``fmt``. + """获取存储给定 ``fmt`` 所需的字节数。 (计算大小) - Example: ``struct.calcsize('hf')`` +Example: ``struct.calcsize('hf')`` - :param fmt: A format string. - :return The number of bytes needed to store such a value. - """ +:param fmt: (格式字符串) 格式字符串。 +:return The number of bytes needed to store such a value.""" ... def pack(fmt: str, v1: Any, *vn: Any) -> bytes: - """Pack values according to a format string. + """根据格式字符串打包值。 (打包) - Example: ``struct.pack('hf', 1, 3.1415)`` +Example: ``struct.pack('hf', 1, 3.1415)`` - :param fmt: The format string. - :param v1: The first value. - :param *vn: The remaining values. - :return A bytes object encoding the values. - """ +:param fmt: (格式字符串) 格式字符串。 +:param v1: 第一个值。 +:param *vn: 剩余值。 +:return A bytes object encoding the values.""" ... -def pack_into( - fmt: str, buffer: WriteableBuffer, offset: int, v1: Any, *vn: Any -) -> None: - """Pack values according to a format string. +def pack_into(fmt: str, buffer: WriteableBuffer, offset: int, v1: Any, *vn: Any) -> None: + """根据格式字符串打包值。 - Example: ``struct.pack_info('hf', buffer, 1, 3.1415)`` +Example: ``struct.pack_info('hf', buffer, 1, 3.1415)`` - :param fmt: The format string. - :param buffer: The target buffer to write into. - :param offset: The offset into the buffer. May be negative to count from the end of the buffer. - :param v1: The first value. - :param *vn: The remaining values. - """ +:param fmt: (格式字符串) 格式字符串。 +:param buffer: (缓冲区) 待写入的目标缓冲区。 +:param offset: (偏移量) 缓冲区内的偏移量。如果从缓冲区末端开始算起,该偏移量可能是负数。 +:param v1: 第一个值。 +:param *vn: 剩余值。""" ... def unpack(fmt: str, data: ReadableBuffer) -> Tuple[Any, ...]: - """Unpack data according to a format string. + """根据格式字符串解压数据。 (解包) - Example: ``v1, v2 = struct.unpack('hf', buffer)`` +Example: ``v1, v2 = struct.unpack('hf', buffer)`` - :param fmt: The format string. - :param data: The data. - :return: A tuple of the unpacked values. - """ +:param fmt: (格式字符串) 格式字符串。 +:param data: (数据) 数据。 +:return: A tuple of the unpacked values.""" ... -def unpack_from(fmt: str, buffer: ReadableBuffer, offset: int = 0) -> Tuple: - """Unpack data from a buffer according to a format string. +def unpack_from(fmt: str, buffer: ReadableBuffer, offset: int=0) -> Tuple: + """根据格式字符串从缓冲区解压数据。 - Example: ``v1, v2 = struct.unpack_from('hf', buffer)`` +Example: ``v1, v2 = struct.unpack_from('hf', buffer)`` - :param fmt: The format string. - :param buffer: The source buffer to read from. - :param offset: The offset into the buffer. May be negative to count from the end of the buffer. - :return: A tuple of the unpacked values. - """ - ... +:param fmt: (格式字符串) 格式字符串。 +:param buffer: 待读取的源缓冲区。 +:param offset: (偏移量) 缓冲区内的偏移量。如果从缓冲区末端开始算起,该偏移量可能是负数。 +:return: A tuple of the unpacked values.""" + ... \ No newline at end of file diff --git a/lang/zh-cn/typeshed/stdlib/sys.pyi b/lang/zh-cn/typeshed/stdlib/sys.pyi index 320bac9..80c2502 100644 --- a/lang/zh-cn/typeshed/stdlib/sys.pyi +++ b/lang/zh-cn/typeshed/stdlib/sys.pyi @@ -1,43 +1,36 @@ -"""System specific functions""" - +"""系统特定功能 (系统)""" from typing import Any, Dict, List, NoReturn, TextIO, Tuple -def exit(retval: object = ...) -> NoReturn: - """Terminate current program with a given exit code. +def exit(retval: object=...) -> NoReturn: + """根据给定退出代码终止当前程序。 (退出) - Example: ``sys.exit(1)`` +Example: ``sys.exit(1)`` - This function raises a ``SystemExit`` exception. If an argument is given, its - value given as an argument to ``SystemExit``. +This function raises a ``SystemExit`` exception. If an argument is given, its +value given as an argument to ``SystemExit``. - :param retval: The exit code or message. - """ +:param retval: (返回值) 退出代码或者消息。""" ... def print_exception(exc: Exception) -> None: - """ - Print an exception with a traceback. - - Example: ``sys.print_exception(e)`` + """打印带有回溯的异常。 (打印异常) - :param exc: The exception to print +Example: ``sys.print_exception(e)`` - This is simplified version of a function which appears in the - ``traceback`` module in CPython. - """ +:param exc: (异常) 需打印的异常 +This is simplified version of a function which appears in the +``traceback`` module in CPython.""" argv: List[str] -"""A mutable list of arguments the current program was started with.""" - +"""当前程序启动时使用的参数的可变列表。 (参数)""" byteorder: str -"""The byte order of the system (``"little"`` or ``"big"``).""" +"""系统的字节顺序 (``"little"`` 或 ``"big"``)。 (字节序)""" class _implementation: name: str version: Tuple[int, int, int] - implementation: _implementation -"""Object with information about the current Python implementation. +"""包含有关当前 Python 实现的信息的对象。 (实现) For MicroPython, it has following attributes: @@ -51,13 +44,11 @@ minimal ports). CPython mandates more attributes for this object, but the actual useful bare minimum is implemented in MicroPython. """ - maxsize: int """ -Maximum value which a native integer type can hold on the current platform, -or maximum value representable by MicroPython integer type, if it's smaller -than platform max value (that is the case for MicroPython ports without -long int support). +在当前平台上可以容纳的整数类型的最大值, +或 MicroPython 整数类型可表示的最大值,如果它小于 +平台的最大值(这见于 MicroPython 端口不支持长整数的情况)。 (最大值) This attribute is useful for detecting "bitness" of a platform (32-bit vs 64-bit, etc.). It's recommended to not compare this attribute to some @@ -77,17 +68,14 @@ value directly, but instead count number of bits in it:: # (e.g. 31) due to peculiarities described above, so use "> 16", # "> 32", "> 64" style of comparisons. """ - modules: Dict[str, Any] -"""Dictionary of loaded modules. +"""已加载模块的字典。 (模块) On some ports, it may not include builtin modules.""" - path: List[str] -"""A mutable list of directories to search for imported modules.""" - +"""用于搜索导入模块的目录的可变列表。 (路径)""" platform: str -"""The platform that MicroPython is running on. +"""正在运行 MicroPython 的平台。 (平台) For OS/RTOS ports, this is usually an identifier of the OS, e.g. ``"linux"``. For baremetal ports it is an identifier of a board, e.g. ``"pyboard"`` for @@ -97,13 +85,11 @@ distinguish one board from another. If you need to check whether your program runs on MicroPython (vs other Python implementation), use ``sys.implementation`` instead. """ - version: str -"""Python language version that this implementation conforms to, as a string.""" - +"""此实现符合的 Python 语言版本,为字符串。 (版本)""" version_info: Tuple[int, int, int] -"""Python language version that this implementation conforms to, as a tuple of ints. +"""此实现符合的 Python 语言版本,为整数元组。 (版本信息) Only the first three version numbers (major, minor, micro) are supported and they can be referenced only by index, not by name. -""" +""" \ No newline at end of file diff --git a/lang/zh-cn/typeshed/stdlib/time.pyi b/lang/zh-cn/typeshed/stdlib/time.pyi index 598c483..04baa25 100644 --- a/lang/zh-cn/typeshed/stdlib/time.pyi +++ b/lang/zh-cn/typeshed/stdlib/time.pyi @@ -1,132 +1,111 @@ -"""Measure time and add delays to programs. -""" - +"""测量时间并给程序添加延迟。 (时间)""" from typing import Union def sleep(seconds: Union[int, float]) -> None: - """ - Delay a number of seconds. + """延迟几秒钟。 (休眠) - Example: ``time.sleep(1)`` +Example: ``time.sleep(1)`` - :param seconds: The number of seconds to sleep for. - Use a floating-point number to sleep for a fractional number of seconds. - """ +:param seconds: (秒) 休眠的秒数。 +使用浮点数休眠小数秒数。""" ... def sleep_ms(ms: int) -> None: - """ - Delay for given number of milliseconds. + """延迟给定的毫秒数。 (休眠延迟以毫秒计算) - Example: ``time.sleep_ms(1_000_000)`` +Example: ``time.sleep_ms(1_000_000)`` - :param ms: The number of milliseconds delay (>= 0). - """ +:param ms: (毫秒) 延迟的毫秒数 (>= 0)。""" ... def sleep_us(us: int) -> None: - """ - Delay for given number of microseconds. + """延迟给定的微秒数。 (休眠延迟以微秒计算) - Example: ``time.sleep_us(1000)`` +Example: ``time.sleep_us(1000)`` - :param us: The number of microseconds delay (>= 0). - """ +:param us: (微秒) 延迟的微秒数 (>= 0)。""" ... def ticks_ms() -> int: - """ - Get an increasing, millisecond counter with an arbitrary reference point, - that wraps around after some value. + """获取一个具有任意参考点、递增的毫秒级计数器,该计数器在某个值之后能够绕回。 (毫秒级刻度) - Example: ``time.ticks_ms()`` +Example: ``time.ticks_ms()`` - :return: The counter value in milliseconds. - """ +:return: The counter value in milliseconds.""" ... def ticks_us() -> int: - """ - Get an increasing, microsecond counter with an arbitrary reference point, - that wraps around after some value. + """获取一个具有任意参考点、递增的微秒级计数器,该计数器在某个值之后能够绕回。 (微秒级刻度) - Example: ``time.ticks_us()`` +Example: ``time.ticks_us()`` - :return: The counter value in microseconds. - """ +:return: The counter value in microseconds.""" ... def ticks_add(ticks: int, delta: int) -> int: - """ - Offset ticks value by a given number, which can be either positive or - negative. + """给定数字的偏移刻度值,可以是正数或负数。 (增加刻度) - Example: ``time.ticks_add(time.ticks_ms(), 200)`` +Example: ``time.ticks_add(time.ticks_ms(), 200)`` - Given a ticks value, this function allows to calculate ticks - value delta ticks before or after it, following modular-arithmetic - definition of tick values. +Given a ticks value, this function allows to calculate ticks +value delta ticks before or after it, following modular-arithmetic +definition of tick values. - :param ticks: A ticks value - :param delta: An integer offset +:param ticks: (刻度) 一个刻度值 +:param delta: 整数偏移量 - Example:: +Example:: - # Find out what ticks value there was 100ms ago - print(ticks_add(time.ticks_ms(), -100)) + # Find out what ticks value there was 100ms ago + print(ticks_add(time.ticks_ms(), -100)) - # Calculate deadline for operation and test for it - deadline = ticks_add(time.ticks_ms(), 200) - while ticks_diff(deadline, time.ticks_ms()) > 0: - do_a_little_of_something() + # Calculate deadline for operation and test for it + deadline = ticks_add(time.ticks_ms(), 200) + while ticks_diff(deadline, time.ticks_ms()) > 0: + do_a_little_of_something() - # Find out TICKS_MAX used by this port - print(ticks_add(0, -1)) - """ + # Find out TICKS_MAX used by this port + print(ticks_add(0, -1))""" ... def ticks_diff(ticks1: int, ticks2: int) -> int: - """ - Measure ticks difference between values returned from - ``time.ticks_ms()`` or ``ticks_us()``, as a signed value - which may wrap around. - - Example: ``time.ticks_diff(scheduled_time, now)`` - - :param ticks1: The value to subtract from - :param ticks2: The value to subtract - - The argument order is the same as for subtraction operator, - ``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. - - ``ticks_diff()`` is designed to accommodate various usage - patterns, among them: - - Polling with timeout. In this case, the order of events is known, and you - will deal only with positive results of :func:`time.ticks_diff()`:: - - # Wait for GPIO pin to be asserted, but at most 500us - start = time.ticks_us() - while pin.value() == 0: - if time.ticks_diff(time.ticks_us(), start) > 500: - raise TimeoutError - - - Scheduling events. In this case, :func:`time.ticks_diff()` result may be - negative if an event is overdue:: - - # This code snippet is not optimized - now = time.ticks_ms() - scheduled_time = task.scheduled_time() - if ticks_diff(scheduled_time, now) > 0: - print("Too early, let's nap") - sleep_ms(ticks_diff(scheduled_time, now)) - task.run() - elif ticks_diff(scheduled_time, now) == 0: - print("Right at time!") - task.run() - elif ticks_diff(scheduled_time, now) < 0: - print("Oops, running late, tell task to run faster!") - task.run(run_faster=True) - """ - ... + """测量函数``time.ticks_ms()``或者函数``ticks_us()``返回值之间的刻度差。本参数为一个有可能绕回的带符号数值。 (刻度差) + +Example: ``time.ticks_diff(scheduled_time, now)`` + +:param ticks1: (刻度1) 要被减的值 +:param ticks2: (刻度2) 要减去的值 + +The argument order is the same as for subtraction operator, +``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. + +``ticks_diff()`` is designed to accommodate various usage +patterns, among them: + +Polling with timeout. In this case, the order of events is known, and you +will deal only with positive results of :func:`time.ticks_diff()`:: + + # Wait for GPIO pin to be asserted, but at most 500us + start = time.ticks_us() + while pin.value() == 0: + if time.ticks_diff(time.ticks_us(), start) > 500: + raise TimeoutError + + +Scheduling events. In this case, :func:`time.ticks_diff()` result may be +negative if an event is overdue:: + + # This code snippet is not optimized + now = time.ticks_ms() + scheduled_time = task.scheduled_time() + if ticks_diff(scheduled_time, now) > 0: + print("Too early, let's nap") + sleep_ms(ticks_diff(scheduled_time, now)) + task.run() + elif ticks_diff(scheduled_time, now) == 0: + print("Right at time!") + task.run() + elif ticks_diff(scheduled_time, now) < 0: + print("Oops, running late, tell task to run faster!") + task.run(run_faster=True)""" + ... \ No newline at end of file diff --git a/lang/zh-tw/typeshed/stdlib/gc.pyi b/lang/zh-tw/typeshed/stdlib/gc.pyi index 1370abf..595bd6e 100644 --- a/lang/zh-tw/typeshed/stdlib/gc.pyi +++ b/lang/zh-tw/typeshed/stdlib/gc.pyi @@ -1,73 +1,68 @@ -"""Control the garbage collector""" - +"""控管記憶體回收器""" from typing import overload def enable() -> None: - """Enable automatic garbage collection.""" + """啟用自動化記憶體回收。""" ... def disable() -> None: - """Disable automatic garbage collection. + """停用自動化記憶體回收。 - Heap memory can still be allocated, - and garbage collection can still be initiated manually using ``gc.collect``.""" +Heap memory can still be allocated, +and garbage collection can still be initiated manually using ``gc.collect``.""" def collect() -> None: - """Run a garbage collection.""" + """執行自動記憶體管理""" ... def mem_alloc() -> int: - """Get the number of bytes of heap RAM that are allocated. + """取得已分配的堆積 RAM 位元組數。 (記憶體分配) - :return: The number of bytes allocated. +:return: The number of bytes allocated. - This function is MicroPython extension. - """ +This function is MicroPython extension.""" ... def mem_free() -> int: - """Get the number of bytes of available heap RAM, or -1 if this amount is not known. + """取得可用堆積 RAM 的位元組,如果此數量未知,則為 -1。 - :return: The number of bytes free. +:return: The number of bytes free. - This function is MicroPython extension. - """ +This function is MicroPython extension.""" ... @overload def threshold() -> int: - """Query the additional GC allocation threshold. + """查詢其他 GC 分配閾值。 - :return: The GC allocation threshold. +:return: The GC allocation threshold. - This function is a MicroPython extension. CPython has a similar - function - ``set_threshold()``, but due to different GC - implementations, its signature and semantics are different. - """ +This function is a MicroPython extension. CPython has a similar +function - ``set_threshold()``, but due to different GC +implementations, its signature and semantics are different.""" ... @overload def threshold(amount: int) -> None: - """Set the additional GC allocation threshold. - - Normally, a collection is triggered only when a new allocation - cannot be satisfied, i.e. on an out-of-memory (OOM) condition. - If this function is called, in addition to OOM, a collection - will be triggered each time after ``amount`` bytes have been - allocated (in total, since the previous time such an amount of bytes - have been allocated). ``amount`` is usually specified as less than the - full heap size, with the intention to trigger a collection earlier than when the - heap becomes exhausted, and in the hope that an early collection will prevent - excessive memory fragmentation. This is a heuristic measure, the effect - of which will vary from application to application, as well as - the optimal value of the ``amount`` parameter. - - A value of -1 means a disabled allocation threshold. - - This function is a MicroPython extension. CPython has a similar - function - ``set_threshold()``, but due to different GC - implementations, its signature and semantics are different. - - :param amount: The number of bytes after which a garbage collection should be triggered. - """ - ... + """設定其他 GC 分配閾值。 + +Normally, a collection is triggered only when a new allocation +cannot be satisfied, i.e. on an out-of-memory (OOM) condition. +If this function is called, in addition to OOM, a collection +will be triggered each time after ``amount`` bytes have been +allocated (in total, since the previous time such an amount of bytes +have been allocated). ``amount`` is usually specified as less than the +full heap size, with the intention to trigger a collection earlier than when the +heap becomes exhausted, and in the hope that an early collection will prevent +excessive memory fragmentation. This is a heuristic measure, the effect +of which will vary from application to application, as well as +the optimal value of the ``amount`` parameter. + +A value of -1 means a disabled allocation threshold. + +This function is a MicroPython extension. CPython has a similar +function - ``set_threshold()``, but due to different GC +implementations, its signature and semantics are different. + +:param amount: 會觸發記憶體自動管理的位元數超標值。""" + ... \ No newline at end of file diff --git a/lang/zh-tw/typeshed/stdlib/log.pyi b/lang/zh-tw/typeshed/stdlib/log.pyi index c9870fa..9853de3 100644 --- a/lang/zh-tw/typeshed/stdlib/log.pyi +++ b/lang/zh-tw/typeshed/stdlib/log.pyi @@ -1,104 +1,89 @@ -"""Log data to your micro:bit V2.""" - +"""將資料記錄到您的 micro:bit V2。""" from typing import Literal, Mapping, Optional, Union, overload - MILLISECONDS = 1 -"""Milliseconds timestamp format.""" - +"""毫秒時間戳記格式。""" SECONDS = 10 -"""Seconds timestamp format.""" - +"""秒時間戳記格式。""" MINUTES = 600 -"""Minutes timestamp format.""" - +"""分鐘時間戳記格式""" HOURS = 36000 -"""Hours timestamp format.""" - +"""小時時間戳記格式。 (小時)""" DAYS = 864000 -"""Days timestamp format.""" +"""天時間戳記格式。""" -def set_labels( - *labels: str, timestamp: Optional[Literal[1, 10, 36000, 864000]] = SECONDS -) -> None: - """Set up the log file header. +def set_labels(*labels: str, timestamp: Optional[Literal[1, 10, 36000, 864000]]=SECONDS) -> None: + """設定紀錄檔案標頭。 - Example: ``log.set_labels('X', 'Y', 'Z', timestamp=log.MINUTES)`` +Example: ``log.set_labels('X', 'Y', 'Z', timestamp=log.MINUTES)`` - Ideally this function should be called a single time, before any data is - logged, to configure the data table header once. +Ideally this function should be called a single time, before any data is +logged, to configure the data table header once. - If a log file already exists when the program starts, or if this function - is called multiple times, it will check the labels already defined in the - log file. If this function call contains any new labels not already - present, it will generate a new header row with the additional columns. +If a log file already exists when the program starts, or if this function +is called multiple times, it will check the labels already defined in the +log file. If this function call contains any new labels not already +present, it will generate a new header row with the additional columns. - By default the first column contains a timestamp for each row. The time - unit can be selected via the timestamp argument. +By default the first column contains a timestamp for each row. The time +unit can be selected via the timestamp argument. - :param *labels: Any number of positional arguments, each corresponding to an entry in the log header. - :param timestamp: Select the timestamp unit that will be automatically added as the first column in every row. Timestamp values can be one of ``log.MILLISECONDS``, ``log.SECONDS``, ``log.MINUTES``, ``log.HOURS``, ``log.DAYS`` or ``None`` to disable the timestamp. The default value is ``log.SECONDS``. - """ +:param *labels: (標籤) Any number of positional arguments, each corresponding to an entry in the log header. +:param timestamp: (時間戳記) Select the timestamp unit that will be automatically added as the first column in every row. Timestamp values can be one of ``log.MILLISECONDS``, ``log.SECONDS``, ``log.MINUTES``, ``log.HOURS``, ``log.DAYS`` or ``None`` to disable the timestamp. The default value is ``log.SECONDS``.""" ... @overload -def add( - data_dictionary: Optional[Mapping[str, Union[str, int, float]]], -) -> None: - """Add a data row to the log by passing a dictionary of headers and values. +def add(data_dictionary: Optional[Mapping[str, Union[str, int, float]]]) -> None: + """透過傳遞包含標頭和數值的字典,將資料列新增至紀錄中。 - Example: ``log.add({ 'temp': temperature() })`` +Example: ``log.add({ 'temp': temperature() })`` - Each call to this function adds a row to the log. +Each call to this function adds a row to the log. - New labels not previously specified via the set_labels function, or by a - previous call to this function, will trigger a new header entry to be added - to the log with the extra labels. +New labels not previously specified via the set_labels function, or by a +previous call to this function, will trigger a new header entry to be added +to the log with the extra labels. - Labels previously specified and not present in a call to this function will - be skipped with an empty value in the log row. +Labels previously specified and not present in a call to this function will +be skipped with an empty value in the log row. - :param data_dictionary: The data to log as a dictionary with a key for each header. - """ +:param data_dictionary: (資料字典) The data to log as a dictionary with a key for each header.""" ... @overload def add(**kwargs: Union[str, int, float]) -> None: - """Add a data row to the log using keyword arguments. + """使用關鍵字引數,將資料列新增至紀錄中。 - Example: ``log.add(temp=temperature())`` +Example: ``log.add(temp=temperature())`` - Each call to this function adds a row to the log. +Each call to this function adds a row to the log. - New labels not previously specified via the set_labels function, or by a - previous call to this function, will trigger a new header entry to be added - to the log with the extra labels. +New labels not previously specified via the set_labels function, or by a +previous call to this function, will trigger a new header entry to be added +to the log with the extra labels. - Labels previously specified and not present in a call to this function will - be skipped with an empty value in the log row. - """ +Labels previously specified and not present in a call to this function will +be skipped with an empty value in the log row.""" ... def delete(full=False): - """Deletes the contents of the log, including headers. + """刪除紀錄的內容,包括標題。 - Example: ``log.delete()`` +Example: ``log.delete()`` - To add the log headers again the ``set_labels`` function should to be called after this function. +To add the log headers again the ``set_labels`` function should to be called after this function. - There are two erase modes; “full” completely removes the data from the physical storage, - and “fast” invalidates the data without removing it. +There are two erase modes; “full” completely removes the data from the physical storage, +and “fast” invalidates the data without removing it. - :param full: ``True`` selects a “full” erase and ``False`` selects the “fast” erase method. - """ +:param full: ``True`` selects a “full” erase and ``False`` selects the “fast” erase method.""" ... def set_mirroring(serial: bool): """Configure mirroring of the data logging activity to the serial output. - Example: ``log.set_mirroring(True)`` +Example: ``log.set_mirroring(True)`` - Serial mirroring is disabled by default. When enabled, it will print to serial each row logged into the log file. +Serial mirroring is disabled by default. When enabled, it will print to serial each row logged into the log file. - :param serial: ``True`` enables mirroring data to the serial output. - """ - ... +:param serial: ``True`` enables mirroring data to the serial output.""" + ... \ No newline at end of file diff --git a/lang/zh-tw/typeshed/stdlib/machine.pyi b/lang/zh-tw/typeshed/stdlib/machine.pyi index 2e82f5b..77a54b5 100644 --- a/lang/zh-tw/typeshed/stdlib/machine.pyi +++ b/lang/zh-tw/typeshed/stdlib/machine.pyi @@ -1,97 +1,84 @@ -"""Low-level utilities. -""" +"""低階公用程式。""" from typing import Any from .microbit import MicroBitDigitalPin def unique_id() -> bytes: - """Get a byte string with a unique identifier of a board. + """取得具有開發板的唯一識別碼之位元組字串。 - Example: ``machine.unique_id()`` +Example: ``machine.unique_id()`` - :return: An identifier that varies from one board instance to another. - """ +:return: An identifier that varies from one board instance to another.""" ... def reset() -> None: - """Reset the device in a manner similar to pushing the external RESET button. + """以類似於按下外部 RESET 按鍵的方式重置裝置。 - Example: ``machine.reset()`` - """ +Example: ``machine.reset()``""" ... def freq() -> int: - """Get the CPU frequency in hertz. + """取得以赫茲為單位的 CPU 頻率。 (頻率) - Example: ``machine.freq()`` +Example: ``machine.freq()`` - :return: The CPU frequency. - """ +:return: The CPU frequency.""" ... def disable_irq() -> Any: - """Disable interrupt requests. + """禁用中斷請求。 (禁用 irq) - Example: ``interrupt_state = machine.disable_irq()`` +Example: ``interrupt_state = machine.disable_irq()`` - :return: the previous IRQ state which should be considered an opaque value +:return: the previous IRQ state which should be considered an opaque value - The return value should be passed to the ``enable_irq`` function to restore - interrupts to their original state. - """ +The return value should be passed to the ``enable_irq`` function to restore +interrupts to their original state.""" ... def enable_irq(state: Any) -> None: - """Re-enable interrupt requests. + """重新啟用中斷請求。 (啟用 irq) - Example: ``machine.enable_irq(interrupt_state)`` +Example: ``machine.enable_irq(interrupt_state)`` - :param state: The value that was returned from the most recent call to the ``disable_irq`` function. - """ +:param state: 從最近一次調用 ``disable_irq`` 函式傳回的值。""" ... -def time_pulse_us( - pin: MicroBitDigitalPin, pulse_level: int, timeout_us: int = 1000000 -) -> int: - """Time a pulse on a pin. +def time_pulse_us(pin: MicroBitDigitalPin, pulse_level: int, timeout_us: int=1000000) -> int: + """計時引腳上的脈衝。 - Example: ``time_pulse_us(pin0, 1)`` +Example: ``time_pulse_us(pin0, 1)`` - If the current input value of the pin is different to ``pulse_level``, the - function first waits until the pin input becomes equal to - ``pulse_level``, then times the duration that the pin is equal to - ``pulse_level``. If the pin is already equal to ``pulse_level`` then timing - starts straight away. +If the current input value of the pin is different to ``pulse_level``, the +function first waits until the pin input becomes equal to +``pulse_level``, then times the duration that the pin is equal to +``pulse_level``. If the pin is already equal to ``pulse_level`` then timing +starts straight away. - :param pin: The pin to use - :param pulse_level: 0 to time a low pulse or 1 to time a high pulse - :param timeout_us: A microsecond timeout - :return: The duration of the pulse in microseconds, or -1 for a timeout waiting for the level to match ``pulse_level``, or -2 on timeout waiting for the pulse to end - """ +:param pin: (引腳) 要使用的引腳 +:param pulse_level: 0 到計時低脈衝或 1 到計時高脈衝 +:param timeout_us: 微秒逾時 +:return: The duration of the pulse in microseconds, or -1 for a timeout waiting for the level to match ``pulse_level``, or -2 on timeout waiting for the pulse to end""" ... class mem: - """The class for the ``mem8``, ``mem16`` and ``mem32`` memory views.""" + """``mem8``、``mem16`` 和 ``mem32`` 記憶體檢視的類別。""" def __getitem__(self, address: int) -> int: - """Access a value from memory. + """從記憶體中存取一個值。 - :param address: The memory address. - :return: The value at that address as an integer. - """ +:param address: 記憶體位址。 +:return: The value at that address as an integer.""" ... + def __setitem__(self, address: int, value: int) -> None: - """Set a value at the given address. + """在指定位址設定一個值。 - :param address: The memory address. - :param value: The integer value to set. - """ +:param address: 記憶體位址。 +:param value: 要設定的整數值。""" ... - mem8: mem -"""8-bit (byte) view of memory.""" - +"""8 位元 (位元組) 的記憶體檢視。""" mem16: mem -"""16-bit view of memory.""" - +"""16 位元的記憶體檢視。""" mem32: mem -"""32-bit view of memory.""" +"""32 位元的記憶體檢視。""" \ No newline at end of file diff --git a/lang/zh-tw/typeshed/stdlib/math.pyi b/lang/zh-tw/typeshed/stdlib/math.pyi index f82d4de..c4117a7 100644 --- a/lang/zh-tw/typeshed/stdlib/math.pyi +++ b/lang/zh-tw/typeshed/stdlib/math.pyi @@ -1,273 +1,246 @@ -"""Mathematical functions. -""" - +"""數學函式。""" from typing import Tuple def acos(x: float) -> float: - """Calculate the inverse cosine. + """計算反餘弦。 - Example: ``math.acos(1)`` +Example: ``math.acos(1)`` - :param x: A number - :return: The inverse cosine of ``x`` - """ +:param x: 一個數字 +:return: The inverse cosine of ``x``""" ... def asin(x: float) -> float: - """Calculate the inverse sine. + """計算反正弦。 - Example: ``math.asin(0)`` +Example: ``math.asin(0)`` - :param x: A number - :return: The inverse sine of ``x`` - """ +:param x: 一個數字 +:return: The inverse sine of ``x``""" ... def atan(x: float) -> float: - """Calculate the inverse tangent. + """計算反正切。 - Example: ``math.atan(0)`` +Example: ``math.atan(0)`` - :param x: A number - :return: The inverse tangent of ``x`` - """ +:param x: 一個數字 +:return: The inverse tangent of ``x``""" ... def atan2(y: float, x: float) -> float: - """Calculate the principal value of the inverse tangent of ``y/x``. + """計算 ``y/x`` 的反正切主值。 - Example: ``math.atan2(0, -1)`` +Example: ``math.atan2(0, -1)`` - :param y: A number - :param x: A number - :return: The principal value of the inverse tangent of ``y/x`` - """ +:param y: 一個數字 +:param x: 一個數字 +:return: The principal value of the inverse tangent of ``y/x``""" ... def ceil(x: float) -> float: - """Round a number towards positive infinity. + """將數字向正無限大捨入。 - Example: ``math.ceil(0.1)`` +Example: ``math.ceil(0.1)`` - :param x: A number - :return: ``x`` rounded towards positive infinity. - """ +:param x: 一個數字 +:return: ``x`` rounded towards positive infinity.""" ... def copysign(x: float, y: float) -> float: - """Calculate ``x`` with the sign of ``y``. + """用 ``y`` 的符號計算 ``x``。 - Example: ``math.copysign(1, -1)`` +Example: ``math.copysign(1, -1)`` - :param x: A number - :param y: The source of the sign for the return value - :return: ``x`` with the sign of ``y`` - """ +:param x: 一個數字 +:param y: 傳回值的符號來源 +:return: ``x`` with the sign of ``y``""" ... def cos(x: float) -> float: - """Calculate the cosine of ``x``. + """計算 ``x`` 的餘弦。 - Example: ``math.cos(0)`` +Example: ``math.cos(0)`` - :param x: A number - :return: The cosine of ``x`` - """ +:param x: 一個數字 +:return: The cosine of ``x``""" ... def degrees(x: float) -> float: - """Convert radians to degrees. + """將弧度 (Radians) 轉換為度 (Degrees) (度) - Example: ``math.degrees(2 * math.pi)`` +Example: ``math.degrees(2 * math.pi)`` - :param x: A value in radians - :return: The value converted to degrees""" +:param x: 單位為弧度的數值 +:return: The value converted to degrees""" ... def exp(x: float) -> float: - """Calculate the exponential of ``x``. + """計算 ``x`` 的指數。 (指數) - Example: ``math.exp(1)`` +Example: ``math.exp(1)`` - :param x: A number - :return: The exponential of ``x``. - """ +:param x: 一個數字 +:return: The exponential of ``x``.""" ... def fabs(x: float) -> float: - """Return the absolute value of ``x``. + """傳回 ``x`` 的絕對值。 - Example: ``math.fabs(-0.1)`` +Example: ``math.fabs(-0.1)`` - :param x: A number - :return: The absolute value of ``x`` - """ +:param x: 一個數字 +:return: The absolute value of ``x``""" ... def floor(x: float) -> int: - """Round a number towards negative infinity. + """將數字向負無限大捨入。 - Example: ``math.floor(0.9)`` +Example: ``math.floor(0.9)`` - :param x: A number - :return: ``x`` rounded towards negative infinity. - """ +:param x: 一個數字 +:return: ``x`` rounded towards negative infinity.""" ... def fmod(x: float, y: float) -> float: - """Calculate the remainder of ``x/y``. + """計算 ``x/y`` 的餘數。 - Example: ``math.fmod(10, 3)`` +Example: ``math.fmod(10, 3)`` - :param x: The numerator - :param y: The denominator - """ +:param x: 分子 +:param y: 分母""" ... def frexp(x: float) -> Tuple[float, int]: - """Decomposes a floating-point number into its mantissa and exponent. + """將一個浮點數分解為其尾數和指數。 - Example: ``mantissa, exponent = math.frexp(2)`` +Example: ``mantissa, exponent = math.frexp(2)`` - The returned value is the tuple ``(m, e)`` such that ``x == m * 2**e`` - exactly. If ``x == 0`` then the function returns ``(0.0, 0)``, otherwise - the relation ``0.5 <= abs(m) < 1`` holds. +The returned value is the tuple ``(m, e)`` such that ``x == m * 2**e`` +exactly. If ``x == 0`` then the function returns ``(0.0, 0)``, otherwise +the relation ``0.5 <= abs(m) < 1`` holds. - :param x: A floating-point number - :return: A tuple of length two containing its mantissa then exponent - """ +:param x: 一個浮點數 +:return: A tuple of length two containing its mantissa then exponent""" ... def isfinite(x: float) -> bool: - """Check if a value is finite. + """檢查值是否為有限。 - Example: ``math.isfinite(float('inf'))`` +Example: ``math.isfinite(float('inf'))`` - :param x: A number. - :return: ``True`` if ``x`` is finite, ``False`` otherwise. - """ +:param x: 一個數字。 +:return: ``True`` if ``x`` is finite, ``False`` otherwise.""" ... def isinf(x: float) -> bool: - """Check if a value is infinite. + """檢查值是否為無限。 - Example: ``math.isinf(float('-inf'))`` +Example: ``math.isinf(float('-inf'))`` - :param x: A number. - :return: ``True`` if ``x`` is infinite, ``False`` otherwise. - """ +:param x: 一個數字。 +:return: ``True`` if ``x`` is infinite, ``False`` otherwise.""" ... def isnan(x: float) -> bool: - """Check if a value is not-a-number (NaN). + """檢查值是否為非數字 (NaN)。 - Example: ``math.isnan(float('nan'))`` +Example: ``math.isnan(float('nan'))`` - :param x: A number - :return: ``True`` if ``x`` is not-a-number (NaN), ``False`` otherwise.""" +:param x: 一個數字 +:return: ``True`` if ``x`` is not-a-number (NaN), ``False`` otherwise.""" ... def ldexp(x: float, exp: int) -> float: - """Calculate ``x * (2**exp)``. + """計算 ``x * (2**exp)``。 - Example: ``math.ldexp(0.5, 2)`` +Example: ``math.ldexp(0.5, 2)`` - :param x: A number - :param exp: Integer exponent - :return: ``x * (2**exp)`` - """ +:param x: 一個數字 +:param exp: (指數) 整數指數 +:return: ``x * (2**exp)``""" ... -def log(x: float, base: float = e) -> float: - """Calculate the logarithm of ``x`` to the given base (defaults to natural logorithm). +def log(x: float, base: float=e) -> float: + """計算指定底數 ``x`` 的對數 (預設為自然對數)。 - Example: ``math.log(math.e)`` +Example: ``math.log(math.e)`` - With one argument, return the natural logarithm of x (to base e). +With one argument, return the natural logarithm of x (to base e). - With two arguments, return the logarithm of x to the given base, calculated as ``log(x)/log(base)``. +With two arguments, return the logarithm of x to the given base, calculated as ``log(x)/log(base)``. - :param x: A number - :param base: The base to use - :return: The natural logarithm of ``x`` - """ +:param x: 一個數字 +:param base: 要使用的底數 +:return: The natural logarithm of ``x``""" ... def modf(x: float) -> Tuple[float, float]: - """Calculate the fractional and integral parts of ``x``. + """計算 ``x`` 的小數部分和整數部分。 - Example: ``fractional, integral = math.modf(1.5)`` +Example: ``fractional, integral = math.modf(1.5)`` - :param x: A number - :return: A tuple of two floats representing the fractional then integral parts of ``x``. +:param x: 一個數字 +:return: A tuple of two floats representing the fractional then integral parts of ``x``. - Both the fractional and integral values have the same sign as ``x``. - """ +Both the fractional and integral values have the same sign as ``x``.""" ... def pow(x: float, y: float) -> float: - """Returns ``x`` to the power of ``y``. + """傳回 ``x`` 的 ``y`` 次方。 - Example: ``math.pow(4, 0.5)`` +Example: ``math.pow(4, 0.5)`` - :param x: A number - :param y: The exponent - :return: ``x`` to the power of ``y`` - """ +:param x: 一個數字 +:param y: 指數 +:return: ``x`` to the power of ``y``""" ... def radians(x: float) -> float: - """Convert a degrees to radians. + """將角度轉換為弧度。 - Example: ``math.radians(360)`` +Example: ``math.radians(360)`` - :param x: A value in degrees - :return: The value converted to radians - """ +:param x: 以角度為單位的值 +:return: The value converted to radians""" ... def sin(x: float) -> float: - """Calculate the sine of ``x``. + """計算 ``x`` 的正弦。 - Example: ``math.sin(math.pi/2)`` +Example: ``math.sin(math.pi/2)`` - :param x: A number - :return: The sine of ``x`` - """ +:param x: 一個數字 +:return: The sine of ``x``""" ... def sqrt(x: float) -> float: - """Calculate the square root of ``x``. + """計算 ``x`` 的平方根。 - Example: ``math.sqrt(4)`` +Example: ``math.sqrt(4)`` - :param x: A number - :return: The square root of ``x`` - """ +:param x: 一個數字 +:return: The square root of ``x``""" ... def tan(x: float) -> float: - """Calculate the tangent of ``x``. + """計算 ``x`` 的正切。 - Example: ``math.tan(0)`` +Example: ``math.tan(0)`` - :param x: A number - :return: The tangent of ``x``. - """ +:param x: 一個數字 +:return: The tangent of ``x``.""" ... def trunc(x: float) -> int: - """Round a number towards 0. + """將數字向 0 捨入。 - Example: ``math.trunc(-0.9)`` +Example: ``math.trunc(-0.9)`` - :param x: A number - :return: ``x`` rounded towards zero. - """ +:param x: 一個數字 +:return: ``x`` rounded towards zero.""" ... - e: float -"""Base of the natural logarithm""" - +"""自然對數的底數""" pi: float -"""The ratio of a circle's circumference to its diameter""" +"""圓的周長與其直徑的比率""" \ No newline at end of file diff --git a/lang/zh-tw/typeshed/stdlib/microbit/__init__.pyi b/lang/zh-tw/typeshed/stdlib/microbit/__init__.pyi index f12158f..0e2e313 100644 --- a/lang/zh-tw/typeshed/stdlib/microbit/__init__.pyi +++ b/lang/zh-tw/typeshed/stdlib/microbit/__init__.pyi @@ -1,11 +1,6 @@ -"""Pins, images, sounds, temperature and volume. -""" - +"""引腳、影像、聲音、溫度和音量。""" from typing import Any, Callable, List, Optional, Tuple, Union, overload - from _typeshed import ReadableBuffer - -# V2 only from . import accelerometer as accelerometer from . import audio as audio from . import compass as compass @@ -16,831 +11,696 @@ from . import speaker as speaker from . import spi as spi from . import uart as uart -def run_every( - callback: Optional[Callable[[], None]] = None, - days: int = 0, - h: int = 0, - min: int = 0, - s: int = 0, - ms: int = 0, -) -> Callable[[Callable[[], None]], Callable[[], None]]: +def run_every(callback: Optional[Callable[[], None]]=None, days: int=0, h: int=0, min: int=0, s: int=0, ms: int=0) -> Callable[[Callable[[], None]], Callable[[], None]]: """Schedule to run a function at the interval specified by the time arguments **V2 only**. - Example: ``run_every(my_logging, min=5)`` +Example: ``run_every(my_logging, min=5)`` - ``run_every`` can be used in two ways: +``run_every`` can be used in two ways: - As a Decorator - placed on top of the function to schedule. For example:: +As a Decorator - placed on top of the function to schedule. For example:: - @run_every(h=1, min=20, s=30, ms=50) - def my_function(): - # Do something here + @run_every(h=1, min=20, s=30, ms=50) + def my_function(): + # Do something here - As a Function - passing the callback as a positional argument. For example:: +As a Function - passing the callback as a positional argument. For example:: - def my_function(): - # Do something here - run_every(my_function, s=30) + def my_function(): + # Do something here + run_every(my_function, s=30) - Each argument corresponds to a different time unit and they are additive. - So ``run_every(min=1, s=30)`` schedules the callback every minute and a half. +Each argument corresponds to a different time unit and they are additive. +So ``run_every(min=1, s=30)`` schedules the callback every minute and a half. - When an exception is thrown inside the callback function it deschedules the - function. To avoid this you can catch exceptions with ``try/except``. +When an exception is thrown inside the callback function it deschedules the +function. To avoid this you can catch exceptions with ``try/except``. - :param callback: Function to call at the provided interval. Omit when using as a decorator. - :param days: Sets the day mark for the scheduling. - :param h: Sets the hour mark for the scheduling. - :param min: Sets the minute mark for the scheduling. - :param s: Sets the second mark for the scheduling. - :param ms: Sets the millisecond mark for the scheduling. - """ +:param callback: Function to call at the provided interval. Omit when using as a decorator. +:param days: Sets the day mark for the scheduling. +:param h: Sets the hour mark for the scheduling. +:param min: Sets the minute mark for the scheduling. +:param s: Sets the second mark for the scheduling. +:param ms: Sets the millisecond mark for the scheduling.""" def panic(n: int) -> None: - """Enter a panic mode. + """進入緊急模式。 - Example: ``panic(127)`` +Example: ``panic(127)`` - :param n: An arbitrary integer <= 255 to indicate a status. +:param n: 任意整數 <= 255 以表示狀態。 - Requires restart. - """ +Requires restart.""" def reset() -> None: - """Restart the board.""" - + """重啟開發板。""" @overload def scale(value: float, from_: Tuple[float, float], to: Tuple[int, int]) -> int: """Converts a value from a range to an integer range. - Example: ``volume = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255))`` +Example: ``volume = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255))`` - For example, to convert an accelerometer X value to a speaker volume. +For example, to convert an accelerometer X value to a speaker volume. - If one of the numbers in the ``to`` parameter is a floating point - (i.e a decimal number like ``10.0``), this function will return a - floating point number. +If one of the numbers in the ``to`` parameter is a floating point +(i.e a decimal number like ``10.0``), this function will return a +floating point number. - temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0)) + temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0)) - :param value: A number to convert. - :param from_: A tuple to define the range to convert from. - :param to: A tuple to define the range to convert to. - :return: The ``value`` converted to the ``to`` range. - """ +:param value: A number to convert. +:param from_: A tuple to define the range to convert from. +:param to: A tuple to define the range to convert to. +:return: The ``value`` converted to the ``to`` range.""" @overload def scale(value: float, from_: Tuple[float, float], to: Tuple[float, float]) -> float: """Converts a value from a range to a floating point range. - Example: ``temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0))`` +Example: ``temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0))`` - For example, to convert temperature from a Celsius scale to Fahrenheit. +For example, to convert temperature from a Celsius scale to Fahrenheit. - If one of the numbers in the ``to`` parameter is a floating point - (i.e a decimal number like ``10.0``), this function will return a - floating point number. - If they are both integers (i.e ``10``), it will return an integer:: +If one of the numbers in the ``to`` parameter is a floating point +(i.e a decimal number like ``10.0``), this function will return a +floating point number. +If they are both integers (i.e ``10``), it will return an integer:: - returns_int = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255)) + returns_int = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255)) - :param value: A number to convert. - :param from_: A tuple to define the range to convert from. - :param to: A tuple to define the range to convert to. - :return: The ``value`` converted to the ``to`` range. - """ +:param value: A number to convert. +:param from_: A tuple to define the range to convert from. +:param to: A tuple to define the range to convert to. +:return: The ``value`` converted to the ``to`` range.""" def sleep(n: float) -> None: - """Wait for ``n`` milliseconds. + """等待 ``n`` 毫秒。 - Example: ``sleep(1000)`` +Example: ``sleep(1000)`` - :param n: The number of milliseconds to wait +:param n: 要等待的毫秒數。 - One second is 1000 milliseconds, so:: +One second is 1000 milliseconds, so:: - microbit.sleep(1000) + microbit.sleep(1000) - will pause the execution for one second. - """ +will pause the execution for one second.""" def running_time() -> int: - """Get the running time of the board. + """取得開發板的執行時間。 - :return: The number of milliseconds since the board was switched on or restarted. - """ +:return: The number of milliseconds since the board was switched on or restarted.""" def temperature() -> int: - """Get the temperature of the micro:bit in degrees Celsius.""" + """取得 micro:bit 的溫度 (以攝氏為單位)。 (溫度)""" def set_volume(v: int) -> None: - """Sets the volume. + """設定音量。 - Example: ``set_volume(127)`` +Example: ``set_volume(127)`` - :param v: a value between 0 (low) and 255 (high). +:param v: 介於 0 (低) 和 255 (高) 之間的值。 - Out of range values will be clamped to 0 or 255. +Out of range values will be clamped to 0 or 255. - **V2** only. - """ +**V2** only.""" ... class Button: - """The class for the buttons ``button_a`` and ``button_b``.""" + """按鈕 ``button_a`` 和 ``button_b`` 的類別。""" def is_pressed(self) -> bool: - """Check if the button is pressed. + """檢查按鈕是否有按下。 - :return: ``True`` if the specified button ``button`` is pressed, and ``False`` otherwise. - """ +:return: ``True`` if the specified button ``button`` is pressed, and ``False`` otherwise.""" ... + def was_pressed(self) -> bool: - """Check if the button was pressed since the device started or the last time this method was called. + """檢查自裝置啟動或上次呼叫此方法以來,是否有按下該按鈕。 - Calling this method will clear the press state so - that the button must be pressed again before this method will return - ``True`` again. +Calling this method will clear the press state so +that the button must be pressed again before this method will return +``True`` again. - :return: ``True`` if the specified button ``button`` was pressed, and ``False`` otherwise - """ +:return: ``True`` if the specified button ``button`` was pressed, and ``False`` otherwise""" ... + def get_presses(self) -> int: - """Get the running total of button presses, and resets this total - to zero before returning. + """取得按下按鈕的執行總數,並在傳回前將此總數重設為零。 - :return: The number of presses since the device started or the last time this method was called - """ +:return: The number of presses since the device started or the last time this method was called""" ... - button_a: Button -"""The left button ``Button`` object.""" - +"""左側按鈕 ``Button`` 物件。""" button_b: Button -"""The right button ``Button`` object.""" +"""右側按鈕 ``Button`` 物件。""" class MicroBitDigitalPin: - """A digital pin. - - Some pins support analog and touch features using the ``MicroBitAnalogDigitalPin`` and ``MicroBitTouchPin`` subclasses. - """ + """數位引腳。 +Some pins support analog and touch features using the ``MicroBitAnalogDigitalPin`` and ``MicroBitTouchPin`` subclasses.""" NO_PULL: int PULL_UP: int PULL_DOWN: int + def read_digital(self) -> int: - """Get the digital value of the pin. + """取得引腳的數位值。 - Example: ``value = pin0.read_digital()`` +Example: ``value = pin0.read_digital()`` - :return: 1 if the pin is high, and 0 if it's low. - """ +:return: 1 if the pin is high, and 0 if it's low.""" ... + def write_digital(self, value: int) -> None: - """Set the digital value of the pin. + """設定引腳的數位值。 - Example: ``pin0.write_digital(1)`` +Example: ``pin0.write_digital(1)`` - :param value: 1 to set the pin high or 0 to set the pin low""" +:param value: 1 將引腳設為高電平,或 0 將引腳設為低電平""" ... + def set_pull(self, value: int) -> None: - """Set the pull state to one of three possible values: ``PULL_UP``, ``PULL_DOWN`` or ``NO_PULL``. + """將提取狀態設為三個可能值之一:``PULL_UP``、``PULL_DOWN`` 或 ``NO_PULL``。 - Example: ``pin0.set_pull(pin0.PULL_UP)`` +Example: ``pin0.set_pull(pin0.PULL_UP)`` - :param value: The pull state from the relevant pin, e.g. ``pin0.PULL_UP``. - """ +:param value: 相關引腳的提取狀態,例如 ``pin0.PULL_UP``。""" ... + def get_pull(self) -> int: - """Get the pull state on a pin. + """取得引腳上的提取狀態。 - Example: ``pin0.get_pull()`` +Example: ``pin0.get_pull()`` - :return: ``NO_PULL``, ``PULL_DOWN``, or ``PULL_UP`` +:return: ``NO_PULL``, ``PULL_DOWN``, or ``PULL_UP`` - These are set using the ``set_pull()`` method or automatically configured - when a pin mode requires it. - """ +These are set using the ``set_pull()`` method or automatically configured +when a pin mode requires it.""" ... + def get_mode(self) -> str: - """Returns the pin mode. + """傳回引腳模式。 - Example: ``pin0.get_mode()`` +Example: ``pin0.get_mode()`` - When a pin is used for a specific function, like - writing a digital value, or reading an analog value, the pin mode - changes. +When a pin is used for a specific function, like +writing a digital value, or reading an analog value, the pin mode +changes. - :return: ``"unused"``, ``"analog"``, ``"read_digital"``, ``"write_digital"``, ``"display"``, ``"button"``, ``"music"``, ``"audio"``, ``"touch"``, ``"i2c"``, or ``"spi"`` - """ +:return: ``"unused"``, ``"analog"``, ``"read_digital"``, ``"write_digital"``, ``"display"``, ``"button"``, ``"music"``, ``"audio"``, ``"touch"``, ``"i2c"``, or ``"spi"``""" ... + def write_analog(self, value: int) -> None: - """Output a PWM signal on the pin, with the duty cycle proportional to ``value``. + """在引腳上輸出 PWM 訊號,工作週期與 ``value`` 成正比。 + +Example: ``pin0.write_analog(254)`` - Example: ``pin0.write_analog(254)`` +:param value: 介於 0 (0% 工作週期) 和 1023 (100% 工作週期) 之間的整數或浮點數。""" - :param value: 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. + """將輸出的 PWM 訊號週期設為 ``period`` (以毫秒為單位)。 - Example: ``pin0.set_analog_period(10)`` +Example: ``pin0.set_analog_period(10)`` + +:param period: 以毫秒為單位的週期,最小有效值為 1ms。""" - :param period: The period in milliseconds with a minimum valid value of 1ms. - """ def set_analog_period_microseconds(self, period: int) -> None: - """Set the period of the PWM signal being output to ``period`` in microseconds. + """將輸出的 PWM 訊號週期設為 ``period`` (以微秒為單位)。 - Example: ``pin0.set_analog_period_microseconds(512)`` +Example: ``pin0.set_analog_period_microseconds(512)`` - :param period: The period in microseconds with a minimum valid value of 256µs. - """ +:param period: 以微秒為單位的週期,最小有效值為 256µs。""" class MicroBitAnalogDigitalPin(MicroBitDigitalPin): - """A pin with analog and digital features.""" + """具有類比和數位功能的引腳。""" def read_analog(self) -> int: - """Read the voltage applied to the pin. + """讀取施加到引腳的電壓。 - Example: ``pin0.read_analog()`` +Example: ``pin0.read_analog()`` - :return: An integer between 0 (meaning 0V) and 1023 (meaning 3.3V). - """ +:return: An integer between 0 (meaning 0V) and 1023 (meaning 3.3V).""" class MicroBitTouchPin(MicroBitAnalogDigitalPin): - """A pin with analog, digital and touch features.""" - + """具有類比、數位和觸控功能的引腳。""" CAPACITIVE: int RESISTIVE: int + def is_touched(self) -> bool: - """Check if the pin is being touched. + """檢查引腳是否受觸控。 - Example: ``pin0.is_touched()`` +Example: ``pin0.is_touched()`` - The default touch mode for the pins on the edge connector is ``resistive``. - The default for the logo pin **V2** is ``capacitive``. +The default touch mode for the pins on the edge connector is ``resistive``. +The default for the logo pin **V2** is ``capacitive``. - **Resistive touch** - This test is done by measuring how much resistance there is between the - pin and ground. A low resistance gives a reading of ``True``. To get - a reliable reading using a finger you may need to touch the ground pin - with another part of your body, for example your other hand. +**Resistive touch** +This test is done by measuring how much resistance there is between the +pin and ground. A low resistance gives a reading of ``True``. To get +a reliable reading using a finger you may need to touch the ground pin +with another part of your body, for example your other hand. - **Capacitive touch** - This test is done by interacting with the electric field of a capacitor - using a finger as a conductor. `Capacitive touch - `_ - does not require you to make a ground connection as part of a circuit. +**Capacitive touch** +This test is done by interacting with the electric field of a capacitor +using a finger as a conductor. `Capacitive touch +`_ +does not require you to make a ground connection as part of a circuit. - :return: ``True`` if the pin is being touched with a finger, otherwise return ``False``. - """ +:return: ``True`` if the pin is being touched with a finger, otherwise return ``False``.""" ... + def set_touch_mode(self, value: int) -> None: - """Set the touch mode for the pin. + """設定引腳的觸控模式。 - Example: ``pin0.set_touch_mode(pin0.CAPACITIVE)`` +Example: ``pin0.set_touch_mode(pin0.CAPACITIVE)`` - The default touch mode for the pins on the edge connector is - ``resistive``. The default for the logo pin **V2** is ``capacitive``. +The default touch mode for the pins on the edge connector is +``resistive``. The default for the logo pin **V2** is ``capacitive``. - :param value: ``CAPACITIVE`` or ``RESISTIVE`` from the relevant pin. - """ +:param value: 相關引腳的 ``CAPACITIVE`` 或 ``RESISTIVE``。""" ... - pin0: MicroBitTouchPin -"""Pin with digital, analog and touch features.""" - +"""具有數位、類比和觸控功能的引腳。 (引腳 0)""" pin1: MicroBitTouchPin -"""Pin with digital, analog and touch features.""" - +"""具有數位、類比和觸控功能的引腳。 (引腳 1)""" pin2: MicroBitTouchPin -"""Pin with digital, analog and touch features.""" - +"""具有數位、類比和觸控功能的引腳。 (引腳 2)""" pin3: MicroBitAnalogDigitalPin -"""Pin with digital and analog features.""" - +"""具有數位和類比功能的引腳。 (引腳 3)""" pin4: MicroBitAnalogDigitalPin -"""Pin with digital and analog features.""" - +"""具有數位和類比功能的引腳。 (引腳 4)""" pin5: MicroBitDigitalPin -"""Pin with digital features.""" - +"""具有數位功能的引腳。 (引腳 5)""" pin6: MicroBitDigitalPin -"""Pin with digital features.""" - +"""具有數位功能的引腳。 (引腳 6)""" pin7: MicroBitDigitalPin -"""Pin with digital features.""" - +"""具有數位功能的引腳。 (引腳 7)""" pin8: MicroBitDigitalPin -"""Pin with digital features.""" - +"""具有數位功能的引腳。 (引腳 8)""" pin9: MicroBitDigitalPin -"""Pin with digital features.""" - +"""具有數位功能的引腳。 (引腳 9)""" pin10: MicroBitAnalogDigitalPin -"""Pin with digital and analog features.""" - +"""具有數位和類比功能的引腳。 (引腳 10)""" pin11: MicroBitDigitalPin -"""Pin with digital features.""" - +"""具有數位功能的引腳。 (引腳 11)""" pin12: MicroBitDigitalPin -"""Pin with digital features.""" - +"""具有數位功能的引腳。 (引腳 12)""" pin13: MicroBitDigitalPin -"""Pin with digital features.""" - +"""具有數位功能的引腳。 (引腳 13)""" pin14: MicroBitDigitalPin -"""Pin with digital features.""" - +"""具有數位功能的引腳。 (引腳 14)""" pin15: MicroBitDigitalPin -"""Pin with digital features.""" - +"""具有數位功能的引腳。 (引腳 15)""" pin16: MicroBitDigitalPin -"""Pin with digital features.""" - +"""具有數位功能的引腳。 (引腳 16)""" pin19: MicroBitDigitalPin -"""Pin with digital features.""" - +"""具有數位功能的引腳。 (引腳 19)""" pin20: MicroBitDigitalPin -"""Pin with digital features.""" - +"""具有數位功能的引腳。 (引腳 20)""" pin_logo: MicroBitTouchPin -"""A touch sensitive logo pin on the front of the micro:bit, which by default is set to capacitive touch mode.""" - +"""micro:bit 正面的觸控感應標誌引腳,預設為電容式觸控模式。""" pin_speaker: MicroBitAnalogDigitalPin -"""A pin to address the micro:bit speaker. +"""用於定址 micro:bit 揚聲器的引腳。 This API is intended only for use in Pulse-Width Modulation pin operations e.g. pin_speaker.write_analog(128). """ class Image: - """An image to show on the micro:bit LED display. + """要在 micro:bit LED 顯示器上顯示的圖像。 (圖像) - Given an image object it's possible to display it via the ``display`` API:: - - display.show(Image.HAPPY) - """ +Given an image object it's possible to display it via the ``display`` API:: + display.show(Image.HAPPY)""" HEART: Image - """Heart image.""" - + """愛心圖像。""" HEART_SMALL: Image - """Small heart image.""" - + """小愛心圖像。""" HAPPY: Image - """Happy face image.""" - + """開心的臉圖像。 (開心)""" SMILE: Image - """Smiling mouth image.""" - + """笑臉圖像。 (微笑)""" SAD: Image - """Sad face image.""" - + """傷心的臉圖像。""" CONFUSED: Image - """Confused face image.""" - + """困惑的臉圖像。""" ANGRY: Image - """Angry face image.""" - + """生氣的臉圖像。""" ASLEEP: Image - """Sleeping face image.""" - + """睡臉圖像。""" SURPRISED: Image - """Surprised face image.""" - + """驚訝的臉圖像。""" SILLY: Image - """Silly face image.""" - + """鬼臉圖像。""" FABULOUS: Image - """Sunglasses face image.""" - + """戴太陽眼鏡的臉圖像。""" MEH: Image - """Unimpressed face image.""" - + """冷漠的臉圖像。""" YES: Image - """Tick image.""" - + """勾號圖像。""" NO: Image - """Cross image.""" - + """叉號圖像。""" CLOCK12: Image - """Image with line pointing to 12 o'clock.""" - + """指針指向 12 點鐘的圖像。""" CLOCK11: Image - """Image with line pointing to 11 o'clock.""" - + """指針指向 11 點鐘的圖像。""" CLOCK10: Image - """Image with line pointing to 10 o'clock.""" - + """指針指向 10 點鐘的圖像。""" CLOCK9: Image - """Image with line pointing to 9 o'clock.""" - + """指針指向 9 點鐘的圖像。""" CLOCK8: Image - """Image with line pointing to 8 o'clock.""" - + """指針指向 8 點鐘的圖像。""" CLOCK7: Image - """Image with line pointing to 7 o'clock.""" - + """指針指向 7 點鐘的圖像。""" CLOCK6: Image - """Image with line pointing to 6 o'clock.""" - + """指針指向 6 點鐘的圖像。""" CLOCK5: Image - """Image with line pointing to 5 o'clock.""" - + """指針指向 5 點鐘的圖像。""" CLOCK4: Image - """Image with line pointing to 4 o'clock.""" - + """指針指向 4 點鐘的圖像。""" CLOCK3: Image - """Image with line pointing to 3 o'clock.""" - + """指針指向 3 點鐘的圖像。""" CLOCK2: Image - """Image with line pointing to 2 o'clock.""" - + """指針指向 2 點鐘的圖像。""" CLOCK1: Image - """Image with line pointing to 1 o'clock.""" - + """指針指向 1 點鐘的圖像。""" ARROW_N: Image - """Image of arrow pointing north.""" - + """指向北方箭頭的圖像。""" ARROW_NE: Image - """Image of arrow pointing north east.""" - + """指向東北箭頭的圖像。""" ARROW_E: Image - """Image of arrow pointing east.""" - + """指向東方箭頭的圖像。""" ARROW_SE: Image - """Image of arrow pointing south east.""" - + """指向東南箭頭的圖像。""" ARROW_S: Image - """Image of arrow pointing south.""" - + """指向南方箭頭的圖像。""" ARROW_SW: Image - """Image of arrow pointing south west.""" - + """指向西南箭頭的圖像。""" ARROW_W: Image - """Image of arrow pointing west.""" - + """指向西方箭頭的圖像。""" ARROW_NW: Image - """Image of arrow pointing north west.""" - + """指向西北箭頭的圖像。""" TRIANGLE: Image - """Image of a triangle pointing up.""" - + """三角形朝上的圖像。""" TRIANGLE_LEFT: Image - """Image of a triangle in the left corner.""" - + """三角形朝左的圖像。""" CHESSBOARD: Image - """Alternate LEDs lit in a chessboard pattern.""" - + """以棋盤圖案交錯發亮的 LED 燈。""" DIAMOND: Image - """Diamond image.""" - + """鑽石圖像。""" DIAMOND_SMALL: Image - """Small diamond image.""" - + """小鑽石圖像。""" SQUARE: Image - """Square image.""" - + """正方形圖像。""" SQUARE_SMALL: Image - """Small square image.""" - + """小正方形圖像。""" RABBIT: Image - """Rabbit image.""" - + """兔子圖像。""" COW: Image - """Cow image.""" - + """乳牛圖像。""" MUSIC_CROTCHET: Image - """Crotchet note image.""" - + """四分音符圖像。""" MUSIC_QUAVER: Image - """Quaver note image.""" - + """八分音符圖像。""" MUSIC_QUAVERS: Image - """Pair of quavers note image.""" - + """一組八分音符圖像。""" PITCHFORK: Image - """Pitchfork image.""" - + """乾草叉圖像。""" XMAS: Image - """Christmas tree image.""" - + """聖誕樹圖像。""" PACMAN: Image - """Pac-Man arcade character image.""" - + """小精靈街機角色圖像。""" TARGET: Image - """Target image.""" - + """靶子圖像。""" TSHIRT: Image - """T-shirt image.""" - + """T 恤圖像。""" ROLLERSKATE: Image - """Rollerskate image.""" - + """輪式溜冰鞋圖像。""" DUCK: Image - """Duck image.""" - + """鴨子圖像。""" HOUSE: Image - """House image.""" - + """房子圖像。""" TORTOISE: Image - """Tortoise image.""" - + """陸龜圖像。""" BUTTERFLY: Image - """Butterfly image.""" - + """蝴蝶圖像。""" STICKFIGURE: Image - """Stick figure image.""" - + """簡筆畫圖像。""" GHOST: Image - """Ghost image.""" - + """幽靈圖像。""" SWORD: Image - """Sword image.""" - + """劍圖像。""" GIRAFFE: Image - """Giraffe image.""" - + """長頸鹿圖像。""" SKULL: Image - """Skull image.""" - + """骷髏頭圖像""" UMBRELLA: Image - """Umbrella image.""" - + """雨傘圖像。""" SNAKE: Image - """Snake image.""" - + """蛇圖像。""" SCISSORS: Image """Scissors image.""" - ALL_CLOCKS: List[Image] - """A list containing all the CLOCK_ images in sequence.""" - + """按順序包含所有 CLOCK_圖像的列表。""" ALL_ARROWS: List[Image] - """A list containing all the ARROW_ images in sequence.""" + """按順序包含所有 ARROW_圖像的列表。""" + @overload def __init__(self, string: str) -> None: - """Create an image from a string describing which LEDs are lit. + """從描述點亮哪些 LED 的字串建立圖像。 - ``string`` has to consist of digits 0-9 arranged into lines, - describing the image, for example:: +``string`` has to consist of digits 0-9 arranged into lines, +describing the image, for example:: - image = Image("90009:" - "09090:" - "00900:" - "09090:" - "90009") + 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 newlines (\\n) insead of the colons. +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 newlines (\\n) insead of the colons. - :param string: The string describing the image. - """ +:param string: 描述圖像的字串。""" ... + @overload - def __init__( - self, width: int = 5, height: int = 5, buffer: ReadableBuffer = None - ) -> None: - """Create an empty image with ``width`` columns and ``height`` rows. + def __init__(self, width: int=5, height: int=5, buffer: ReadableBuffer=None) -> None: + """建立一個 ``width`` 行 ``height`` 列的空白圖像。 - :param width: Optional width of the image - :param height: Optional height of the image - :param buffer: Optional array or bytes of ``width``×``height`` integers in range 0-9 to initialize the image +:param width: 可選的圖像寬度 +:param height: 可選的圖像高度 +:param buffer: 用可選陣列或在 0-9 範圍內的 ``width``×``height`` 整數位元組,來初始化圖像 - Examples:: +Examples:: - Image(2, 2, b'\x08\x08\x08\x08') - Image(2, 2, bytearray([9,9,9,9])) + Image(2, 2, b'\x08\x08\x08\x08') + Image(2, 2, bytearray([9,9,9,9])) - These create 2 x 2 pixel images at full brightness. - """ +These create 2 x 2 pixel images at full brightness.""" ... + def width(self) -> int: - """Get the number of columns. + """取得行數。 - :return: The number of columns in the image - """ +:return: The number of columns in the image""" ... + def height(self) -> int: - """Get the number of rows. + """取得列數。 - :return: The number of rows in the image - """ +:return: The number of rows in the image""" ... + def set_pixel(self, x: int, y: int, value: int) -> None: - """Set the brightness of a pixel. + """設定像素的亮度。 - Example: ``my_image.set_pixel(0, 0, 9)`` +Example: ``my_image.set_pixel(0, 0, 9)`` - :param x: The column number - :param y: The row number - :param value: The brightness as an integer between 0 (dark) and 9 (bright) +:param x: 行號 +:param y: 列號 +:param value: 亮度為介於 0 (暗) 和 9 (亮) 之間的整數 - This method will raise an exception when called on any of the built-in - read-only images, like ``Image.HEART``. - """ +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: - """Get the brightness of a pixel. + """取得像素的亮度。 - Example: ``my_image.get_pixel(0, 0)`` +Example: ``my_image.get_pixel(0, 0)`` - :param x: The column number - :param y: The row number - :return: The brightness as an integer between 0 and 9. - """ +:param x: 行號 +:param y: 列號 +:return: The brightness as an integer between 0 and 9.""" ... + def shift_left(self, n: int) -> Image: - """Create a new image by shifting the picture left. + """向左移動圖像,以建立新圖像。 - Example: ``Image.HEART_SMALL.shift_left(1)`` +Example: ``Image.HEART_SMALL.shift_left(1)`` - :param n: The number of columns to shift by - :return: The shifted image - """ +:param n: 要移動的行數 +:return: The shifted image""" ... + def shift_right(self, n: int) -> Image: - """Create a new image by shifting the picture right. + """向右移動圖像,以建立新圖像。 - Example: ``Image.HEART_SMALL.shift_right(1)`` +Example: ``Image.HEART_SMALL.shift_right(1)`` - :param n: The number of columns to shift by - :return: The shifted image - """ +:param n: 要移動的行數 +:return: The shifted image""" ... + def shift_up(self, n: int) -> Image: - """Create a new image by shifting the picture up. + """向上移動圖像,以建立新圖像。 - Example: ``Image.HEART_SMALL.shift_up(1)`` +Example: ``Image.HEART_SMALL.shift_up(1)`` - :param n: The number of rows to shift by - :return: The shifted image - """ +:param n: 要移動的列數 +:return: The shifted image""" ... + def shift_down(self, n: int) -> Image: - """Create a new image by shifting the picture down. + """透過向下移動圖像,以建立一個新圖像。 - Example: ``Image.HEART_SMALL.shift_down(1)`` +Example: ``Image.HEART_SMALL.shift_down(1)`` - :param n: The number of rows to shift by - :return: The shifted image - """ +:param n: 要移動的列數 +:return: The shifted image""" ... + def crop(self, x: int, y: int, w: int, h: int) -> Image: - """Create a new image by cropping the picture. + """透過裁剪圖像,以建立一個新圖像。 - Example: ``Image.HEART.crop(1, 1, 3, 3)`` +Example: ``Image.HEART.crop(1, 1, 3, 3)`` - :param x: The crop offset column - :param y: The crop offset row - :param w: The crop width - :param h: The crop height - :return: The new image - """ +:param x: 裁剪位移行 +:param y: 裁剪位移列 +:param w: 剪裁寬度 +:param h: 剪裁高度 +:return: The new image""" ... + def copy(self) -> Image: - """Create an exact copy of the image. + """建立圖像的精確副本。 - Example: ``Image.HEART.copy()`` +Example: ``Image.HEART.copy()`` - :return: The new image - """ +:return: The new image""" ... + def invert(self) -> Image: - """Create a new image by inverting the brightness of the pixels in the - source image. + """透過反轉來源圖像的像素亮度,以建立一個新圖像。 - Example: ``Image.SMALL_HEART.invert()`` +Example: ``Image.SMALL_HEART.invert()`` - :return: The new image. - """ +:return: The new image.""" ... + def fill(self, value: int) -> None: - """Set the brightness of all the pixels in the image. + """設定圖像中所有像素的亮度。 - Example: ``my_image.fill(5)`` +Example: ``my_image.fill(5)`` - :param value: The new brightness as a number between 0 (dark) and 9 (bright). +:param value: 新亮度為 0 (暗) 和 9 (亮) 之間的數字。 - This method will raise an exception when called on any of the built-in - read-only images, like ``Image.HEART``. - """ +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 an area from another image into this image. - - Example: ``my_image.blit(Image.HEART, 1, 1, 3, 3, 1, 1)`` - - :param src: The source image - :param x: The starting column offset in the source image - :param y: The starting row offset in the source image - :param w: The number of columns to copy - :param h: The number of rows to copy - :param xdest: The column offset to modify in this image - :param ydest: The row offset to modify in this image - - Pixels outside the source image are treated as having a brightness 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 blit(self, src: Image, x: int, y: int, w: int, h: int, xdest: int=0, ydest: int=0) -> None: + """將另一個圖像中的一個區域複製到該圖像中。 + +Example: ``my_image.blit(Image.HEART, 1, 1, 3, 3, 1, 1)`` + +:param src: 來源圖像 +:param x: 來源圖像中的起始行位移 +:param y: 來源圖像中的起始列位移 +:param w: 要複製的行數 +:param h: 要複製的列數 +:param xdest: 此圖像中要修改的行位移 +:param ydest: 此圖像中要修改的列位移 + +Pixels outside the source image are treated as having a brightness 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. + """透過將兩個圖像的像素亮度值相加,以建立一個新圖像。 - Example: ``Image.HEART + Image.HAPPY`` +Example: ``Image.HEART + Image.HAPPY`` - :param other: The image to add. - """ +:param other: 要新增的圖像。""" ... + def __sub__(self, other: Image) -> Image: - """Create a new image by subtracting the brightness values of the - other image from this image. + """透過從該圖像中減去另一個圖像的亮度值,以建立一個新圖像。 - Example: ``Image.HEART - Image.HEART_SMALL`` +Example: ``Image.HEART - Image.HEART_SMALL`` - :param other: The image to subtract. - """ +:param other: 要減去的圖像。""" ... + def __mul__(self, n: float) -> Image: - """Create a new image by multiplying the brightness of each pixel by - ``n``. + """將各像素的亮度乘以 ``n``,以建立新圖像。 - Example: ``Image.HEART * 0.5`` +Example: ``Image.HEART * 0.5`` - :param n: The value to multiply by. - """ +:param n: 要乘以的值。""" ... + def __truediv__(self, n: float) -> Image: - """Create a new image by dividing the brightness of each pixel by - ``n``. + """透過將各像素的亮度除以 ``n``,以建立一個新圖像。 - Example: ``Image.HEART / 2`` +Example: ``Image.HEART / 2`` - :param n: The value to divide by. - """ +:param n: 要除以的值。""" ... class SoundEvent: LOUD: SoundEvent - """Represents the transition of sound events, from ``quiet`` to ``loud`` like clapping or shouting.""" - + """表示聲音事件的轉換,從 ``quiet`` 到 ``loud``,如鼓掌或喊叫。""" QUIET: SoundEvent - """Represents the transition of sound events, from ``loud`` to ``quiet`` like speaking or background music.""" + """表示聲音事件的轉換,從 ``loud`` 到 ``quiet``。例如,說話或背景音樂。""" class Sound: - """The built-in sounds can be called using ``audio.play(Sound.NAME)``.""" - + """可以使用 ``audio.play(Sound.NAME)`` 調用內建聲音。""" GIGGLE: Sound - """Giggling sound.""" - + """咯咯笑的聲音。 (咯咯笑)""" HAPPY: Sound - """Happy sound.""" - + """開心的聲音。 (開心)""" HELLO: Sound - """Greeting sound.""" - + """歡迎的聲音。 (哈囉)""" MYSTERIOUS: Sound - """Mysterious sound.""" - + """神祕的聲音。 (神秘)""" SAD: Sound - """Sad sound.""" - + """難過的聲音。 (難過)""" SLIDE: Sound - """Sliding sound.""" - + """滑動的聲音。""" SOARING: Sound - """Soaring sound.""" - + """高昂的聲音。 (高昂)""" SPRING: Sound - """Spring sound.""" - + """彈跳的聲音。 (彈跳)""" TWINKLE: Sound - """Twinkling sound.""" - + """發亮的聲音。 (發亮)""" YAWN: Sound - """Yawning sound.""" + """呵欠的聲音。""" \ No newline at end of file diff --git a/lang/zh-tw/typeshed/stdlib/microbit/accelerometer.pyi b/lang/zh-tw/typeshed/stdlib/microbit/accelerometer.pyi index bac82c0..bb2e9ad 100644 --- a/lang/zh-tw/typeshed/stdlib/microbit/accelerometer.pyi +++ b/lang/zh-tw/typeshed/stdlib/microbit/accelerometer.pyi @@ -1,115 +1,103 @@ -"""Measure the acceleration of the micro:bit and recognise gestures. -""" - +"""測量 micro:bit 的加速度並識別手勢。""" from typing import Tuple def get_x() -> int: - """Get the acceleration measurement in the ``x`` axis in milli-g. + """取得 ``x`` 軸上的加速度測量值 (以毫克為單位)。 - Example: ``accelerometer.get_x()`` +Example: ``accelerometer.get_x()`` - :return: A positive or negative integer depending on direction in the range +/- 2000mg. - """ +:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" ... def get_y() -> int: - """Get the acceleration measurement in the ``y`` axis in milli-g. + """取得 ``y`` 軸上的加速度測量值 (以毫克為單位)。 - Example: ``accelerometer.get_y()`` +Example: ``accelerometer.get_y()`` - :return: A positive or negative integer depending on direction in the range +/- 2000mg. - """ +:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" ... def get_z() -> int: - """Get the acceleration measurement in the ``z`` axis in milli-g. + """取得 ``z`` 軸上的加速度測量值 (以毫克為單位)。 - Example: ``accelerometer.get_z()`` +Example: ``accelerometer.get_z()`` - :return: A positive or negative integer depending on direction in the range +/- 2000mg. - """ +:return: A positive or negative integer depending on direction in the range +/- 2000mg.""" ... def get_values() -> Tuple[int, int, int]: - """Get the acceleration measurements in all axes at once as a tuple. + """一次取得所有軸上的加速度測量值做為元組。 - Example: ``x, y, z = accelerometer.get_values()`` +Example: ``x, y, z = accelerometer.get_values()`` - :return: a three-element tuple of integers ordered as X, Y, Z, each value a positive or negative integer depending on direction in the range +/- 2000mg - """ +:return: a three-element tuple of integers ordered as X, Y, Z, each value a positive or negative integer depending on direction in the range +/- 2000mg""" ... def get_strength() -> int: """Get the acceleration measurement of all axes combined, as a positive integer. This is the Pythagorean sum of the X, Y and Z axes. - Example: ``accelerometer.get_strength()`` +Example: ``accelerometer.get_strength()`` - :return: The combined acceleration strength of all the axes, in milli-g. - """ +:return: The combined acceleration strength of all the axes, in milli-g.""" ... def current_gesture() -> str: - """Get the name of the current gesture. + """取得目前手勢的名稱。 - Example: ``accelerometer.current_gesture()`` +Example: ``accelerometer.current_gesture()`` - 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. +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. - :return: The current gesture - """ +:return: The current gesture""" ... def is_gesture(name: str) -> bool: - """Check if the named gesture is currently active. + """檢查命名的手勢目前是否處於活動狀態。 - Example: ``accelerometer.is_gesture('shake')`` +Example: ``accelerometer.is_gesture('shake')`` - 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. +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. - :param name: The gesture name. - :return: ``True`` if the gesture is active, ``False`` otherwise. - """ +:param name: 手勢名稱。 +:return: ``True`` if the gesture is active, ``False`` otherwise.""" ... def was_gesture(name: str) -> bool: - """Check if the named gesture was active since the last call. + """檢查命名手勢自上次呼叫後是否處於活動狀態。 - Example: ``accelerometer.was_gesture('shake')`` +Example: ``accelerometer.was_gesture('shake')`` - 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. +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. - :param name: The gesture name. - :return: ``True`` if the gesture was active since the last call, ``False`` otherwise. - """ +:param name: 手勢名稱。 +:return: ``True`` if the gesture was active since the last call, ``False`` otherwise.""" def get_gestures() -> Tuple[str, ...]: - """Return a tuple of the gesture history. + """傳回手勢歷史紀錄的元組。 - Example: ``accelerometer.get_gestures()`` +Example: ``accelerometer.get_gestures()`` - Clears the gesture history before returning. +Clears the gesture history before returning. - Gestures are not updated in the background so there needs to be constant - calls to some accelerometer method to do the gesture detection. Usually - gestures can be detected using a loop with a small :func:`microbit.sleep` delay. +Gestures are not updated in the background so there needs to be constant +calls to some accelerometer method to do the gesture detection. Usually +gestures can be detected using a loop with a small :func:`microbit.sleep` delay. - :return: The history as a tuple, most recent last. - """ +:return: The history as a tuple, most recent last.""" ... def set_range(value: int) -> None: """Set the accelerometer sensitivity range, in g (standard gravity), to the closest values supported by the hardware, so it rounds to either ``2``, ``4``, or ``8`` g. - Example: ``accelerometer.set_range(8)`` +Example: ``accelerometer.set_range(8)`` - :param value: New range for the accelerometer, an integer in ``g``. - """ +:param value: New range for the accelerometer, an integer in ``g``.""" \ No newline at end of file diff --git a/lang/zh-tw/typeshed/stdlib/microbit/audio.pyi b/lang/zh-tw/typeshed/stdlib/microbit/audio.pyi index 3b1e327..aa56a2c 100644 --- a/lang/zh-tw/typeshed/stdlib/microbit/audio.pyi +++ b/lang/zh-tw/typeshed/stdlib/microbit/audio.pyi @@ -1,160 +1,123 @@ -"""Play sounds using the micro:bit (import ``audio`` for V1 compatibility). -""" - +"""使用 micro:bit 播放聲音 (匯入 ``audio`` 與 V1 相容)。""" from ..microbit import MicroBitDigitalPin, Sound, pin0 from typing import ClassVar, Iterable, Union -def play( - source: Union[Iterable[AudioFrame], Sound, SoundEffect], - wait: bool = True, - pin: MicroBitDigitalPin = pin0, - return_pin: Union[MicroBitDigitalPin, None] = None, -) -> None: +def play(source: Union[Iterable[AudioFrame], Sound, SoundEffect], wait: bool=True, pin: MicroBitDigitalPin=pin0, return_pin: Union[MicroBitDigitalPin, None]=None) -> None: """Play a built-in sound, sound effect or custom audio frames. - Example: ``audio.play(Sound.GIGGLE)`` +Example: ``audio.play(Sound.GIGGLE)`` - :param source: A built-in ``Sound`` such as ``Sound.GIGGLE``, a ``SoundEffect`` or sample data as an iterable of ``AudioFrame`` objects. - :param wait: If ``wait`` is ``True``, this function will block until the sound is complete. - :param pin: An optional argument to specify the output pin can be used to override the default of ``pin0``. If we do not want any sound to play we can use ``pin=None``. - :param return_pin: Specifies a differential edge connector pin to connect to an external speaker instead of ground. This is ignored for the **V2** revision. - """ +:param source: A built-in ``Sound`` such as ``Sound.GIGGLE``, a ``SoundEffect`` or sample data as an iterable of ``AudioFrame`` objects. +:param wait: 如果 ``wait`` 為 ``True``,此函式將會封鎖,直到聲音完成。 +:param pin: (引腳) 指定輸出引腳的可選引數,可用於覆寫預設值 ``pin0``。如果我們不想播放任何聲音,我們可以使用 ``pin=None``。 +:param return_pin: 指定差分邊緣連接器引腳,以連接到外部揚聲器而不是接地。在 **V2** 修訂版中,這將會被忽略。""" def is_playing() -> bool: - """Check whether a sound is playing. + """檢查是否正在播放聲音。 - Example: ``audio.is_playing()`` +Example: ``audio.is_playing()`` - :return: ``True`` if audio is playing, otherwise ``False``.""" +:return: ``True`` if audio is playing, otherwise ``False``.""" ... def stop() -> None: - """Stop all audio playback. + """停止所有音訊播放。 - Example: ``audio.stop()`` - """ +Example: ``audio.stop()``""" ... class SoundEffect: """A sound effect, composed by a set of parameters configured via the constructor or attributes.""" - WAVEFORM_SINE: ClassVar[int] """Sine wave option used for the ``waveform`` parameter.""" - WAVEFORM_SAWTOOTH: ClassVar[int] """Sawtooth wave option used for the ``waveform`` parameter.""" - WAVEFORM_TRIANGLE: ClassVar[int] """Triangle wave option used for the ``waveform`` parameter.""" - WAVEFORM_SQUARE: ClassVar[int] """Square wave option used for the ``waveform`` parameter.""" - WAVEFORM_NOISE: ClassVar[int] """Noise option used for the ``waveform`` parameter.""" - SHAPE_LINEAR: ClassVar[int] """Linear interpolation option used for the ``shape`` parameter.""" - SHAPE_CURVE: ClassVar[int] """Curve interpolation option used for the ``shape`` parameter.""" - SHAPE_LOG: ClassVar[int] """Logarithmic interpolation option used for the ``shape`` parameter.""" - FX_NONE: ClassVar[int] """No effect option used for the ``fx`` parameter.""" - FX_TREMOLO: ClassVar[int] """Tremolo effect option used for the ``fx`` parameter.""" - FX_VIBRATO: ClassVar[int] """Vibrato effect option used for the ``fx`` parameter.""" - FX_WARBLE: ClassVar[int] """Warble effect option used for the ``fx`` parameter.""" - freq_start: int """Start frequency in Hertz (Hz), a number between ``0`` and ``9999``""" - freq_end: int """End frequency in Hertz (Hz), a number between ``0`` and ``9999``""" - duration: int """Duration of the sound in milliseconds, a number between ``0`` and ``9999``""" - vol_start: int """Start volume value, a number between ``0`` and ``255``""" - vol_end: int """End volume value, a number between ``0`` and ``255``""" - waveform: int """Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise)""" - fx: int """Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``""" - shape: int """The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``""" - def __init__( - self, - freq_start: int = 500, - freq_end: int = 2500, - duration: int = 500, - vol_start: int = 255, - vol_end: int = 0, - waveform: int = WAVEFORM_SQUARE, - fx: int = FX_NONE, - shape: int = SHAPE_LOG, - ): + def __init__(self, freq_start: int=500, freq_end: int=2500, duration: int=500, vol_start: int=255, vol_end: int=0, waveform: int=WAVEFORM_SQUARE, fx: int=FX_NONE, shape: int=SHAPE_LOG): """Create a new sound effect. - Example: ``my_effect = SoundEffect(duration=1000)`` - - All the parameters are optional, with default values as shown above, and - they can all be modified via attributes of the same name. For example, we - can first create an effect ``my_effect = SoundEffect(duration=1000)``, - and then change its attributes ``my_effect.duration = 500``. - - :param freq_start: Start frequency in Hertz (Hz), a number between ``0`` and ``9999``. - :param freq_end: End frequency in Hertz (Hz), a number between ``0`` and ``9999``. - :param duration: Duration of the sound in milliseconds, a number between ``0`` and ``9999``. - :param vol_start: Start volume value, a number between ``0`` and ``255``. - :param vol_end: End volume value, a number between ``0`` and ``255``. - :param waveform: Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise). - :param fx: Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``. - :param shape: The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``. - """ +Example: ``my_effect = SoundEffect(duration=1000)`` + +All the parameters are optional, with default values as shown above, and +they can all be modified via attributes of the same name. For example, we +can first create an effect ``my_effect = SoundEffect(duration=1000)``, +and then change its attributes ``my_effect.duration = 500``. + +:param freq_start: Start frequency in Hertz (Hz), a number between ``0`` and ``9999``. +:param freq_end: End frequency in Hertz (Hz), a number between ``0`` and ``9999``. +:param duration: Duration of the sound in milliseconds, a number between ``0`` and ``9999``. +:param vol_start: Start volume value, a number between ``0`` and ``255``. +:param vol_end: End volume value, a number between ``0`` and ``255``. +:param waveform: Type of waveform shape, one of these values: ``WAVEFORM_SINE``, ``WAVEFORM_SAWTOOTH``, ``WAVEFORM_TRIANGLE``, ``WAVEFORM_SQUARE``, ``WAVEFORM_NOISE`` (randomly generated noise). +:param fx: Effect to add on the sound, one of the following values: ``FX_TREMOLO``, ``FX_VIBRATO``, ``FX_WARBLE``, or ``FX_NONE``. +:param shape: The type of the interpolation curve between the start and end frequencies, different wave shapes have different rates of change in frequency. One of the following values: ``SHAPE_LINEAR``, ``SHAPE_CURVE``, ``SHAPE_LOG``.""" + def copy(self) -> SoundEffect: """Create a copy of this ``SoundEffect``. - Example: ``sound_2 = sound_1.copy()`` +Example: ``sound_2 = sound_1.copy()`` - :return: A copy of the SoundEffect. - """ +:return: A copy of the SoundEffect.""" class AudioFrame: - """An ``AudioFrame`` object is a list of 32 samples each of which is a unsigned byte - (whole number between 0 and 255). + """``AudioFrame`` 物件是 32 個樣本的列表,每個樣本都是一個無符號位元組 (0 到 255 之間的整數)。 - It takes just over 4 ms to play a single frame. +It takes just over 4 ms to play a single frame. - Example:: +Example:: - frame = AudioFrame() - for i in range(len(frame)): - frame[i] = 252 - i * 8 - """ + frame = AudioFrame() + for i in range(len(frame)): + frame[i] = 252 - i * 8""" def copyfrom(self, other: AudioFrame) -> None: """Overwrite the data in this ``AudioFrame`` with the data from another ``AudioFrame`` instance. - Example: ``my_frame.copyfrom(source_frame)`` +Example: ``my_frame.copyfrom(source_frame)`` + +:param other: ``AudioFrame`` instance from which to copy the data.""" + + def __len__(self) -> int: + ... + + def __setitem__(self, key: int, value: int) -> None: + ... - :param other: ``AudioFrame`` instance from which to copy the data. - """ - def __len__(self) -> int: ... - def __setitem__(self, key: int, value: int) -> None: ... - def __getitem__(self, key: int) -> int: ... + def __getitem__(self, key: int) -> int: + ... \ No newline at end of file diff --git a/lang/zh-tw/typeshed/stdlib/microbit/compass.pyi b/lang/zh-tw/typeshed/stdlib/microbit/compass.pyi index c74a47b..74681f3 100644 --- a/lang/zh-tw/typeshed/stdlib/microbit/compass.pyi +++ b/lang/zh-tw/typeshed/stdlib/microbit/compass.pyi @@ -1,78 +1,70 @@ -"""Use the built-in compass. -""" +"""使用內建指南針。 (指南針)""" def calibrate() -> None: - """Starts the calibration process. + """開始校準程序。 - Example: ``compass.calibrate()`` +Example: ``compass.calibrate()`` - 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. - """ +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: - """Check is the compass is calibrated. + """檢查指南針是否已校準。 - Example: ``compass.is_calibrated()`` +Example: ``compass.is_calibrated()`` - :return: ``True`` if the compass has been successfully calibrated, ``False`` otherwise. - """ +:return: ``True`` if the compass has been successfully calibrated, ``False`` otherwise.""" ... def clear_calibration() -> None: - """Undoes the calibration, making the compass uncalibrated again. + """復原校準,使指南針再次未校準。 - Example: ``compass.clear_calibration()`` - """ +Example: ``compass.clear_calibration()``""" ... def get_x() -> int: - """Get the magnetic field strength on the ``x`` axis. + """取得 ``x`` 軸上的磁場強度。 - Example: ``compass.get_x()`` +Example: ``compass.get_x()`` - Call ``calibrate`` first or the results will be inaccurate. +Call ``calibrate`` first or the results will be inaccurate. - :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. - """ +:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" ... def get_y() -> int: - """Get the magnetic field strength on the ``y`` axis. + """取得 ``y`` 軸上的磁場強度。 - Example: ``compass.get_y()`` +Example: ``compass.get_y()`` - Call ``calibrate`` first or the results will be inaccurate. +Call ``calibrate`` first or the results will be inaccurate. - :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. - """ +:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" ... def get_z() -> int: - """Get the magnetic field strength on the ``z`` axis. + """取得 ``z`` 軸上的磁場強度。 - Example: ``compass.get_z()`` +Example: ``compass.get_z()`` - Call ``calibrate`` first or the results will be inaccurate. +Call ``calibrate`` first or the results will be inaccurate. - :return: A positive or negative integer in nano tesla representing the magnitude and direction of the field. - """ +:return: A positive or negative integer in nano tesla representing the magnitude and direction of the field.""" ... def heading() -> int: - """Get the compass heading. + """取得指南針方向。 - Example: ``compass.heading()`` +Example: ``compass.heading()`` - :return: An integer in the range from 0 to 360, representing the angle in degrees, clockwise, with north as 0. - """ +:return: An integer in the range from 0 to 360, representing the angle in degrees, clockwise, with north as 0.""" ... def get_field_strength() -> int: - """Get the magnitude of the magnetic field around the device. + """取得裝置周圍磁場的強度。 - Example: ``compass.get_field_strength()`` +Example: ``compass.get_field_strength()`` - :return: An integer indication of the magnitude of the magnetic field in nano tesla.""" - ... +:return: An integer indication of the magnitude of the magnetic field in nano tesla.""" + ... \ No newline at end of file diff --git a/lang/zh-tw/typeshed/stdlib/microbit/display.pyi b/lang/zh-tw/typeshed/stdlib/microbit/display.pyi index aa4013e..5b2a57e 100644 --- a/lang/zh-tw/typeshed/stdlib/microbit/display.pyi +++ b/lang/zh-tw/typeshed/stdlib/microbit/display.pyi @@ -1,115 +1,92 @@ -"""Show text, images and animations on the 5×5 LED display. -""" - +"""在 5×5 LED 顯示器上顯示文字、圖像和動畫。""" from ..microbit import Image from typing import Union, overload, Iterable def get_pixel(x: int, y: int) -> int: - """Get the brightness of the LED at column ``x`` and row ``y``. + """取得行 ``x`` 和列 ``y`` 的 LED 亮度。 - Example: ``display.get_pixel(0, 0)`` +Example: ``display.get_pixel(0, 0)`` - :param x: The display column (0..4) - :param y: The display row (0..4) - :return: A number between 0 (off) and 9 (bright) - """ +:param x: 顯示行 (0..4) +:param y: 顯示列 (0..4) +:return: A number 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``. + """在行 ``x`` 和列 ``y`` 設定 LED 亮度。 - Example: ``display.set_pixel(0, 0, 9)`` +Example: ``display.set_pixel(0, 0, 9)`` - :param x: The display column (0..4) - :param y: The display row (0..4) - :param value: The brightness between 0 (off) and 9 (bright) - """ +:param x: 顯示行 (0..4) +:param y: 顯示列 (0..4) +:param value: 0 (關閉) 和 9 (最亮) 之間的亮度""" ... def clear() -> None: - """Set the brightness of all LEDs to 0 (off). + """將所有 LED 的亮度設定為 0 (關閉)。 - Example: ``display.clear()`` - """ +Example: ``display.clear()``""" ... -def show( - image: Union[str, float, int, Image, Iterable[Image]], - delay: int = 400, - wait: bool = True, - loop: bool = False, - clear: bool = False, -) -> None: - """Shows images, letters or digits on the LED display. +def show(image: Union[str, float, int, Image, Iterable[Image]], delay: int=400, wait: bool=True, loop: bool=False, clear: bool=False) -> None: + """在 LED 顯示器上顯示圖像、字母或數字。 - Example: ``display.show(Image.HEART)`` +Example: ``display.show(Image.HEART)`` - When ``image`` is an image or a list of images then each image is displayed in turn. - If ``image`` is a string or number, each letter or digit is displayed in turn. +When ``image`` is an image or a list of images then each image is displayed in turn. +If ``image`` is a string or number, each letter or digit is displayed in turn. - :param image: A string, number, image or list of images to show. - :param delay: Each letter, digit or image is shown with ``delay`` milliseconds between them. - :param wait: If ``wait`` is ``True``, this function will block until the animation is finished, otherwise the animation will happen in the background. - :param loop: If ``loop`` is ``True``, the animation will repeat forever. - :param clear: If ``clear`` is ``True``, the display will be cleared after the sequence has finished. +:param image: 要顯示的字串、數字、圖像或圖像列表。 +:param delay: 每個字母、數字或圖像之間的顯示時間為 ``delay`` 毫秒。 +:param wait: 如果 ``wait`` 為 ``True``,此函式將封鎖直到動畫完成,否則動畫將在背景發生。 +:param loop: 如果 ``loop`` 為 ``True``,動畫將永遠重複。 +:param clear: 如果 ``clear`` 為 ``True``,則顯示將在序列完成後被清除。 - The ``wait``, ``loop`` and ``clear`` arguments must be specified using their keyword. - """ +The ``wait``, ``loop`` and ``clear`` arguments must be specified using their keyword.""" ... -def scroll( - text: Union[str, float, int], - delay: int = 150, - wait: bool = True, - loop: bool = False, - monospace: bool = False, -) -> None: - """Scrolls a number or text on the LED display. - - Example: ``display.scroll('micro:bit')`` - - :param text: The string to scroll. If ``text`` is an integer or float it is first converted to a string using ``str()``. - :param delay: The ``delay`` parameter controls how fast the text is scrolling. - :param wait: If ``wait`` is ``True``, this function will block until the animation is finished, otherwise the animation will happen in the background. - :param loop: If ``loop`` is ``True``, the animation will repeat forever. - :param monospace: 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. - - The ``wait``, ``loop`` and ``monospace`` arguments must be specified - using their keyword. - """ +def scroll(text: Union[str, float, int], delay: int=150, wait: bool=True, loop: bool=False, monospace: bool=False) -> None: + """捲動 LED 顯示器上的數字或文字。 + +Example: ``display.scroll('micro:bit')`` + +:param text: 要捲動的字串。如果 ``text`` 是整數或浮點數,則先使用 ``str()`` 將其轉換為字串。 +:param delay: ``delay`` 參數可控制文字捲動的速度。 +:param wait: 如果 ``wait`` 為 ``True``,此函式將封鎖直到動畫完成,否則動畫將在背景發生。 +:param loop: 如果 ``loop`` 為 ``True``,動畫將永遠重複。 +:param monospace: 如果 ``monospace`` 為 ``True``,字元寬度將全部佔用 5 個像素行。否則,捲動時每個字元之間將恰好有 1 個空白像素行。 + +The ``wait``, ``loop`` and ``monospace`` arguments must be specified +using their keyword.""" ... def on() -> None: - """Turn on the LED display. + """開啟 LED 顯示器。 - Example: ``display.on()`` - """ +Example: ``display.on()``""" ... def off() -> None: - """Turn off the LED display (disabling the display allows you to re-use the GPIO pins for other purposes). + """關閉 LED 顯示器 (停用顯示器,可讓您將 GPIO 引腳重新用於其他目的)。 - Example: ``display.off()`` - """ +Example: ``display.off()``""" ... def is_on() -> bool: - """Check whether the LED display is enabled. + """檢查 LED 顯示器是否有啟用。 - Example: ``display.is_on()`` +Example: ``display.is_on()`` - :return: ``True`` if the display is on, otherwise returns ``False``. - """ +:return: ``True`` if the display is on, otherwise returns ``False``.""" ... def read_light_level() -> int: - """Read the light level. + """讀取光度。 - Example: ``display.read_light_level()`` +Example: ``display.read_light_level()`` - Uses the display's LEDs in reverse-bias mode to sense the amount of light - falling on the display. +Uses the display's LEDs in reverse-bias mode to sense the amount of light +falling on the display. - :return: An integer between 0 and 255 representing the light level, with larger meaning more light. - """ - ... +:return: An integer between 0 and 255 representing the light level, with larger meaning more light.""" + ... \ No newline at end of file diff --git a/lang/zh-tw/typeshed/stdlib/microbit/i2c.pyi b/lang/zh-tw/typeshed/stdlib/microbit/i2c.pyi index df26efa..1ba931c 100644 --- a/lang/zh-tw/typeshed/stdlib/microbit/i2c.pyi +++ b/lang/zh-tw/typeshed/stdlib/microbit/i2c.pyi @@ -1,57 +1,49 @@ -"""Communicate with devices using the I²C bus protocol. -""" - +"""使用 I²C 匯流排通訊協定與裝置通訊。""" from _typeshed import ReadableBuffer from ..microbit import MicroBitDigitalPin, pin19, pin20 from typing import List -def init( - freq: int = 100000, sda: MicroBitDigitalPin = pin20, scl: MicroBitDigitalPin = pin19 -) -> None: - """Re-initialize a peripheral. +def init(freq: int=100000, sda: MicroBitDigitalPin=pin20, scl: MicroBitDigitalPin=pin19) -> None: + """重新初始化周邊設備。 - Example: ``i2c.init()`` +Example: ``i2c.init()`` - :param freq: clock frequency - :param sda: ``sda`` pin (default 20) - :param scl: ``scl`` pin (default 19) +:param freq: (頻率) 時脈頻率 +:param sda: ``sda`` 引腳 (預設 20) +:param scl: ``scl`` 引腳 (預設 19) - On a micro:bit V1 board, changing the I²C pins from defaults will make - the accelerometer and compass stop working, as they are connected - internally to those pins. This warning does not apply to the **V2** - revision of the micro:bit as this has `separate I²C lines `_ - for the motion sensors and the edge connector. - """ +On a micro:bit V1 board, changing the I²C pins from defaults will make +the accelerometer and compass stop working, as they are connected +internally to those pins. This warning does not apply to the **V2** +revision of the micro:bit as this has `separate I²C lines `_ +for the motion sensors and the edge connector.""" ... def scan() -> List[int]: - """Scan the bus for devices. + """掃描匯流排以尋找裝置。 - Example: ``i2c.scan()`` +Example: ``i2c.scan()`` - :return: A list of 7-bit addresses corresponding to those devices that responded to the scan. - """ +:return: A list of 7-bit addresses corresponding to those devices that responded to the scan.""" ... -def read(addr: int, n: int, repeat: bool = False) -> bytes: - """Read bytes from a device. +def read(addr: int, n: int, repeat: bool=False) -> bytes: + """從裝置讀取位元組。 - Example: ``i2c.read(0x50, 64)`` +Example: ``i2c.read(0x50, 64)`` - :param addr: The 7-bit address of the device - :param n: The number of bytes to read - :param repeat: If ``True``, no stop bit will be sent - :return: The bytes read - """ +:param addr: 裝置的 7 位元地址 +:param n: 要讀取的位元組數 +:param repeat: 如果 ``True``,則不會傳送停止位元 +:return: The bytes read""" ... -def write(addr: int, buf: ReadableBuffer, repeat: bool = False) -> None: - """Write bytes to a device. +def write(addr: int, buf: ReadableBuffer, repeat: bool=False) -> None: + """將位元組寫入裝置。 - Example: ``i2c.write(0x50, bytes([1, 2, 3]))`` +Example: ``i2c.write(0x50, bytes([1, 2, 3]))`` - :param addr: The 7-bit address of the device - :param buf: A buffer containing the bytes to write - :param repeat: If ``True``, no stop bit will be sent - """ - ... +:param addr: 裝置的 7 位元位址 +:param buf: 包含要寫入位元組的緩衝區 +:param repeat: 如果 ``True``,則不會傳送停止位元""" + ... \ No newline at end of file diff --git a/lang/zh-tw/typeshed/stdlib/microbit/microphone.pyi b/lang/zh-tw/typeshed/stdlib/microbit/microphone.pyi index 68e8f3a..894fa45 100644 --- a/lang/zh-tw/typeshed/stdlib/microbit/microphone.pyi +++ b/lang/zh-tw/typeshed/stdlib/microbit/microphone.pyi @@ -1,70 +1,62 @@ -"""Respond to sound using the built-in microphone (V2 only). -""" - +"""使用內建麥克風回應聲音 (僅限 V2)。""" from typing import Optional, Tuple from ..microbit import SoundEvent def current_event() -> Optional[SoundEvent]: - """Get the last recorded sound event + """取得最後錄製的聲音事件 - Example: ``microphone.current_event()`` +Example: ``microphone.current_event()`` - :return: The event, ``SoundEvent('loud')`` or ``SoundEvent('quiet')``. - """ +:return: The event, ``SoundEvent('loud')`` or ``SoundEvent('quiet')``.""" ... def was_event(event: SoundEvent) -> bool: - """Check if a sound was heard at least once since the last call. + """檢查自上次呼叫後,是否至少有聽到一次聲音。 - Example: ``microphone.was_event(SoundEvent.LOUD)`` +Example: ``microphone.was_event(SoundEvent.LOUD)`` - This call clears the sound history before returning. +This call clears the sound history before returning. - :param event: The event to check for, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET`` - :return: ``True`` if sound was heard at least once since the last call, otherwise ``False``. - """ +:param event: 要檢查的事件,例如 ``SoundEvent.LOUD`` 或 ``SoundEvent.QUIET`` +:return: ``True`` if sound was heard at least once since the last call, otherwise ``False``.""" ... def is_event(event: SoundEvent) -> bool: - """Check the most recent sound event detected. + """檢查偵測到的最新聲音事件。 - Example: ``microphone.is_event(SoundEvent.LOUD)`` +Example: ``microphone.is_event(SoundEvent.LOUD)`` - This call does not clear the sound event history. +This call does not clear the sound event history. - :param event: The event to check for, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET`` - :return: ``True`` if sound was the most recent heard, ``False`` otherwise. - """ +:param event: 要檢查的事件,例如 ``SoundEvent.LOUD`` 或 ``SoundEvent.QUIET`` +:return: ``True`` if sound was the most recent heard, ``False`` otherwise.""" ... def get_events() -> Tuple[SoundEvent, ...]: - """Get the sound event history as a tuple. + """以元組的形式取得聲音事件歷史。 - Example: ``microphone.get_events()`` +Example: ``microphone.get_events()`` - This call clears the sound history before returning. +This call clears the sound history before returning. - :return: A tuple of the event history with the most recent event last. - """ +:return: A tuple of the event history with the most recent event last.""" ... def set_threshold(event: SoundEvent, value: int) -> None: - """Set the threshold for a sound event. + """設定聲音事件的閾值。 - Example: ``microphone.set_threshold(SoundEvent.LOUD, 250)`` +Example: ``microphone.set_threshold(SoundEvent.LOUD, 250)`` - A high threshold means the event will only trigger if the sound is very loud (>= 250 in the example). +A high threshold means the event will only trigger if the sound is very loud (>= 250 in the example). - :param event: A sound event, such as ``SoundEvent.LOUD`` or ``SoundEvent.QUIET``. - :param value: The threshold level in the range 0-255. - """ +:param event: 聲音事件,例如 ``SoundEvent.LOUD`` 或 ``SoundEvent.QUIET``。 +:param value: 0-255 範圍內的閾值等級。""" ... def sound_level() -> int: - """Get the sound pressure level. + """取得聲壓位準。 - Example: ``microphone.sound_level()`` +Example: ``microphone.sound_level()`` - :return: A representation of the sound pressure level in the range 0 to 255. - """ - ... +:return: A representation of the sound pressure level in the range 0 to 255.""" + ... \ No newline at end of file diff --git a/lang/zh-tw/typeshed/stdlib/microbit/speaker.pyi b/lang/zh-tw/typeshed/stdlib/microbit/speaker.pyi index 5a74a4d..879118f 100644 --- a/lang/zh-tw/typeshed/stdlib/microbit/speaker.pyi +++ b/lang/zh-tw/typeshed/stdlib/microbit/speaker.pyi @@ -1,18 +1,15 @@ -"""Control the built-in speaker (V2 only). -""" +"""控制內建揚聲器 (僅限 V2)。""" def off() -> None: - """Turn the speaker off. + """關閉揚聲器。 - Example: ``speaker.off()`` +Example: ``speaker.off()`` - This does not disable sound output to an edge connector pin. - """ +This does not disable sound output to an edge connector pin.""" ... def on() -> None: - """Turn the speaker on. + """開啟揚聲器。 - Example: ``speaker.on()`` - """ - ... +Example: ``speaker.on()``""" + ... \ No newline at end of file diff --git a/lang/zh-tw/typeshed/stdlib/microbit/spi.pyi b/lang/zh-tw/typeshed/stdlib/microbit/spi.pyi index 09c4046..34e5f08 100644 --- a/lang/zh-tw/typeshed/stdlib/microbit/spi.pyi +++ b/lang/zh-tw/typeshed/stdlib/microbit/spi.pyi @@ -1,60 +1,47 @@ -"""Communicate with devices using the serial peripheral interface (SPI) bus. -""" - +"""使用周邊設備介面 (SPI) 匯流排與裝置進行通訊。""" from _typeshed import ReadableBuffer, WriteableBuffer from ..microbit import pin13, pin14, pin15, MicroBitDigitalPin -def init( - baudrate: int = 1000000, - bits: int = 8, - mode: int = 0, - sclk: MicroBitDigitalPin = pin13, - mosi: MicroBitDigitalPin = pin15, - miso: MicroBitDigitalPin = pin14, -) -> None: - """Initialize SPI communication. - - Example: ``spi.init()`` - - For correct communication, the parameters have to be the same on both communicating devices. - - :param baudrate: The speed of communication. - :param bits: The width in bits of each transfer. Currently only ``bits=8`` is supported. However, this may change in the future. - :param mode: Determines the combination of clock polarity and phase - `see online table `_. - :param sclk: sclk pin (default 13) - :param mosi: mosi pin (default 15) - :param miso: miso pin (default 14) - """ +def init(baudrate: int=1000000, bits: int=8, mode: int=0, sclk: MicroBitDigitalPin=pin13, mosi: MicroBitDigitalPin=pin15, miso: MicroBitDigitalPin=pin14) -> None: + """初始化 SPI 通訊。 + +Example: ``spi.init()`` + +For correct communication, the parameters have to be the same on both communicating devices. + +:param baudrate: 通訊速度。 +:param bits: 每次傳輸的位元寬度。目前僅支援 ``bits=8``。然而,這種情況在未來可能會改變。 +:param mode: 確定時脈極性和相位的組合 - 請見線上表格 `_。 +:param sclk: sclk 引腳 (預設 13) +:param mosi: mosi 引腳 (預設 15) +:param miso: miso 引腳 (預設 14)""" ... -def read(nbytes: int, out: int = 0) -> bytes: - """Read at most ``nbytes`` while continuously writing the single byte given by ``out``. +def read(nbytes: int, out: int=0) -> bytes: + """讀取位元組。 - Example: ``spi.read(64)`` +Example: ``spi.read(64)`` - :param nbytes: Maximum number of bytes to read. - :param out: The byte value to write (default 0). - :return: The bytes read. - """ +:param nbytes: 要讀取的最大位元組數。 +:param out: The byte value to write (default 0). +:return: The bytes read.""" ... def write(buffer: ReadableBuffer) -> None: - """Write bytes to the bus. + """將位元組寫入匯流排。 - Example: ``spi.write(bytes([1, 2, 3]))`` +Example: ``spi.write(bytes([1, 2, 3]))`` - :param buffer: A buffer to read data from. - """ +:param buffer: 讀取資料的來源緩衝區。""" ... def write_readinto(out: WriteableBuffer, in_: ReadableBuffer) -> None: - """Write the ``out`` buffer to the bus and read any response into the ``in_`` buffer. + """將 ``out`` 緩衝區寫入匯流排,並將任何回應寫入 ``in_`` 緩衝區。 - Example: ``spi.write_readinto(out_buffer, in_buffer)`` +Example: ``spi.write_readinto(out_buffer, in_buffer)`` - The length of the buffers should be the same. The buffers can be the same object. +The length of the buffers should be the same. The buffers can be the same object. - :param out: The buffer to write any response to. - :param in_: The buffer to read data from. - """ - ... +:param out: 要寫入任何回應的緩衝區。 +:param in_: 要從中讀取資料的緩衝區。""" + ... \ No newline at end of file diff --git a/lang/zh-tw/typeshed/stdlib/microbit/uart.pyi b/lang/zh-tw/typeshed/stdlib/microbit/uart.pyi index 2ab650f..f5e15ff 100644 --- a/lang/zh-tw/typeshed/stdlib/microbit/uart.pyi +++ b/lang/zh-tw/typeshed/stdlib/microbit/uart.pyi @@ -1,96 +1,79 @@ -"""Communicate with a device using a serial interface. -""" - +"""使用序列介面與裝置通訊。""" from _typeshed import WriteableBuffer from ..microbit import MicroBitDigitalPin from typing import Optional, Union - ODD: int -"""Odd parity""" - +"""奇數同位檢查""" EVEN: int -"""Even parity""" - -def init( - baudrate: int = 9600, - bits: int = 8, - parity: Optional[int] = None, - stop: int = 1, - tx: Optional[MicroBitDigitalPin] = None, - rx: Optional[MicroBitDigitalPin] = None, -) -> None: - """Initialize serial communication. - - Example: ``uart.init(115200, tx=pin0, rx=pin1)`` - - :param baudrate: The speed of communication. - :param bits: The size of bytes being transmitted. micro:bit only supports 8. - :param parity: How parity is checked, ``None``, ``uart.ODD`` or ``uart.EVEN``. - :param stop: The number of stop bits, has to be 1 for micro:bit. - :param tx: Transmitting pin. - :param rx: Receiving pin. - - 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. - - For more details see `the online documentation `_. - """ +"""偶數同位檢查""" + +def init(baudrate: int=9600, bits: int=8, parity: Optional[int]=None, stop: int=1, tx: Optional[MicroBitDigitalPin]=None, rx: Optional[MicroBitDigitalPin]=None) -> None: + """初始化序列通訊。 + +Example: ``uart.init(115200, tx=pin0, rx=pin1)`` + +:param baudrate: 通訊速度。 +:param bits: 正在傳輸的位元組大小,micro:bit 只支援 8。 +:param parity: 如何檢查奇偶性,``None``、``uart.ODD`` 或 ``uart.EVEN``。 +:param stop: 停止位元的數量,micro:bit 必須為 1。 +:param tx: 傳輸引腳。 +:param rx: 正在接收引腳。 + +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. + +For more details see `the online documentation `_.""" ... def any() -> bool: - """Check if any data is waiting. + """檢查是否有任何資料正在等待。 - Example: ``uart.any()`` +Example: ``uart.any()`` - :return: ``True`` if any data is waiting, else ``False``. - """ +:return: ``True`` if any data is waiting, else ``False``.""" ... -def read(nbytes: Optional[int] = None) -> Optional[bytes]: - """Read bytes. +def read(nbytes: Optional[int]=None) -> Optional[bytes]: + """讀取位元組。 - Example: ``uart.read()`` +Example: ``uart.read()`` - :param nbytes: If ``nbytes`` is specified then read at most that many bytes, otherwise read as many bytes as possible - :return: A bytes object or ``None`` on timeout - """ +:param nbytes: 如果指定了 ``nbytes``,則最多讀取那麼多位元組,否則讀取盡可能多的位元組 +:return: A bytes object or ``None`` on timeout""" ... -def readinto(buf: WriteableBuffer, nbytes: Optional[int] = None) -> Optional[int]: - """Read bytes into the ``buf``. +def readinto(buf: WriteableBuffer, nbytes: Optional[int]=None) -> Optional[int]: + """將位元組讀入 ``buf``。 - Example: ``uart.readinto(input_buffer)`` +Example: ``uart.readinto(input_buffer)`` - :param buf: The buffer to write to. - :param nbytes: If ``nbytes`` is specified then read at most that many bytes, otherwise read ``len(buf)`` bytes. - :return: number of bytes read and stored into ``buf`` or ``None`` on timeout. - """ +:param buf: 要寫入的緩衝區。 +:param nbytes: 如果指定了 ``nbytes``,則最多讀取那麼多位元組,否則讀取 ``len(buf)`` 個位元組。 +:return: number of bytes read and stored into ``buf`` or ``None`` on timeout.""" ... def readline() -> Optional[bytes]: - """Read a line, ending in a newline character. + """讀取一行,以新行字元結尾。 - Example: ``uart.readline()`` +Example: ``uart.readline()`` - :return: The line read or ``None`` on timeout. The newline character is included in the returned bytes. - """ +:return: The line read or ``None`` on timeout. The newline character is included in the returned bytes.""" ... def write(buf: Union[bytes, str]) -> Optional[int]: - """Write a buffer to the bus. + """將緩衝區寫入匯流排。 - Example: ``uart.write('hello world')`` +Example: ``uart.write('hello world')`` - :param buf: A bytes object or a string. - :return: The number of bytes written, or ``None`` on timeout. +:param buf: 一個位元組物件或一個字串。 +:return: The number of bytes written, or ``None`` on timeout. - Examples:: +Examples:: - uart.write('hello world') - uart.write(b'hello world') - uart.write(bytes([1, 2, 3])) - """ - ... + uart.write('hello world') + uart.write(b'hello world') + uart.write(bytes([1, 2, 3]))""" + ... \ No newline at end of file diff --git a/lang/zh-tw/typeshed/stdlib/micropython.pyi b/lang/zh-tw/typeshed/stdlib/micropython.pyi index 7a6079f..3b2ad82 100644 --- a/lang/zh-tw/typeshed/stdlib/micropython.pyi +++ b/lang/zh-tw/typeshed/stdlib/micropython.pyi @@ -1,144 +1,131 @@ -"""MicroPython internals.""" - +"""MicroPython 內部。""" from typing import Any, TypeVar, overload - -_T = TypeVar("_T") +_T = TypeVar('_T') def const(expr: _T) -> _T: - """Used to declare that the expression is a constant so that the compiler can - optimise it. + """用於宣告運算式為常數,以便編譯器對其進行最佳化。 - The use of this function should be as follows:: +The use of this function should be as follows:: - from micropython import const - CONST_X = const(123) - CONST_Y = const(2 * CONST_X + 1) + from micropython import const + CONST_X = const(123) + CONST_Y = const(2 * CONST_X + 1) - Constants declared this way are still accessible as global variables from - outside the module they are declared in. On the other hand, if a constant - begins with an underscore then it is hidden, it is not available as a - global variable, and does not take up any memory during execution. +Constants declared this way are still accessible as global variables from +outside the module they are declared in. On the other hand, if a constant +begins with an underscore then it is hidden, it is not available as a +global variable, and does not take up any memory during execution. - :param expr: A constant expression. - """ +:param expr: 一個常數運算式。""" ... @overload def opt_level() -> int: - """Get the current optimisation level for the compilation of scripts. + """取得指令碼編譯的目前最佳化等級。 - Example: ``micropython.opt_level()`` +Example: ``micropython.opt_level()`` - The optimisation level controls the following compilation features: +The optimisation level controls the following compilation features: - - Assertions: at level 0 assertion statements are enabled and compiled - into the bytecode; at levels 1 and higher assertions are not compiled. +- Assertions: at level 0 assertion statements are enabled and compiled + into the bytecode; at levels 1 and higher assertions are not compiled. - - Built-in ``__debug__`` variable: at level 0 this variable expands to - True; at levels 1 and higher it expands to False. +- Built-in ``__debug__`` variable: at level 0 this variable expands to + True; at levels 1 and higher it expands to False. - - Source-code line numbers: at levels 0, 1 and 2 source-code line number - are stored along with the bytecode so that exceptions can report the - line number they occurred at; at levels 3 and higher line numbers are - not stored. +- Source-code line numbers: at levels 0, 1 and 2 source-code line number + are stored along with the bytecode so that exceptions can report the + line number they occurred at; at levels 3 and higher line numbers are + not stored. - :return: An integer representing the current level. - """ +:return: An integer representing the current level.""" ... @overload def opt_level(level: int) -> None: - """Sets the optimisation level for subsequent compilation of scripts. + """設定指令碼後續編譯的最佳化等級。 - Example: ``micropython.opt_level(1)`` +Example: ``micropython.opt_level(1)`` - The optimisation level controls the following compilation features: +The optimisation level controls the following compilation features: - - Assertions: at level 0 assertion statements are enabled and compiled - into the bytecode; at levels 1 and higher assertions are not compiled. +- Assertions: at level 0 assertion statements are enabled and compiled + into the bytecode; at levels 1 and higher assertions are not compiled. - - Built-in ``__debug__`` variable: at level 0 this variable expands to - True; at levels 1 and higher it expands to False. +- Built-in ``__debug__`` variable: at level 0 this variable expands to + True; at levels 1 and higher it expands to False. - - Source-code line numbers: at levels 0, 1 and 2 source-code line number - are stored along with the bytecode so that exceptions can report the - line number they occurred at; at levels 3 and higher line numbers are - not stored. +- Source-code line numbers: at levels 0, 1 and 2 source-code line number + are stored along with the bytecode so that exceptions can report the + line number they occurred at; at levels 3 and higher line numbers are + not stored. - The default optimisation level is usually level 0. +The default optimisation level is usually level 0. - :param level: An integer optimisation level. - """ +:param level: 整數最佳化等級。""" ... -def mem_info(verbose: Any = None) -> None: - """Print information about currently used memory. +def mem_info(verbose: Any=None) -> None: + """輸出關於目前使用的記憶體資訊。 - Example: ``micropython.mem_info()`` +Example: ``micropython.mem_info()`` - :param verbose: If the ``verbose`` argument is given then extra information is printed. - """ +:param verbose: 如果給出 ``verbose`` 引數,則會輸出額外資訊。""" ... -def qstr_info(verbose: Any = None) -> None: - """Print information about currently interned strings. +def qstr_info(verbose: Any=None) -> None: + """輸出關於目前駐留字串的資訊。 - Example: ``micropython.qstr_info()`` +Example: ``micropython.qstr_info()`` - :param verbose: If the ``verbose`` argument is given then extra information is printed. +:param verbose: 如果指定 ``verbose`` 引數,則會輸出額外資訊。 - The information that is printed is implementation dependent, but currently - includes the number of interned strings and the amount of RAM they use. In - verbose mode it prints out the names of all RAM-interned strings. - """ +The information that is printed is implementation dependent, but currently +includes the number of interned strings and the amount of RAM they use. In +verbose mode it prints out the names of all RAM-interned strings.""" ... def stack_use() -> int: - """Return an integer representing the current amount of stack that is being - used. + """傳回整數,表示目前正在使用的堆疊數量。 - Example: ``micropython.stack_use()`` +Example: ``micropython.stack_use()`` - The absolute value of this is not particularly useful, rather it - should be used to compute differences in stack usage at different points. +The absolute value of this is not particularly useful, rather it +should be used to compute differences in stack usage at different points. - :return: An integer representing current stack use. - """ +:return: An integer representing current stack use.""" ... def heap_lock() -> None: - """Lock the heap. + """鎖定堆積。 - Example: ``micropython.heap_lock()`` +Example: ``micropython.heap_lock()`` - When locked no memory allocation can occur and a ``MemoryError`` will be - raised if any heap allocation is attempted. - """ +When locked no memory allocation can occur and a ``MemoryError`` will be +raised if any heap allocation is attempted.""" ... def heap_unlock() -> None: - """Unlock the heap. + """解鎖堆積。 - Example: ``micropython.heap_unlock()`` +Example: ``micropython.heap_unlock()`` - When locked no memory allocation can occur and a ``MemoryError`` will be - raised if any heap allocation is attempted. - """ +When locked no memory allocation can occur and a ``MemoryError`` will be +raised if any heap allocation is attempted.""" ... def kbd_intr(chr: int) -> None: - """Set the character that will raise a ``KeyboardInterrupt`` exception. + """設定將觸發 ``KeyboardInterrupt`` 例外狀況的字元。 - Example: ``micropython.kbd_intr(-1)`` +Example: ``micropython.kbd_intr(-1)`` - :param chr: Character code to raise the interrupt or -1 to disable capture of Ctrl-C. +:param chr: 用於引發中斷的字元程式碼或 -1,以停用 Ctrl-C 的擷取。 - By default this is set to 3 during script execution, corresponding to Ctrl-C. - Passing -1 to this function will disable capture of Ctrl-C, and passing 3 - will restore it. +By default this is set to 3 during script execution, corresponding to Ctrl-C. +Passing -1 to this function will disable capture of Ctrl-C, and passing 3 +will restore it. - This function can be used to prevent the capturing of Ctrl-C on the - incoming stream of characters that is usually used for the REPL, in case - that stream is used for other purposes. - """ - ... +This function can be used to prevent the capturing of Ctrl-C on the +incoming stream of characters that is usually used for the REPL, in case +that stream is used for other purposes.""" + ... \ No newline at end of file diff --git a/lang/zh-tw/typeshed/stdlib/music.pyi b/lang/zh-tw/typeshed/stdlib/music.pyi index 5f4778b..7f81664 100644 --- a/lang/zh-tw/typeshed/stdlib/music.pyi +++ b/lang/zh-tw/typeshed/stdlib/music.pyi @@ -1,167 +1,128 @@ -"""Create and play melodies. -""" +"""創作和播放旋律。""" from typing import Optional, Tuple, Union, List - from .microbit import MicroBitDigitalPin, pin0 - DADADADUM: Tuple[str, ...] -"""Melody: the opening to Beethoven’s 5th Symphony in C minor.""" - +"""旋律:貝多芬 C 小調第五交響曲的開場。""" ENTERTAINER: Tuple[str, ...] -"""Melody: the opening fragment of Scott Joplin’s Ragtime classic “The Entertainer”.""" - +"""旋律:史考特喬普林的名曲《演藝人》開場。""" PRELUDE: Tuple[str, ...] -"""Melody: the opening of the first Prelude in C Major of J.S.Bach’s 48 Preludes and Fugues.""" - +"""旋律:巴哈 48 首前奏曲與賦格曲 C 大調第一前奏曲的開場。""" ODE: Tuple[str, ...] -"""Melody: the “Ode to Joy” theme from Beethoven’s 9th Symphony in D minor.""" - +"""旋律:貝多芬 D 小調第九交響曲中的「歡樂頌」主題。""" NYAN: Tuple[str, ...] -"""Melody: the Nyan Cat theme (http://www.nyan.cat/). +"""旋律:Nyan Cat 主題 (http://www.nyan.cat/)。 The composer is unknown. This is fair use for educational porpoises (as they say in New York).""" - RINGTONE: Tuple[str, ...] -"""Melody: something that sounds like a mobile phone ringtone. +"""旋律:聽起來像手機鈴聲的東西。 To be used to indicate an incoming message. """ - FUNK: Tuple[str, ...] -"""Melody: a funky bass line for secret agents and criminal masterminds.""" - +"""旋律:為特務和犯罪首腦準備的放克貝斯。""" BLUES: Tuple[str, ...] -"""Melody: a boogie-woogie 12-bar blues walking bass.""" - +"""旋律:布基烏基 12 小節藍調走路貝斯。""" BIRTHDAY: Tuple[str, ...] -"""Melody: “Happy Birthday to You…” +"""旋律:「祝你生日快樂……」 For copyright status see: http://www.bbc.co.uk/news/world-us-canada-34332853 """ - WEDDING: Tuple[str, ...] -"""Melody: the bridal chorus from Wagner’s opera “Lohengrin”.""" - +"""旋律:華格納歌劇《羅恩格林》中的新娘合唱。""" FUNERAL: Tuple[str, ...] -"""Melody: the “funeral march” otherwise known as Frédéric Chopin’s Piano Sonata No. 2 in B♭ minor, Op. 35.""" - +"""旋律:《葬禮進行曲》,亦稱為蕭邦的「降 b 小調第二號鋼琴奏鳴曲」。""" PUNCHLINE: Tuple[str, ...] -"""Melody: a fun fragment that signifies a joke has been made.""" - +"""旋律:一段有趣的音樂,表示說了一個笑話。""" PYTHON: Tuple[str, ...] -"""Melody: John Philip Sousa’s march “Liberty Bell” aka, the theme for “Monty Python’s Flying Circus” (after which the Python programming language is named).""" - +"""旋律:約翰菲利普蘇薩的進行曲《自由鐘》,又名《蒙提派森的飛行馬戲團》的主題曲 (Python 程式語言以此命名)。""" BADDY: Tuple[str, ...] -"""Melody: silent movie era entrance of a baddy.""" - +"""旋律:無聲電影時代的惡人登場。""" CHASE: Tuple[str, ...] -"""Melody: silent movie era chase scene.""" - +"""旋律:無聲電影時代的追逐場景。""" BA_DING: Tuple[str, ...] -"""Melody: a short signal to indicate something has happened.""" - +"""旋律:表示某事發生的短訊號。""" WAWAWAWAA: Tuple[str, ...] -"""Melody: a very sad trombone.""" - +"""旋律:非常悲傷的長號。""" JUMP_UP: Tuple[str, ...] -"""Melody: for use in a game, indicating upward movement.""" - +"""旋律:用於遊戲中,代表向上移動。""" JUMP_DOWN: Tuple[str, ...] -"""Melody: for use in a game, indicating downward movement.""" - +"""旋律:用於遊戲中,表示向下移動。""" POWER_UP: Tuple[str, ...] -"""Melody: a fanfare to indicate an achievement unlocked.""" - +"""旋律:表示已解鎖成就的號角齊鳴。""" POWER_DOWN: Tuple[str, ...] -"""Melody: a sad fanfare to indicate an achievement lost.""" +"""旋律:表示失去成就的悲傷號角聲。""" -def set_tempo(ticks: int = 4, bpm: int = 120) -> None: - """Sets the approximate tempo for playback. +def set_tempo(ticks: int=4, bpm: int=120) -> None: + """設定播放的大致節奏。 - Example: ``music.set_tempo(bpm=120)`` +Example: ``music.set_tempo(bpm=120)`` - :param ticks: The number of ticks constituting a beat. - :param bpm: An integer determining how many beats per minute. +:param ticks: 構成節拍的滴答聲數。 +:param bpm: 一個整數,決定每分鐘有多少次節拍。 - Suggested default values allow the following useful behaviour: +Suggested default values allow the following useful behaviour: - - music.set_tempo() – reset the tempo to default of ticks = 4, bpm = 120 - - music.set_tempo(ticks=8) – change the “definition” of a beat - - music.set_tempo(bpm=180) – just change the tempo +- music.set_tempo() – reset the tempo to default of ticks = 4, bpm = 120 +- music.set_tempo(ticks=8) – change the “definition” of a beat +- music.set_tempo(bpm=180) – just change the tempo - To work out the length of a tick in milliseconds is very simple arithmetic: - 60000/bpm/ticks_per_beat. For the default values that’s - 60000/120/4 = 125 milliseconds or 1 beat = 500 milliseconds. - """ +To work out the length of a tick in milliseconds is very simple arithmetic: +60000/bpm/ticks_per_beat. For the default values that’s +60000/120/4 = 125 milliseconds or 1 beat = 500 milliseconds.""" ... def get_tempo() -> Tuple[int, int]: - """Gets the current tempo as a tuple of integers: ``(ticks, bpm)``. + """以整數元組的形式取得當前節奏:``(ticks, bpm)``。 - Example: ``ticks, beats = music.get_tempo()`` +Example: ``ticks, beats = music.get_tempo()`` - :return: The temp as a tuple with two integer values, the ticks then the beats per minute. - """ +:return: The temp as a tuple with two integer values, the ticks then the beats per minute.""" ... -def play( - music: Union[str, List[str], Tuple[str, ...]], - pin: Optional[MicroBitDigitalPin] = pin0, - wait: bool = True, - loop: bool = False, -) -> None: - """Plays music. +def play(music: Union[str, List[str], Tuple[str, ...]], pin: Optional[MicroBitDigitalPin]=pin0, wait: bool=True, loop: bool=False) -> None: + """播放音樂。 - Example: ``music.play(music.NYAN)`` +Example: ``music.play(music.NYAN)`` - :param music: music specified in `a special notation `_ - :param pin: the output pin for use with an external speaker (default ``pin0``), ``None`` for no sound. - :param wait: If ``wait`` is set to ``True``, this function is blocking. - :param loop: If ``loop`` is set to ``True``, the tune repeats until ``stop`` is called or the blocking call is interrupted. +:param music: 特殊音符中指定的音樂 `_ +:param pin: (引腳) 用於外接揚聲器的輸出引腳 (預設為 ``pin0``),``None`` 表示無聲音。 +:param wait: 如果 ``wait`` 設定為 ``True``,則此函式會封鎖。 +:param loop: 如果 ``loop`` 設定為 ``True``,樂曲會重複直到呼叫 ``stop`` 或封鎖呼叫被中斷。 - Many built-in melodies are defined in this module. - """ +Many built-in melodies are defined in this module.""" ... -def pitch( - frequency: int, - duration: int = -1, - pin: Optional[MicroBitDigitalPin] = pin0, - wait: bool = True, -) -> None: - """Play a note. +def pitch(frequency: int, duration: int=-1, pin: Optional[MicroBitDigitalPin]=pin0, wait: bool=True) -> None: + """彈奏一個音符。 (間距) - Example: ``music.pitch(185, 1000)`` +Example: ``music.pitch(185, 1000)`` - :param frequency: An integer frequency - :param duration: A millisecond duration. If negative then sound is continuous until the next call or a call to ``stop``. - :param pin: Optional output pin (default ``pin0``). - :param wait: If ``wait`` is set to ``True``, this function is blocking. +:param frequency: (頻率) 整數頻率 +:param duration: 毫秒的持續時間。如果是否定的,則聲音將持續到下一次呼叫或對 ``stop`` 的呼叫。 +:param pin: (引腳) 可選輸出引腳 (預設值 ``pin0``)。 +:param wait: 如果 ``wait`` 設定為 ``True``,則此函式為封鎖。 - For example, if the frequency is set to 440 and the length to - 1000 then we hear a standard concert A for one second. +For example, if the frequency is set to 440 and the length to +1000 then we hear a standard concert A for one second. - You can only play one pitch on one pin at any one time. - """ +You can only play one pitch on one pin at any one time.""" ... -def stop(pin: Optional[MicroBitDigitalPin] = pin0) -> None: - """Stops all music playback on the built-in speaker and any pin outputting sound. +def stop(pin: Optional[MicroBitDigitalPin]=pin0) -> None: + """停止內建揚聲器上的所有音樂播放和任何引腳輸出聲音。 - Example: ``music.stop()`` +Example: ``music.stop()`` - :param pin: An optional argument can be provided to specify a pin, e.g. ``music.stop(pin1)``. - """ +:param pin: (引腳) 可以提供一個可選引數來指定一個引腳,例如 ``music.stop(pin1)``。""" def reset() -> None: - """Resets ticks, bpm, duration and octave to their default values. + """將 ticks、bpm、duration 和 octave 重設為其預設值。 - Example: ``music.reset()`` +Example: ``music.reset()`` - Values: - - ``ticks = 4`` - - ``bpm = 120`` - - ``duration = 4`` - - ``octave = 4`` - """ - ... +Values: +- ``ticks = 4`` +- ``bpm = 120`` +- ``duration = 4`` +- ``octave = 4``""" + ... \ No newline at end of file diff --git a/lang/zh-tw/typeshed/stdlib/neopixel.pyi b/lang/zh-tw/typeshed/stdlib/neopixel.pyi index 2d5a749..45b5b35 100644 --- a/lang/zh-tw/typeshed/stdlib/neopixel.pyi +++ b/lang/zh-tw/typeshed/stdlib/neopixel.pyi @@ -1,82 +1,81 @@ -"""Individually addressable RGB and RGBW LED strips. -""" +"""可獨立尋址的 RGB 和 RGBW LED 燈條。""" from .microbit import MicroBitDigitalPin from typing import Tuple class NeoPixel: - def __init__(self, pin: MicroBitDigitalPin, n: int, bpp: int = 3) -> None: - """Initialise a new strip of neopixel LEDs controlled via a pin. - Example: ``np = neopixel.NeoPixel(pin0, 8)`` + def __init__(self, pin: MicroBitDigitalPin, n: int, bpp: int=3) -> None: + """初始化透過引腳控制的 NeoPixel LED 燈條。 - To support RGBW neopixels, a third argument can be passed to - ``NeoPixel`` to indicate the number of bytes per pixel (``bpp``). - For RGBW, this is is 4 rather than the default of 3 for RGB and GRB. +Example: ``np = neopixel.NeoPixel(pin0, 8)`` - Each pixel is addressed by a position (starting from 0). Neopixels are - given RGB (red, green, blue) / RGBW (red, green, blue, white) values - between 0-255 as a tuple. For example, in RGB, ``(255,255,255)`` is - white. In RGBW, ``(255,255,255,0)`` or ``(0,0,0,255)`` is white. +To support RGBW neopixels, a third argument can be passed to +``NeoPixel`` to indicate the number of bytes per pixel (``bpp``). +For RGBW, this is is 4 rather than the default of 3 for RGB and GRB. - See `the online docs `_ for warnings and other advice. +Each pixel is addressed by a position (starting from 0). Neopixels are +given RGB (red, green, blue) / RGBW (red, green, blue, white) values +between 0-255 as a tuple. For example, in RGB, ``(255,255,255)`` is +white. In RGBW, ``(255,255,255,0)`` or ``(0,0,0,255)`` is white. - :param pin: The pin controlling the neopixel strip. - :param n: The number of neopixels in the strip. - :param bpp: Bytes per pixel. For RGBW neopixel support, pass 4 rather than the default of 3 for RGB and GRB. - """ +See `the online docs `_ for warnings and other advice. + +:param pin: (引腳) 控制 NeoPixel 燈條的引腳。 +:param n: 燈條中的 NeoPixel 數。 +:param bpp: 各像素位元組數。對於 RGBW neopixel 支援,傳遞 4 而不是 RGB 和 GRB 的預設值 3。""" ... + def clear(self) -> None: - """Clear all the pixels. + """清除所有像素。 - Example: ``np.clear()`` - """ +Example: ``np.clear()``""" ... + def show(self) -> None: - """Show the pixels. + """顯示像素。 - Example: ``np.show()`` +Example: ``np.show()`` - Must be called for any updates to become visible. - """ +Must be called for any updates to become visible.""" ... + def write(self) -> None: - """Show the pixels (micro:bit V2 only). + """顯示像素 (僅限 micro:bit V2)。 - Example: ``np.write()`` +Example: ``np.write()`` - Must be called for any updates to become visible. +Must be called for any updates to become visible. - Equivalent to ``show``. - """ +Equivalent to ``show``.""" ... + def fill(self, colour: Tuple[int, ...]) -> None: - """Colour all pixels a given RGB/RGBW value (micro:bit V2 only). + """用特定 RGB/RGBW 值為所有像素著色 (僅限 micro:bit V2)。 - Example: ``np.fill((0, 0, 255))`` +Example: ``np.fill((0, 0, 255))`` - :param colour: A tuple of the same length as the number of bytes per pixel (bpp). +:param colour: 長度與每像素位元組數 (bpp) 相同的元組。 - Use in conjunction with ``show()`` to update the neopixels. - """ +Use in conjunction with ``show()`` to update the neopixels.""" ... + def __setitem__(self, key: int, value: Tuple[int, ...]) -> None: - """Set a pixel colour. + """設定像素顏色。 - Example: ``np[0] = (255, 0, 0)`` +Example: ``np[0] = (255, 0, 0)`` + +:param key: 像素編號。 +:param value: 顏色。""" - :param key: The pixel number. - :param value: The colour. - """ def __getitem__(self, key: int) -> Tuple[int, ...]: - """Get a pixel colour. + """取得像素顏色。 + +Example: ``r, g, b = np[0]`` - Example: ``r, g, b = np[0]`` +:param key: 像素編號。 +:return: The colour tuple.""" - :param key: The pixel number. - :return: The colour tuple. - """ def __len__(self) -> int: - """Get length of this pixel strip. + """取得此像素燈條的長度。 - Example: ``len(np)`` - """ +Example: ``len(np)``""" \ No newline at end of file diff --git a/lang/zh-tw/typeshed/stdlib/os.pyi b/lang/zh-tw/typeshed/stdlib/os.pyi index 2f2db77..cf8c724 100644 --- a/lang/zh-tw/typeshed/stdlib/os.pyi +++ b/lang/zh-tw/typeshed/stdlib/os.pyi @@ -1,73 +1,63 @@ -"""Access the file system. -""" - +"""存取檔案系統。""" from typing import Tuple from typing import List def listdir() -> List[str]: - """List files. + """列出檔案。 - Example: ``os.listdir()`` +Example: ``os.listdir()`` - :return: A list of the names of all the files contained within the local - persistent on-device file system. - """ +:return: A list of the names of all the files contained within the local +persistent on-device file system.""" ... def remove(filename: str) -> None: - """Remove (delete) a file. + """移除 (刪除) 一個檔案。 - Example: ``os.remove('data.txt')`` +Example: ``os.remove('data.txt')`` - :param filename: The file to delete. +:param filename: 要刪除的檔案。 - If the file does not exist an ``OSError`` exception will occur. - """ +If the file does not exist an ``OSError`` exception will occur.""" ... def size(filename: str) -> int: - """Returns the size of a file. + """傳回檔案的大小。 - Example: ``os.size('data.txt')`` +Example: ``os.size('data.txt')`` - :param filename: The file - :return: The size in bytes. +:param filename: 檔案 +:return: The size in bytes. - If the file does not exist an ``OSError`` exception will occur. - """ +If the file does not exist an ``OSError`` exception will occur.""" class uname_result(Tuple[str, str, str, str, str]): - """Result of ``os.uname()``""" + """``os.uname()`` 的結果""" sysname: str - """Operating system name.""" - + """作業系統名稱。""" nodename: str - """Name of machine on network (implementation-defined).""" - + """網路上的機器名稱 (執行定義)。""" release: str - """Operating system release.""" - + """作業系統發佈。""" version: str - """Operating system version.""" - + """作業系統版本。""" machine: str - """Hardware identifier.""" + """硬體識別碼。""" def uname() -> uname_result: - """Returns information identifying the current operating system. + """傳回識別目前作業系統的資訊。 - Example: ``os.uname()`` +Example: ``os.uname()`` - The return value is an object with five attributes: +The return value is an object with five attributes: - - ``sysname`` - operating system name - - ``nodename`` - name of machine on network (implementation-defined) - - ``release`` - operating system release - - ``version`` - operating system version - - ``machine`` - hardware identifier +- ``sysname`` - operating system name +- ``nodename`` - name of machine on network (implementation-defined) +- ``release`` - operating system release +- ``version`` - operating system version +- ``machine`` - hardware identifier - There is no underlying operating system in MicroPython. As a result the - information returned by the ``uname`` function is mostly useful for - versioning details. - """ - ... +There is no underlying operating system in MicroPython. As a result the +information returned by the ``uname`` function is mostly useful for +versioning details.""" + ... \ No newline at end of file diff --git a/lang/zh-tw/typeshed/stdlib/radio.pyi b/lang/zh-tw/typeshed/stdlib/radio.pyi index 8dd0267..94a4b6d 100644 --- a/lang/zh-tw/typeshed/stdlib/radio.pyi +++ b/lang/zh-tw/typeshed/stdlib/radio.pyi @@ -1,152 +1,131 @@ -"""Communicate between micro:bits with the built-in radio. -""" - +"""使用內建無線電在 micro:bits 之間進行通訊。 (無線電)""" from _typeshed import WriteableBuffer from typing import Optional, Tuple - RATE_1MBIT: int -"""Constant used to indicate a throughput of 1 MBit a second.""" - +"""常數用於指示每秒 1 MBit 的輸送量。""" RATE_2MBIT: int -"""Constant used to indicate a throughput of 2 MBit a second.""" +"""常數用於指示每秒 2 MBit 的輸送量。""" def on() -> None: - """Turns the radio on. + """開啟無線電。 - Example: ``radio.on()`` +Example: ``radio.on()`` - This needs to be explicitly called since the radio draws power and takes - up memory that you may otherwise need. - """ +This needs to be explicitly called since the radio draws power and takes +up memory that you may otherwise need.""" ... def off() -> None: - """Turns off the radio, saving power and memory. + """關閉無線電,節省電量和記憶體。 - Example: ``radio.off()`` - """ +Example: ``radio.off()``""" ... -def config( - length: int = 32, - queue: int = 3, - channel: int = 7, - power: int = 6, - address: int = 0x75626974, - group: int = 0, - data_rate: int = RATE_1MBIT, -) -> None: - """Configures the radio. - - Example: ``radio.config(group=42)`` - - The default configuration is suitable for most use. - - :param length: (default=32) defines the maximum length, in bytes, of a message sent via the radio. - It can be up to 251 bytes long (254 - 3 bytes for S0, LENGTH and S1 preamble). - :param queue: (default=3) specifies the number of messages that can be stored on the incoming message queue. - If there are no spaces left on the queue for incoming messages, then the incoming message is dropped. - :param channel: (default=7) an integer value from 0 to 83 (inclusive) that defines an arbitrary "channel" to which the radio is tuned. - Messages will be sent via this channel and only messages received via this channel will be put onto the incoming message queue. Each step is 1MHz wide, based at 2400MHz. - :param power: (default=6) is an integer value from 0 to 7 (inclusive) to indicate the strength of signal used when broadcasting a message. - The higher the value the stronger the signal, but the more power is consumed by the device. The numbering translates to positions in the following list of dBm (decibel milliwatt) values: -30, -20, -16, -12, -8, -4, 0, 4. - :param address: (default=0x75626974) an arbitrary name, expressed as a 32-bit address, that's used to filter incoming packets at the hardware level, keeping only those that match the address you set. - The default used by other micro:bit related platforms is the default setting used here. - :param group: (default=0) an 8-bit value (0-255) used with the ``address`` when filtering messages. - Conceptually, "address" is like a house/office address and "group" is like the person at that address to which you want to send your message. - :param data_rate: (default=``radio.RATE_1MBIT``) indicates the speed at which data throughput takes place. - Can be one of the following constants defined in the ``radio`` module: ``RATE_250KBIT``, ``RATE_1MBIT`` or ``RATE_2MBIT``. - - If ``config`` is not called then the defaults described above are assumed. - """ +def config(length: int=32, queue: int=3, channel: int=7, power: int=6, address: int=1969383796, group: int=0, data_rate: int=RATE_1MBIT) -> None: + """設定無線電。 + +Example: ``radio.config(group=42)`` + +The default configuration is suitable for most use. + +:param length: (default=32) 定義透過無線電傳送的訊息的最大長度 (以位元組為單位)。 +最長可達 251 個位元組 (S0、LENGTH 和 S1 前序編碼為 254 - 3 個位元組)。 +:param queue: (default=3) 指定可以存儲在傳入訊息佇列中的訊息數。 +如果佇列中沒有空間可留給傳入訊息,則捨棄傳入訊息。 +:param channel: (default=7) 一個從 0 到 83 (包含) 的整數值,定義無線電調整到的任意 "channel"。 +訊息將透過此頻道傳送,只有透過此頻道接收的訊息,才會放入傳入訊息佇列。 +每一步都是 1MHz 寬,以 2400MHz 為基礎。 +:param power: (default=6) 是一個從 0 到 7 (包含) 的整數值,表示無線電訊息時使用的訊號功率。 +數值越高,訊號越強,但裝置消耗的功率越多。編號轉換為下列 dBm (分貝毫瓦) 數值列表中的位置:-30、-20、-16、-12、-8、-4、0、4。 +:param address: (default=0x75626974) 任意名稱,表示為 32 位元位址,用於在硬體等級篩選傳入的資料套件,僅保留與您設定的位址相符的那些。 +其他 micro:bit 相關平台使用的預設設定,則是此處使用的預設設定。 +:param group: (default=0) 篩選訊息時與 ``address`` 一起使用的 8 位元值 (0-255)。 +從概念上講,"address" 就像一個家庭/辦公室地址,而 "group" 就像您要向該地址傳送訊息的人。 +:param data_rate: (default=``radio.RATE_1MBIT``) 表示資料輸送量發生的速度。 +可以是 ``radio`` 模組中定義的下列常數之一:``RATE_250KBIT``、``RATE_1MBIT`` 或 ``RATE_2MBIT``。 + +If ``config`` is not called then the defaults described above are assumed.""" ... def reset() -> None: - """Reset the settings to their default values. + """將設定重設為其預設值。 - Example: ``radio.reset()`` +Example: ``radio.reset()`` - The defaults as as per the ``config`` function above. - """ +The defaults as as per the ``config`` function above.""" ... def send_bytes(message: bytes) -> None: - """Sends a message containing bytes. + """傳送包含位元組的訊息。 - Example: ``radio.send_bytes(b'hello')`` +Example: ``radio.send_bytes(b'hello')`` - :param message: The bytes to send. - """ +:param message: 要傳送的位元組。""" ... def receive_bytes() -> Optional[bytes]: - """Receive the next incoming message on the message queue. + """接收訊息佇列中的下一則傳入訊息。 - Example: ``radio.receive_bytes()`` +Example: ``radio.receive_bytes()`` - :return: The message bytes if any, otherwise ``None``. - """ +:return: The message bytes if any, otherwise ``None``.""" ... def receive_bytes_into(buffer: WriteableBuffer) -> Optional[int]: - """Copy the next incoming message on the message queue into a buffer. + """將訊息佇列中的下一則傳入訊息複製到緩衝區。 - Example: ``radio.receive_bytes_info(buffer)`` +Example: ``radio.receive_bytes_info(buffer)`` - :param buffer: The target buffer. The message is truncated if larger than the buffer. - :return: ``None`` if there are no pending messages, otherwise it returns the length of the message (which might be more than the length of the buffer). - """ +:param buffer: 目標緩衝區。如果訊息大小大於緩衝區,則訊息會被截斷。 +:return: ``None`` if there are no pending messages, otherwise it returns the length of the message (which might be more than the length of the buffer).""" ... def send(message: str) -> None: - """Sends a message string. + """傳送訊息字串。 - Example: ``radio.send('hello')`` +Example: ``radio.send('hello')`` - This is the equivalent of ``radio.send_bytes(bytes(message, 'utf8'))`` but with ``b'\x01\x00\x01'`` - prepended to the front (to make it compatible with other platforms that target the micro:bit). +This is the equivalent of ``radio.send_bytes(bytes(message, 'utf8'))`` but with ``b'\x01\x00\x01'`` +prepended to the front (to make it compatible with other platforms that target the micro:bit). - :param message: The string to send. - """ +:param message: 要傳送的字串。""" ... def receive() -> Optional[str]: - """Works in exactly the same way as ``receive_bytes`` but returns whatever was sent. + """工作方式與 ``receive_bytes`` 完全相同,但會傳回傳送的任何內容。 - Example: ``radio.receive()`` +Example: ``radio.receive()`` - Equivalent to ``str(receive_bytes(), 'utf8')`` but with a check that the the first - three bytes are ``b'\x01\x00\x01'`` (to make it compatible with other platforms that - may target the micro:bit). +Equivalent to ``str(receive_bytes(), 'utf8')`` but with a check that the the first +three bytes are ``b'\x01\x00\x01'`` (to make it compatible with other platforms that +may target the micro:bit). - :return: The message with the prepended bytes stripped and converted to a string. +:return: The message with the prepended bytes stripped and converted to a string. - A ``ValueError`` exception is raised if conversion to string fails. - """ +A ``ValueError`` exception is raised if conversion to string fails.""" ... def receive_full() -> Optional[Tuple[bytes, int, int]]: - """Returns a tuple containing three values representing the next incoming message on the message queue. + """傳回一個包含三個數值的元組,用來代表訊息佇列中的下一則傳入訊息。 - Example: ``radio.receive_full()`` +Example: ``radio.receive_full()`` - If there are no pending messages then ``None`` is returned. +If there are no pending messages then ``None`` is returned. - The three values in the tuple represent: +The three values in the tuple represent: - - the next incoming message on the message queue as bytes. - - the RSSI (signal strength): a value between 0 (strongest) and -255 (weakest) as measured in dBm. - - a microsecond timestamp: the value returned by ``time.ticks_us()`` when the message was received. +- the next incoming message on the message queue as bytes. +- the RSSI (signal strength): a value between 0 (strongest) and -255 (weakest) as measured in dBm. +- a microsecond timestamp: the value returned by ``time.ticks_us()`` when the message was received. - For example:: +For example:: - details = radio.receive_full() - if details: - msg, rssi, timestamp = details + details = radio.receive_full() + if details: + msg, rssi, timestamp = details - This function is useful for providing information needed for triangulation - and/or trilateration with other micro:bit devices. +This function is useful for providing information needed for triangulation +and/or trilateration with other micro:bit devices. - :return: ``None`` if there is no message, otherwise a tuple of length three with the bytes, strength and timestamp values. - """ - ... +:return: ``None`` if there is no message, otherwise a tuple of length three with the bytes, strength and timestamp values.""" + ... \ No newline at end of file diff --git a/lang/zh-tw/typeshed/stdlib/random.pyi b/lang/zh-tw/typeshed/stdlib/random.pyi index a2c2ef3..e606e08 100644 --- a/lang/zh-tw/typeshed/stdlib/random.pyi +++ b/lang/zh-tw/typeshed/stdlib/random.pyi @@ -1,93 +1,80 @@ -"""Generate random numbers. -""" +"""生成隨機數。""" from typing import TypeVar, Sequence, Union, overload def getrandbits(n: int) -> int: - """Generate an integer with ``n`` random bits. + """生成具有 ``n`` 個隨機位元的整數。 - Example: ``random.getrandbits(1)`` +Example: ``random.getrandbits(1)`` - :param n: A value between 1-30 (inclusive). - """ +:param n: 介於 1-30 (包含) 之間的值。""" ... def seed(n: int) -> None: - """Initialize the random number generator. + """初始化隨機數生成器。 - Example: ``random.seed(0)`` +Example: ``random.seed(0)`` - :param n: The integer seed +:param n: 整數種子 - This will give you reproducibly deterministic randomness from a given starting - state (``n``). - """ +This will give you reproducibly deterministic randomness from a given starting +state (``n``).""" ... def randint(a: int, b: int) -> int: - """Choose a random integer between ``a`` and ``b`` inclusive. + """在 ``a`` 和 ``b`` (包含) 之間選擇一個隨機整數。 - Example: ``random.randint(0, 9)`` +Example: ``random.randint(0, 9)`` - :param a: Start value for the range (inclusive) - :param b: End value for the range (inclusive) +:param a: 範圍的起始值 (包含) +:param b: 範圍的結束值 (包含) - Alias for ``randrange(a, b + 1)``. - """ +Alias for ``randrange(a, b + 1)``.""" ... @overload def randrange(stop: int) -> int: - """Choose a randomly selected integer between zero and up to (but not - including) ``stop``. + """在零到 (但不包括) ``stop`` 之間隨機選擇一個整數。 - Example: ``random.randrange(10)`` +Example: ``random.randrange(10)`` - :param stop: End value for the range (exclusive) - """ +:param stop: 範圍的結束值 (排除)""" ... @overload -def randrange(start: int, stop: int, step: int = 1) -> int: - """ - Choose a randomly selected element from ``range(start, stop, step)``. +def randrange(start: int, stop: int, step: int=1) -> int: + """從 ``range(start, stop, step)`` 中選擇一個隨機選擇的元素。 - Example: ``random.randrange(0, 10)`` +Example: ``random.randrange(0, 10)`` - :param start: The start of the range (inclusive) - :param stop: The end of the range (exclusive) - :param step: The step. - """ +:param start: 範圍的開始 (包含) +:param stop: 範圍結束 (排除) +:param step: 步驟。""" ... - -_T = TypeVar("_T") +_T = TypeVar('_T') def choice(seq: Sequence[_T]) -> _T: - """Choose a random element from the non-empty sequence ``seq``. + """從非空序列 ``seq`` 中選擇一個隨機元素。 - Example: ``random.choice([Image.HAPPY, Image.SAD])`` +Example: ``random.choice([Image.HAPPY, Image.SAD])`` - :param seq: A sequence. +:param seq: 序列。 - If ``seq`` is empty, raises ``IndexError``. - """ +If ``seq`` is empty, raises ``IndexError``.""" ... def random() -> float: - """Generate a random floating point number in the range [0.0, 1.0). + """在 [0.0, 1.0) 範圍內生成一個隨機浮點數。 - Example: ``random.random()`` +Example: ``random.random()`` - :return: The random floating point number - """ +:return: The random floating point number""" ... def uniform(a: float, b: float) -> float: - """ - Return a random floating point number between ``a`` and ``b`` inclusive. + """傳回一個介於 ``a`` 和 ``b`` 之間的隨機浮點數。 - Example: ``random.uniform(0, 9)`` +Example: ``random.uniform(0, 9)`` - :param a: Start value for the range (inclusive) - :param b: End value for the range (inclusive) - """ - ... +:param a: 範圍的起始值 (包括) +:param b: 範圍的結束值 (包含)""" + ... \ No newline at end of file diff --git a/lang/zh-tw/typeshed/stdlib/speech.pyi b/lang/zh-tw/typeshed/stdlib/speech.pyi index 349d188..01137a7 100644 --- a/lang/zh-tw/typeshed/stdlib/speech.pyi +++ b/lang/zh-tw/typeshed/stdlib/speech.pyi @@ -1,106 +1,79 @@ -"""Make the micro:bit talk, sing and make other speech like sounds. -""" - +"""讓 micro:bit 說話、唱歌和發出類似聲音的其他語音。""" from typing import Optional from .microbit import MicroBitDigitalPin, pin0 def translate(words: str) -> str: - """Translate English words to phonemes. + """將英語單字翻譯成音素。 - Example: ``speech.translate('hello world')`` +Example: ``speech.translate('hello world')`` - :param words: A string of English words. - :return: A string containing a best guess at the appropriate phonemes to pronounce. - The output is generated from this `text to phoneme translation table `_. +:param words: 英文單字字串。 +:return: A string containing a best guess at the appropriate phonemes to pronounce. +The output is generated from this `text to phoneme translation table `_. - This function should be used to generate a first approximation of phonemes - that can be further hand-edited to improve accuracy, inflection and - emphasis. +This function should be used to generate a first approximation of phonemes +that can be further hand-edited to improve accuracy, inflection and +emphasis. - See `the online documentation `_ for detailed information. - """ +See `the online documentation `_ for detailed information.""" ... -def pronounce( - phonemes: str, - pitch: int = 64, - speed: int = 72, - mouth: int = 128, - throat: int = 128, - pin: Optional[MicroBitDigitalPin] = pin0, -) -> None: - """Pronounce phonemes. - - Example: ``speech.pronounce(' /HEHLOW WERLD')`` - - :param phonemes: The string of phonemes to pronounce - :param pitch: A number representing the pitch of the voice - :param speed: A number representing the speed of the voice - :param mouth: A number representing the mouth of the voice - :param throat: A number representing the throat of the voice - :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. - If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. - - Override the optional pitch, speed, mouth and throat settings to change the - timbre (quality) of the voice. - - See `the online documentation `_ for detailed information. - """ - ... +def pronounce(phonemes: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: Optional[MicroBitDigitalPin]=pin0) -> None: + """發出音素的聲音。 + +Example: ``speech.pronounce(' /HEHLOW WERLD')`` + +:param phonemes: 發音的音素字串 +:param pitch: (間距) 一個代表聲音音高的數字 +:param speed: 一個代表聲音速度的數字 +:param mouth: 一個代表聲音口型的數字 +:param throat: 一個代表聲音喉型的數字 +:param pin: (引腳) 指定輸出引腳的可選引數,可用於覆寫預設值 ``pin0``。 +如果我們不想從引腳上播放任何聲音,可以使用 ``pin=None``。僅限 micro:bit。 -def say( - words: str, - pitch: int = 64, - speed: int = 72, - mouth: int = 128, - throat: int = 128, - pin: MicroBitDigitalPin = pin0, -) -> None: - """Say English words. - - Example: ``speech.say('hello world')`` - - :param words: The string of words to say. - :param pitch: A number representing the pitch of the voice - :param speed: A number representing the speed of the voice - :param mouth: A number representing the mouth of the voice - :param throat: A number representing the throat of the voice - :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. - If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. - - The result is semi-accurate for English. Override the optional pitch, speed, - mouth and throat settings to change the timbre (quality) of the voice. - - This is a short-hand equivalent of: - ``speech.pronounce(speech.translate(words))`` - - See `the online documentation `_ for detailed information. - """ +Override the optional pitch, speed, mouth and throat settings to change the +timbre (quality) of the voice. + +See `the online documentation `_ for detailed information.""" ... -def sing( - phonemes: str, - pitch: int = 64, - speed: int = 72, - mouth: int = 128, - throat: int = 128, - pin: MicroBitDigitalPin = pin0, -) -> None: - """Sing phonemes. - - Example: ``speech.sing(' /HEHLOW WERLD')`` - - :param phonemes: The string of words to sing. - :param pitch: A number representing the pitch of the voice - :param speed: A number representing the speed of the voice - :param mouth: A number representing the mouth of the voice - :param throat: A number representing the throat of the voice - :param pin: Optional argument to specify the output pin can be used to override the default of ``pin0``. - If we do not want any sound to play out of the pins can use ``pin=None``. micro:bit V2 only. - - Override the optional pitch, speed, mouth and throat settings to change - the timbre (quality) of the voice. - - See `the online documentation `_ for detailed information. - """ +def say(words: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: MicroBitDigitalPin=pin0) -> None: + """說英語單字。 + +Example: ``speech.say('hello world')`` + +:param words: 要說的一串詞。 +:param pitch: (間距) 一個代表聲音音高的數字 +:param speed: 一個代表聲音速度的數字 +:param mouth: 一個代表聲音口型的數字 +:param throat: 一個代表聲音喉型的數字 +:param pin: (引腳) 指定輸出引腳的可選引數可用於覆寫預設值 ``pin0``。 +如果我們無意從引腳上播放任何聲音,可以使用 ``pin=None``。僅限 micro:bit。 + +The result is semi-accurate for English. Override the optional pitch, speed, +mouth and throat settings to change the timbre (quality) of the voice. + +This is a short-hand equivalent of: +``speech.pronounce(speech.translate(words))`` + +See `the online documentation `_ for detailed information.""" ... + +def sing(phonemes: str, pitch: int=64, speed: int=72, mouth: int=128, throat: int=128, pin: MicroBitDigitalPin=pin0) -> None: + """唱出音素。 + +Example: ``speech.sing(' /HEHLOW WERLD')`` + +:param phonemes: 要唱的一串詞。 +:param pitch: (間距) 一個代表聲音音高的數字 +:param speed: 一個代表聲音速度的數字 +:param mouth: 一個代表聲音口型的數字 +:param throat: 一個代表聲音喉型的數字 +:param pin: (引腳) 指定輸出引腳的可選引數,可用於覆寫預設值 ``pin0``。 +如果我們不想從引腳上播放任何聲音,可以使用 ``pin=None``。僅限 micro:bit。 + +Override the optional pitch, speed, mouth and throat settings to change +the timbre (quality) of the voice. + +See `the online documentation `_ for detailed information.""" + ... \ No newline at end of file diff --git a/lang/zh-tw/typeshed/stdlib/struct.pyi b/lang/zh-tw/typeshed/stdlib/struct.pyi index 53b3e0b..fbe57da 100644 --- a/lang/zh-tw/typeshed/stdlib/struct.pyi +++ b/lang/zh-tw/typeshed/stdlib/struct.pyi @@ -1,65 +1,56 @@ -"""Pack and unpack primitive data types. -""" - +"""壓縮和解壓縮原始資料類型。""" from _typeshed import ReadableBuffer, WriteableBuffer from typing import Any, Tuple, Union def calcsize(fmt: str) -> int: - """Get the number of bytes needed to store the given ``fmt``. + """取得存儲特定 ``fmt`` 所需的位元組數。 - Example: ``struct.calcsize('hf')`` +Example: ``struct.calcsize('hf')`` - :param fmt: A format string. - :return The number of bytes needed to store such a value. - """ +:param fmt: 格式字串。 +:return The number of bytes needed to store such a value.""" ... def pack(fmt: str, v1: Any, *vn: Any) -> bytes: - """Pack values according to a format string. + """根據格式字串,壓縮數值。 - Example: ``struct.pack('hf', 1, 3.1415)`` +Example: ``struct.pack('hf', 1, 3.1415)`` - :param fmt: The format string. - :param v1: The first value. - :param *vn: The remaining values. - :return A bytes object encoding the values. - """ +:param fmt: 格式字串。 +:param v1: 首位數值。 +:param *vn: 剩餘數值。 +:return A bytes object encoding the values.""" ... -def pack_into( - fmt: str, buffer: WriteableBuffer, offset: int, v1: Any, *vn: Any -) -> None: - """Pack values according to a format string. +def pack_into(fmt: str, buffer: WriteableBuffer, offset: int, v1: Any, *vn: Any) -> None: + """根據格式字串,壓縮數值。 - Example: ``struct.pack_info('hf', buffer, 1, 3.1415)`` +Example: ``struct.pack_info('hf', buffer, 1, 3.1415)`` - :param fmt: The format string. - :param buffer: The target buffer to write into. - :param offset: The offset into the buffer. May be negative to count from the end of the buffer. - :param v1: The first value. - :param *vn: The remaining values. - """ +:param fmt: 格式字串。 +:param buffer: 要寫入的緩衝區。 +:param offset: 緩衝區內的位移。從緩衝區結尾開始計數,該位移可能為負數。 +:param v1: 首位數值。 +:param *vn: 剩餘數值。""" ... def unpack(fmt: str, data: ReadableBuffer) -> Tuple[Any, ...]: - """Unpack data according to a format string. + """根據格式字串,解壓縮數值。 - Example: ``v1, v2 = struct.unpack('hf', buffer)`` +Example: ``v1, v2 = struct.unpack('hf', buffer)`` - :param fmt: The format string. - :param data: The data. - :return: A tuple of the unpacked values. - """ +:param fmt: 格式字串。 +:param data: 資料。 +:return: A tuple of the unpacked values.""" ... -def unpack_from(fmt: str, buffer: ReadableBuffer, offset: int = 0) -> Tuple: - """Unpack data from a buffer according to a format string. +def unpack_from(fmt: str, buffer: ReadableBuffer, offset: int=0) -> Tuple: + """根據格式字串,從緩衝區解壓縮資料。 - Example: ``v1, v2 = struct.unpack_from('hf', buffer)`` +Example: ``v1, v2 = struct.unpack_from('hf', buffer)`` - :param fmt: The format string. - :param buffer: The source buffer to read from. - :param offset: The offset into the buffer. May be negative to count from the end of the buffer. - :return: A tuple of the unpacked values. - """ - ... +:param fmt: 格式字串。 +:param buffer: 要讀取的來源緩衝區。 +:param offset: 緩衝區內的位移。從緩衝區結尾開始計數,該位移可能為負數。 +:return: A tuple of the unpacked values.""" + ... \ No newline at end of file diff --git a/lang/zh-tw/typeshed/stdlib/sys.pyi b/lang/zh-tw/typeshed/stdlib/sys.pyi index 320bac9..3342ae5 100644 --- a/lang/zh-tw/typeshed/stdlib/sys.pyi +++ b/lang/zh-tw/typeshed/stdlib/sys.pyi @@ -1,43 +1,36 @@ -"""System specific functions""" - +"""系統特定函式""" from typing import Any, Dict, List, NoReturn, TextIO, Tuple -def exit(retval: object = ...) -> NoReturn: - """Terminate current program with a given exit code. +def exit(retval: object=...) -> NoReturn: + """使用指定的退出代碼來終止當前程式。 - Example: ``sys.exit(1)`` +Example: ``sys.exit(1)`` - This function raises a ``SystemExit`` exception. If an argument is given, its - value given as an argument to ``SystemExit``. +This function raises a ``SystemExit`` exception. If an argument is given, its +value given as an argument to ``SystemExit``. - :param retval: The exit code or message. - """ +:param retval: 退出代碼或訊息。""" ... def print_exception(exc: Exception) -> None: - """ - Print an exception with a traceback. - - Example: ``sys.print_exception(e)`` + """輸出帶有回溯的例外狀況。 - :param exc: The exception to print +Example: ``sys.print_exception(e)`` - This is simplified version of a function which appears in the - ``traceback`` module in CPython. - """ +:param exc: 輸出例外狀況 +This is simplified version of a function which appears in the +``traceback`` module in CPython.""" argv: List[str] -"""A mutable list of arguments the current program was started with.""" - +"""目前程式啟動時,所使用的可變引數列表。""" byteorder: str -"""The byte order of the system (``"little"`` or ``"big"``).""" +"""系統的位元組順序 (``"little"`` 或 ``"big"``)。""" class _implementation: name: str version: Tuple[int, int, int] - implementation: _implementation -"""Object with information about the current Python implementation. +"""包含關於目前 Python 執行資訊的物件。 For MicroPython, it has following attributes: @@ -51,13 +44,9 @@ minimal ports). CPython mandates more attributes for this object, but the actual useful bare minimum is implemented in MicroPython. """ - maxsize: int """ -Maximum value which a native integer type can hold on the current platform, -or maximum value representable by MicroPython integer type, if it's smaller -than platform max value (that is the case for MicroPython ports without -long int support). +本機整數類型在當前平台上可以保存的最大值,或 MicroPython 整數類型可表示的最大值,如果它小於平台最大值 (對於沒有 long int 支援的 MicroPython 連接埠,就是這種情況)。 This attribute is useful for detecting "bitness" of a platform (32-bit vs 64-bit, etc.). It's recommended to not compare this attribute to some @@ -77,17 +66,14 @@ value directly, but instead count number of bits in it:: # (e.g. 31) due to peculiarities described above, so use "> 16", # "> 32", "> 64" style of comparisons. """ - modules: Dict[str, Any] -"""Dictionary of loaded modules. +"""已載入模組的字典。 On some ports, it may not include builtin modules.""" - path: List[str] -"""A mutable list of directories to search for imported modules.""" - +"""用於搜尋匯入模組的可變字典列表。""" platform: str -"""The platform that MicroPython is running on. +"""正在執行 MicroPython 的平台。 For OS/RTOS ports, this is usually an identifier of the OS, e.g. ``"linux"``. For baremetal ports it is an identifier of a board, e.g. ``"pyboard"`` for @@ -97,13 +83,11 @@ distinguish one board from another. If you need to check whether your program runs on MicroPython (vs other Python implementation), use ``sys.implementation`` instead. """ - version: str -"""Python language version that this implementation conforms to, as a string.""" - +"""此執行符合的 Python 語言版本,做為字串。""" version_info: Tuple[int, int, int] -"""Python language version that this implementation conforms to, as a tuple of ints. +"""此執行符合的 Python 語言版本,做為整數元組。 Only the first three version numbers (major, minor, micro) are supported and they can be referenced only by index, not by name. -""" +""" \ No newline at end of file diff --git a/lang/zh-tw/typeshed/stdlib/time.pyi b/lang/zh-tw/typeshed/stdlib/time.pyi index 598c483..2a7d325 100644 --- a/lang/zh-tw/typeshed/stdlib/time.pyi +++ b/lang/zh-tw/typeshed/stdlib/time.pyi @@ -1,132 +1,112 @@ -"""Measure time and add delays to programs. -""" - +"""測量時間並為程式增加延遲。""" from typing import Union def sleep(seconds: Union[int, float]) -> None: - """ - Delay a number of seconds. + """延遲秒數。 - Example: ``time.sleep(1)`` +Example: ``time.sleep(1)`` - :param seconds: The number of seconds to sleep for. - Use a floating-point number to sleep for a fractional number of seconds. - """ +:param seconds: 睡眠的秒數。 +使用浮點數代表睡眠秒數的小數。""" ... def sleep_ms(ms: int) -> None: - """ - Delay for given number of milliseconds. + """延遲指定的毫秒數。 - Example: ``time.sleep_ms(1_000_000)`` +Example: ``time.sleep_ms(1_000_000)`` - :param ms: The number of milliseconds delay (>= 0). - """ +:param ms: 延遲的毫秒數 (>= 0)。""" ... def sleep_us(us: int) -> None: - """ - Delay for given number of microseconds. + """延遲指定的微秒數。 - Example: ``time.sleep_us(1000)`` +Example: ``time.sleep_us(1000)`` - :param us: The number of microseconds delay (>= 0). - """ +:param us: 延遲的微秒數 (>= 0)。""" ... def ticks_ms() -> int: - """ - Get an increasing, millisecond counter with an arbitrary reference point, - that wraps around after some value. + """取得具有任意參考點的遞增毫秒計數器,該計數器會在某個值之後繞回。 - Example: ``time.ticks_ms()`` +Example: ``time.ticks_ms()`` - :return: The counter value in milliseconds. - """ +:return: The counter value in milliseconds.""" ... def ticks_us() -> int: - """ - Get an increasing, microsecond counter with an arbitrary reference point, - that wraps around after some value. + """取得具有任意參考點的遞增微秒計數器,該計數器會在某個值之後繞回。 - Example: ``time.ticks_us()`` +Example: ``time.ticks_us()`` - :return: The counter value in microseconds. - """ +:return: The counter value in microseconds.""" ... def ticks_add(ticks: int, delta: int) -> int: - """ - Offset ticks value by a given number, which can be either positive or - negative. + """特定數字的位移滴答聲值,可以是正數或負數。 - Example: ``time.ticks_add(time.ticks_ms(), 200)`` +Example: ``time.ticks_add(time.ticks_ms(), 200)`` - Given a ticks value, this function allows to calculate ticks - value delta ticks before or after it, following modular-arithmetic - definition of tick values. +Given a ticks value, this function allows to calculate ticks +value delta ticks before or after it, following modular-arithmetic +definition of tick values. - :param ticks: A ticks value - :param delta: An integer offset +:param ticks: 滴答聲值 +:param delta: 整數位移 - Example:: +Example:: - # Find out what ticks value there was 100ms ago - print(ticks_add(time.ticks_ms(), -100)) + # Find out what ticks value there was 100ms ago + print(ticks_add(time.ticks_ms(), -100)) - # Calculate deadline for operation and test for it - deadline = ticks_add(time.ticks_ms(), 200) - while ticks_diff(deadline, time.ticks_ms()) > 0: - do_a_little_of_something() + # Calculate deadline for operation and test for it + deadline = ticks_add(time.ticks_ms(), 200) + while ticks_diff(deadline, time.ticks_ms()) > 0: + do_a_little_of_something() - # Find out TICKS_MAX used by this port - print(ticks_add(0, -1)) - """ + # Find out TICKS_MAX used by this port + print(ticks_add(0, -1))""" ... def ticks_diff(ticks1: int, ticks2: int) -> int: - """ - Measure ticks difference between values returned from - ``time.ticks_ms()`` or ``ticks_us()``, as a signed value - which may wrap around. - - Example: ``time.ticks_diff(scheduled_time, now)`` - - :param ticks1: The value to subtract from - :param ticks2: The value to subtract - - The argument order is the same as for subtraction operator, - ``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. - - ``ticks_diff()`` is designed to accommodate various usage - patterns, among them: - - Polling with timeout. In this case, the order of events is known, and you - will deal only with positive results of :func:`time.ticks_diff()`:: - - # Wait for GPIO pin to be asserted, but at most 500us - start = time.ticks_us() - while pin.value() == 0: - if time.ticks_diff(time.ticks_us(), start) > 500: - raise TimeoutError - - - Scheduling events. In this case, :func:`time.ticks_diff()` result may be - negative if an event is overdue:: - - # This code snippet is not optimized - now = time.ticks_ms() - scheduled_time = task.scheduled_time() - if ticks_diff(scheduled_time, now) > 0: - print("Too early, let's nap") - sleep_ms(ticks_diff(scheduled_time, now)) - task.run() - elif ticks_diff(scheduled_time, now) == 0: - print("Right at time!") - task.run() - elif ticks_diff(scheduled_time, now) < 0: - print("Oops, running late, tell task to run faster!") - task.run(run_faster=True) - """ - ... + """測量從 +``time.ticks_ms()`` 或 ``ticks_us()`` 傳回值之間的滴答聲差異。此參數是一個可能會繞回的帶符號值。 (tick diff) + +Example: ``time.ticks_diff(scheduled_time, now)`` + +:param ticks1: (tick 1) 要被減的值 +:param ticks2: (tick 2) 要減去的值 + +The argument order is the same as for subtraction operator, +``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. + +``ticks_diff()`` is designed to accommodate various usage +patterns, among them: + +Polling with timeout. In this case, the order of events is known, and you +will deal only with positive results of :func:`time.ticks_diff()`:: + + # Wait for GPIO pin to be asserted, but at most 500us + start = time.ticks_us() + while pin.value() == 0: + if time.ticks_diff(time.ticks_us(), start) > 500: + raise TimeoutError + + +Scheduling events. In this case, :func:`time.ticks_diff()` result may be +negative if an event is overdue:: + + # This code snippet is not optimized + now = time.ticks_ms() + scheduled_time = task.scheduled_time() + if ticks_diff(scheduled_time, now) > 0: + print("Too early, let's nap") + sleep_ms(ticks_diff(scheduled_time, now)) + task.run() + elif ticks_diff(scheduled_time, now) == 0: + print("Right at time!") + task.run() + elif ticks_diff(scheduled_time, now) < 0: + print("Oops, running late, tell task to run faster!") + task.run(run_faster=True)""" + ... \ No newline at end of file