Коммит 5b5c8397 создал по автору OMP Education's avatar OMP Education
Просмотр файлов

Add module: JavaScript. #12

владелец 23edb605
......@@ -53,7 +53,13 @@ Copyright © 2016–2023 ООО «Открытая мобильн
* [Примеры](./models_and_views/examples.md)
* [Задания](./models_and_views/tasks.md)
* [Тесты](./models_and_views/tests.md)
* JavaScript
* [JavaScript](./javascript)
* Лекция:
[cлайды](./javascript/lecture.fodp),
[конспект](./javascript/lecture.md)
* [Примеры](./javascript/examples.md)
* [Задания](./javascript/tasks.md)
* [Тесты](./javascript/tests.md)
* Silica
* Qt Quick Controls 2
* Объектная модель Qt
......
# Примеры по теме «Работа с Java Script»
Copyright © 2016–2023 ООО «Открытая мобильная платформа».
Этот документ предоставляется в соответствии
с [Публичной лицензией Creative Commons с указанием авторства версии 4.0 Международная](../../LICENSE.CC-BY-4.0.ru.md).
* [Пример работы с WorkerScript для Qt Creator](../../projects/pascals_triangle_qtcreator)
* [Пример работы с WorkerScript для Аврора IDE](../../projects/pascals_triangle_aurora)
Это отличие свёрнуто
Это отличие свёрнуто
# Задания по теме «Работа с Java Script»
Copyright © 2016–2023 ООО «Открытая мобильная платформа».
Этот документ предоставляется в соответствии
с [Публичной лицензией Creative Commons с указанием авторства версии 4.0 Международная](../../LICENSE.CC-BY-4.0.ru.md).
## Задание 1
Реализуйте параллельное вычисление n-го элемента из последовательности Фибоначчи с помощью `WorkerScript`.
# Тесты по теме «Работа с Java Script»
Copyright © 2016–2023 ООО «Открытая мобильная платформа».
Этот документ предоставляется в соответствии
с [Публичной лицензией Creative Commons с указанием авторства версии 4.0 Международная](../../LICENSE.CC-BY-4.0.ru.md).
## Order
Расположите в правильном порядке вызов базовых действий для рисования линии на `Canvas`:
---
* ctx.strokeStyle = "red"
* ctx.beginPath()
* ctx.moveTo(50,50)
* ctx.lineTo(150,50)
* ctx.stroke()
## Single choice
Сколько вторичных потоков можно подключить к экземпляру `WorkerScript`?
---
* **один**
* два
* три
* от одного до 63
## Single choice
Из какого объекта WorkerScript можно обращаться к свойствам и методам QML?
---
* **Из определённого в QML**
* Из определённого в js-файле
* Из обоих
// SPDX-FileCopyrightText: 2023 Open Mobile Platform LLC <edu@omp.ru>
// SPDX-License-Identifier: BSD-3-Clause
import QtQuick 2.0
Item {
id: root
property real fontSize: width / 16
function requestResult() {
resultText.text = "Loading...";
worker.sendMessage({
row: rowEdit.value,
column: columnEdit.value
});
}
WorkerScript {
id: worker
source: "js/worker.js"
onMessage: {
if (messageObject.row === rowEdit.value
&& messageObject.column === columnEdit.value) {
if (!messageObject.result)
resultText.text = "Column must be <= Row";
else
resultText.text = messageObject.result;
}
}
}
Column {
objectName: "layout"
width: parent.width
Text {
id: resultText
objectName: "resultText"
height: root.height / 2
width: parent.width
wrapMode: Text.WordWrap
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
font.pixelSize: fontSize
}
Row {
objectName: "inputLayout"
anchors.horizontalCenter: parent.horizontalCenter
Text {
id: rowLabel
objectName: "rowLabel"
text: "Row: "
font.pixelSize: fontSize
}
TextEdit {
id: rowEdit
objectName: "rowEdit"
property int value: Number(text)
text: "0"
width: (root.width) / 5
font.pixelSize: fontSize
onValueChanged: {
console.log("row changed: " + value);
requestResult();
}
}
Text {
id: columnLabel
objectName: "columnLabel"
text: "Column: "
font.pixelSize: fontSize
}
TextEdit {
id: columnEdit
objectName: "columnEdit"
property int value: Number(text)
text: "0"
width: (root.width) / 5
font.pixelSize: fontSize
onValueChanged: {
console.log("column changed: " + value);
requestResult();
}
}
}
}
}
// SPDX-FileCopyrightText: 2023 Open Mobile Platform LLC <edu@omp.ru>
// SPDX-License-Identifier: BSD-3-Clause
var cache = [];
function binomialCoefficient(row, column) {
if (!cache[row])
cache[row] = [];
if (cache[row][column] !== undefined)
return cache[row][column];
console.log(row, column);
var result = row < column
? 0
: column === 0 || column === row
? 1
: binomialCoefficient(row - 1, column - 1) +
binomialCoefficient(row - 1, column);
cache[row][column] = result;
return result;
}
WorkerScript.onMessage = function(message) {
var result = binomialCoefficient(message.row, message.column);
WorkerScript.sendMessage({
row: message.row,
column: message.column,
result: result
});
}
Name: ru.auroraos.PascalsTriangle
Summary: Pascal's Triangle
Version: 1.0
Release: 1
Group: Qt/Qt
License: BSD-3-Clause
URL: https://auroraos.ru
Source0: %{name}-%{version}.tar.bz2
Requires: sailfishsilica-qt5 >= 0.10.9
BuildRequires: pkgconfig(auroraapp)
BuildRequires: pkgconfig(Qt5Core)
BuildRequires: pkgconfig(Qt5Qml)
BuildRequires: pkgconfig(Qt5Quick)
BuildRequires: desktop-file-utils
%description
WorkerScript example
%prep
%setup -q -n %{name}-%{version}
%build
%qmake5
%make_build
%install
rm -rf %{buildroot}
%qmake5_install
desktop-file-install --delete-original --dir %{buildroot}%{_datadir}/applications %{buildroot}%{_datadir}/applications/*.desktop
%files
%defattr(-,root,root,-)
%{_bindir}/%{name}
%defattr(644,root,root,-)
%{_datadir}/%{name}
%{_datadir}/applications/%{name}.desktop
%{_datadir}/icons/hicolor/*/apps/%{name}.png
[Desktop Entry]
Type=Application
X-Nemo-Application-Type=silica-qt5
Icon=ru.auroraos.PascalsTriangle
Exec=/usr/bin/ru.auroraos.PascalsTriangle
Name=Pascal's Triangle
Name[ru]=Треугольник Паскаля
[X-Application]
Permissions=
OrganizationName=ru.auroraos
ApplicationName=PascalsTriangle
ExecDBus=/usr/bin/ru.auroraos.PascalsTriangle
# SPDX-FileCopyrightText: 2023 Open Mobile Platform LLC <edu@omp.ru>
# SPDX-License-Identifier: BSD-3-Clause
TARGET = ru.auroraos.PascalsTriangle
CONFIG += \
auroraapp \
SOURCES += \
src/main.cpp \
DISTFILES += \
rpm/$${TARGET}.spec \
AURORAAPP_ICONS = 86x86 108x108 128x128 172x172
// SPDX-FileCopyrightText: 2023 Open Mobile Platform LLC <edu@omp.ru>
// SPDX-License-Identifier: BSD-3-Clause
#include <auroraapp.h>
#include <QtQuick>
int main(int argc, char *argv[])
{
QScopedPointer<QGuiApplication> application(Aurora::Application::application(argc, argv));
application->setOrganizationName(QStringLiteral("ru.auroraos"));
application->setApplicationName(QStringLiteral("PascalsTriangle"));
QScopedPointer<QQuickView> view(Aurora::Application::createView());
view->setSource(Aurora::Application::pathTo(QStringLiteral("qml/PascalsTriangle.qml")));
view->show();
return application->exec();
}
# SPDX-FileCopyrightText: 2023 Open Mobile Platform LLC <edu@omp.ru>
# SPDX-License-Identifier: BSD-3-Clause
QT += \
quick\
CONFIG += \
c++17 \
DEFINES += \
QT_DEPRECATED_WARNINGS \
SOURCES += \
src/main.cpp \
RESOURCES += \
qml.qrc \
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
<RCC>
<qresource prefix="/">
<file>qml/js/worker.js</file>
<file>qml/main.qml</file>
<file>qml/PascalsTriangle.qml</file>
</qresource>
</RCC>
// SPDX-FileCopyrightText: 2023 Open Mobile Platform LLC <edu@omp.ru>
// SPDX-License-Identifier: BSD-3-Clause
import QtQuick 2.0
Item {
id: root
property real fontSize: width / 16
function requestResult() {
resultText.text = "Loading...";
worker.sendMessage({
row: rowEdit.value,
column: columnEdit.value
});
}
WorkerScript {
id: worker
source: "js/worker.js"
onMessage: {
if (messageObject.row === rowEdit.value
&& messageObject.column === columnEdit.value) {
if (!messageObject.result)
resultText.text = "Column must be <= Row";
else
resultText.text = messageObject.result;
}
}
}
Column {
objectName: "layout"
width: parent.width
Text {
id: resultText
objectName: "resultText"
height: root.height / 2
width: parent.width
wrapMode: Text.WordWrap
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
font.pixelSize: fontSize
}
Row {
objectName: "inputLayout"
anchors.horizontalCenter: parent.horizontalCenter
Text {
id: rowLabel
objectName: "rowLabel"
text: "Row: "
font.pixelSize: fontSize
}
TextEdit {
id: rowEdit
objectName: "rowEdit"
property int value: Number(text)
text: "0"
width: (root.width) / 5
font.pixelSize: fontSize
onValueChanged: {
console.log("row changed: " + value);
requestResult();
}
}
Text {
id: columnLabel
objectName: "columnLabel"
text: "Column: "
font.pixelSize: fontSize
}
TextEdit {
id: columnEdit
objectName: "columnEdit"
property int value: Number(text)
text: "0"
width: (root.width) / 5
font.pixelSize: fontSize
onValueChanged: {
console.log("column changed: " + value);
requestResult();
}
}
}
}
}
// SPDX-FileCopyrightText: 2023 Open Mobile Platform LLC <edu@omp.ru>
// SPDX-License-Identifier: BSD-3-Clause
var cache = [];
function binomialCoefficient(row, column) {
if (!cache[row])
cache[row] = [];
if (cache[row][column] !== undefined)
return cache[row][column];
console.log(row, column);
var result = row < column
? 0
: column === 0 || column === row
? 1
: binomialCoefficient(row - 1, column - 1) +
binomialCoefficient(row - 1, column);
cache[row][column] = result;
return result;
}
WorkerScript.onMessage = function(message) {
var result = binomialCoefficient(message.row, message.column);
WorkerScript.sendMessage({
row: message.row,
column: message.column,
result: result
});
}
Поддерживает Markdown
0% или .
You are about to add 0 people to the discussion. Proceed with caution.
Сначала завершите редактирование этого сообщения!
Пожалуйста, зарегистрируйтесь или чтобы прокомментировать