Beaker is a smart contract development framework for PyTeal.
Hello, Beaker
frompytealimport*frombeakerimport*hello_app=Application("HelloBeaker")
@hello_app.externaldefhello(name: abi.String, *, output: abi.String) ->Expr:
# Set output to the result of `Hello, `+namereturnoutput.set(Concat(Bytes("Hello, "), name.get()))
# Create an Application clientapp_client=client.ApplicationClient(
# Get sandbox algod clientclient=sandbox.get_algod_client(),
# Pass instance of app to clientapp=hello_app,
# Get acct from sandbox and pass the signersigner=sandbox.get_accounts().pop().signer,
)
# Deploy the app on-chainapp_id, app_addr, txid=app_client.create()
print(
f"""Deployed app in txid {txid} App ID: {app_id} Address: {app_addr}"""
)
# Call the `hello` methodresult=app_client.call(hello, name="Beaker")
print(result.return_value) # "Hello, Beaker"
Install
Beaker requires Python >= 3.10
You can install from pip:
pip install beaker-pyteal
Or from github directly (no promises on stability):
We recommend that any production smart contracts be audited by a professional before deployment. Beaker has been thoroughly tested, but we cannot guarantee that it is entirely free of bugs.
First off, create a .env file (use the .env.example for reference)
Next, simply use this command to run the application:
docker-compose up
You will then see something similar to this:
...
discord-bot | INFO connecting to database discord on db.py:10
discord-bot | mysql:3306 as user root
discord-bot | INFO creating table todo db.py:21
discord-bot | [2022-11-12 08:46:08] [INFO ] discord.client: logging in using static token
discord-bot | INFO logging in using static token client.py:571
discord-bot | [2022-11-12 08:46:11] [INFO ] discord.gateway: Shard ID None has connected to Gateway (Session ID: ---).
discord-bot | [2022/11/12 08:46;11] INFO Shard ID None has connected to gateway.py:560
discord-bot | Gateway (Session ID:
discord-bot | ----).
discord-bot | [2022/11/12 08:46;13] INFO We have logged in as mhasan01-bot#--- main.py:15
It will download the image from the remote location, modify it using libvips and return it to the client.
Operations
A number of operations exposed by libvips are supported by PlugImageProcessing. See the PlugImageProcessing.Operations.* module for more details.
Requests validations
Validations can be added so your endpoint is more secure.
Signature key
By adding a signature key in your config, a parameter sign needs to be included in the URL to validate the payload.
The signature prevent a client to forge a large number of unique requests that would go through the CDN and hitting our server.
will fail because the sign parameter is not present.
The HMAC-SHA256 hash is created by taking the URL path (excluding the leading /), the request parameters (alphabetically-sorted and concatenated with & into a string). The hash is then base64url-encoded.
Mirego is a team of passionate people who believe that work is a place where you can innovate and have fun. We’re a team of talented people who imagine and build beautiful Web and mobile applications. We come together to share ideas and change the world.
«What to watch» — это проект на Laravel, который представляет собой REST-API для веб-приложения онлайн-кинотеатра. В рамках этого проекта большой акцент делался на автоматизированном тестировании (помимо работы с API) и подходе TDD. Всего было написано 63 автотеста.
Страница представляет собой список по 8 фильмов с пагинацией.
Информация о фильме содержит название, превью обложки (изображение для отображения в списке), превью видео (ссылка на превью) и другую дополнительную информацию для построения пагинации.
Есть возможность отсортировать список по дате выхода и рейтингу фильма.
По умолчанию фильмы сортируются по дате выхода, от новых к старым (desc).
Этот же endpoint может использоваться для получения списка фильмов по жанру.
Отправка get запроса на endpoint получения списка фильмов
Возвращение первых 8 фильмов, если не передано другое условие (параметр page)
Вместе со списком сериалов возвращаются параметры пагинации: количество элементов всего ссылка на первую страницу, на последнюю, на предыдущую и следующую
Дополнительно вместе с запросом могут быть переданы следующие параметры:
page — номер страницы, для пагинации
genre — фильтрация по жанру
status — фильтрация по статусу, по умолчанию значение ready, пользователь с ролью модератор может изменить значение на (pending, moderate)
order_by — правило сортировки. Возможные значения: released, rating
order_to — направление сортировки. Возможные значения: asc, desc
Получение информации о фильме GET/api/films/{id}
При получении информации о фильме с идентификатором id пользователь видит следующую информацию:
Большой постер
Превью (маленькое изображение)
Обложка фильма
Цвет фона для карточки фильма
Название фильма
Жанры
Год выхода на экраны
Описание
Режиссёр
Список актёров
Продолжительность фильма
Ссылка на видео
Ссылка на превью видео
Рейтинг фильма, в виде числа, к-во голосов
Если запрос выполняет авторизованный пользователь — в дополнение к другим данным, возвращается статус наличия фильма в избранном.
В случае попытки обращения к несуществующему фильму, ожидается возврат 404 ошибки.
Получение списка жанров GET/api/genres
Технический endpoint. Для формирования списка жанров в форме поиска или каталоге.
Редактирование жанра PATCH/api/genres/{genre}
Метод доступен только аутентифицированному пользователю с ролью модератор.
Получение списка фильмов добавленных пользователем в избранное GET/api/favorite
Метод возвращает список фильмов, добавленных пользователем в избранное (список «К просмотру»).
Формат и информация возвращаемая в этом списке аналогична методу для получения списка фильмов.
Фильмы возвращаются в порядке добавления пользователем в список, от новых к старым.
Метод доступен только аутентифицированному пользователю.
Добавление фильма в избранное POST/api/films/{id}/favorite/
Метод принимает на вход id добавляемого фильма.
В случае попытки добавления несуществующего фильма, ожидается возврат 404 ошибки.
В случае попытки добавления в избранное фильма который уже присутствует в списке пользователя — ошибка 422, с соответствующим сообщением (message).
Метод доступен только аутентифицированному пользователю.
Удаление фильма из избранного DELETE/api/films/{id}/favorite/
Метод принимает на вход id удаляемого фильма.
В случае попытки удаления несуществующего фильма, ожидается возврат 404 ошибки.
В случае попытки удаления фильма, который отсутствует в списке пользователя, — ошибка 422, с соответствующим сообщением (message).
Метод доступен только аутентифицированному пользователю.
Получение списка похожих фильмов GET/api/films/{id}/similar
Отправляя на роут получения похожих фильмов с указанием id фильма для которого запрашиваются похожие, метод возвращает список из 4 подходящих фильмов.
Похожесть определяется принадлежностью к тем же жанрам, что и исходный фильм (любым из имеющихся).
Формат и информация возвращаемая в этом списке аналогична методу для получения списка фильмов.
Получение списка отзывов к фильму GET/api/comments/{id}
Метод принимает на вход id фильма, в случае отсутствия такового — возвращается 404 ошибка.
Возвращает список отзывов. Каждый отзыв содержит: текст отзыва, имя автора, дату написания отзыва. Также может содержать оценку.
Отзывы, загруженные из внешнего источника, возвращаются в общем списке с именем автора «Гость» Отзывы отсортированы от наиболее новых к старым (desc).
Добавление отзыва к фильму POST/api/comments/{id}
В качестве параметра в адресе указывается id фильма к которому добавляется комментарий.
Комментарий может быть добавлен отдельно, так и в ответ на другой, в этом случае в теле запроса указывается и comment_id.
Метод доступен только аутентифицированному пользователю.
Правила валидации:
Поле
Тип
Обязательное
Правила
Пример
text
string
true
min: 50, max: 400
Discerning travellers and Wes Anderson fans will luxuriate in the glorious Mittel-European kitsch of one of the director’s funniest and most exquisitely designed movies in years.
Метод доступен только аутентифицированному пользователю.
Пользователь может удалить свой комментарий, при условии, что комментарий не содержит ответов.
Модератор может удалить любой комментарий.
При удалении комментария, имеющего ответы, удаляются все его потомки.
Получение промо-фильма GET/api/promo
Метод, возвращающий фильм, являющийся продвигаемым на данный момент (promo).
Формат и информация возвращаемая в этом списке аналогична методу для получения информации о фильме.
Установка промо-фильма POST/api/promo/{id}
Метод доступен только аутентифицированному пользователю с ролью модератор.
При отсутствии запрошенного в роуте фильма в базе, на запрос возвращается 404 ошибка.
Добавление фильма в базу POST/api/films
Модератор указывает в форме идентификатор фильма с сайта imdb вида tt0111161.
Создается фоновая задача, которая запрашивает данные о фильме из внешнего источника, и обновляет информацию о фильме в базе.
В момент создания заявки, фильм сохраняется только с imdb_id и статусом «в ожидании» (pending).
После загрузки данных, статус меняется на «на модерации» (moderate). Модератор может получить список фильмов с этим статусом, отредактировать его, заполнить недостающие поля, указать ссылки на видео и прочее, после чего поставить статус «готов» (ready) — после чего фильм будет доступен пользователям.
Для получения информации о фильме можно использовать сервис http://www.omdbapi.com (или api htmlacademy)
Метод доступен только аутентифицированному пользователю с ролью модератор.
Правила валидации:
Поле
Тип
Обязательное
Правила
Пример
imdb_id
string
true
уникальное, проверка формата ttXXX
tt0944947
При заполнении поля imdb_id и наличии фильма с таким id в базе — возвращается ошибка валидации 422.
При сохранении проверяем наличие связанных жанров и создаем при отсутствии.
Редактирование фильма PATCH/api/films/{id}
Модератор может изменить информацию о фильме или заполнить недостающие данные после добавления фильма.
Метод доступен только аутентифицированному пользователю с ролью модератор.
In the 1930s, the Grand Budapest Hotel is a popular European ski resort, presided over by concierge Gustave H. (Ralph Fiennes). Zero, a junior lobby boy, becomes Gustave’s friend and protege.
Financial Tracker Application is a web application that allows their user to keep track of their income and expense. To use this application, user just need to register to the application, then login to add an income or expense that they got. After that, the system will automatically calculate their balance and display a line chart that visualize the transaction per month. User can also generate the transaction history into PDF format with this application.
Install project dependency
Make sure that your terminal pointing at the root directory of this project (financial-tracker folder).
yarn install && cd client && yarn install
Complete the .env variable
Rename .env.example file at server/config directory become .env, then fill the value for every key. Below is the guideline for filling the .env value:
Complete the constant.ts value
Rename constant.example.ts file at client/src/utils directory become constant.ts, then fill the value for every constant. Below is the guideline for filling the constant.ts value:
Key
What To Fill
Example Value
GOOGLE_CLIENT_ID
Your google client ID
3392348929324-tarur228dxxx
FACEBOOK_APP_ID
Your facebook app ID
18239943847394
Create a database with name corresponding to your DB_ENV value at .env file
Run below command at your terminal that pointing to the root directory of this project
If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag “enhancement”.
Don’t forget to give the project a star! Thanks again!
Fork the Project
Create your Feature Branch (git checkout -b feature/AmazingFeature)
Commit your Changes (git commit -m 'Add some AmazingFeature')
Push to the Branch (git push origin feature/AmazingFeature)
Дизайнери 🎨 підготували для нас макет командного проекту в 3 версіях: мобільна📱, планшетна📟, десктопна💻.
GoIT підготувала ТЗ 📖
🏁 Наші завдання :
розробити сайт з пошуку популярних фільмів;
організувати бібліотеку користувача, де будуть зберігатися улюблені та переглянуті фільми;
організувати для користувача можливість видалення фільмів з бібліотеки;
розробити карточку фільму з детальним описом;
реалізувати перегляд трейлерів фільму за бажанням користувача;
розробити авторизацію користувача на сайті;
розробити пагінацію.
🔨 Під час виконання проекту ми:
закріпили знання з HTML і CSS/SASS;
закріпили знання з JavaScript;
працювали з Parcel;
практикували навички командной работи з Git;
використовували методологію Scrum;
працювали з анімацією;
використовували Firebase для авторизації користувачів і зберігання інформації.
В результаті злагодженої роботи 🤝 ми отримали наш проект: ⬇ Переглянути проект ⬇
EN————————————————————————————————————————–EN
WEB servise “Filmoteka”
Hi! 🤗
We are students of group named “Team-10” of GоIT academy 🔥 🚀
Designers 🎨 prepared for us 3 Versions of team project layout : mobile, tablet, desktop.
GoIT academy prepared technical tasks 📖
🏁 Tasks :
develop a website for searching of popular film;
give to users an opportunity to search films by genre;
orgonize user’s library for collecting favourite and watched films;
orgonize for user’s library an opportunity to delete movie from library;
develop a movie card with detailed description;
develop a movie card’s slider for next/previous card view by pushing arrow buttons (left/right);
implement viewing of movie trailers at the user’s request;
develop user authorization on website;
develop pagination;
develop localization for language change: english/ukrainian.
🔨 During project developing we:
consolidated knowledges of HTML and CSS/SASS;
consolidated knowledges of JavaScript;
worked with Parcel;
teamwork practice with Git;
used Scrum methodology;
worked with animation;
used Firebase for user authorization and information collaction.
As a result 🤝 we made our project: ⬇ View a project link ⬇
Choose FI Podcast – Listen to the latest episodes from one of the top business and finance podcasts in the world! – Spotify.
NPR: Money Talks – Money Talks airs Tuesday mornings at 9 Central Time on MPB Think Radio and over the internet at mpbonline.org – Apple.
NPR: Planet Money – The economy explained. Imagine you could call up a friend and say, “Meet me at the bar and tell me what’s going on with the economy.” Now imagine that’s actually a fun evening. – Spotify, Apple, Google, Pocket Casts, NPR One.
NPR: How I Built This with Guy Raz – Guy Raz dives into the stories behind some of the world’s best known companies. How I Built This weaves a narrative journey about innovators, entrepreneurs and idealists—and the movements they built. – Spotify, Apple, Google, Pocket Casts, NPR One.
NPR: The Indicator from Planet Money – A little show about big ideas. From the people who make Planet Money, The Indicator helps you make sense of what’s happening today. It’s a quick hit of insight into work, business, the economy, and everything else. Listen weekday afternoons. – Spotify, Apple, Google, Pocket Casts, NPR One.
Teamistry – Teamistry is the chemistry of unsung teams that achieve the impossible. – Spotify, Apple, Google.
At the table – Sit across the table from one of the foremost experts in leadership and business. In his simple and approachable style, Pat tackles every topic related to the world of work (and some that aren’t). From culture to family to building world-class organizations, Pat brings his wisdom, humor, and insight together to provide actionable advice for leaders everywhere. – Spotify, Apple, Google.
Codeblocks .NET – We are a few guys who’ve been professional programmers for years. As avid listeners of podcasts and consumers of many things code-related, we were frustrated by the lack of quality programming (pun) available in listenable formats. Given our years of experience and real-world problem solving skills, we thought it might be worth getting into this world of podcasting and “giving back” a shot. – Spotify, Apple, OverCast.
Elixir Talk – Desmond Bowe and Chris Bell present a titillating discussion about Elixir application design and the state of the ecosystem. – Spotify, Apple.
The Stack Overflow Podcast – The Stack Overflow podcast is a frank and funny conversation about what it means to work in software and how code is reshaping our world. As it celebrates its 12th anniversary, it’s a must listen for any programmer, as necessary as Stack Overflow itself. – Spotify, Apple, Google, OverCast.
Elixir Wizards – Elixir Wizards is an interview-format podcast, focused on engineers who use the Elixir programming language. Initially launched in early 2019, each season focuses on a specific topic or topics, with each interview focusing on the guest’s experience and opinions on the topic. Elixir Wizards is hosted by Justus Eapen, Eric Oestrich, and Sundi Myint of SmartLogic, a dev shop that’s been building custom software since 2005 and running Elixir applications in production since 2015. Learn more about how SmartLogic uses Phoenix and Elixir. (https://smartlogic.io/phoenix-and-elixir?utm_source=awesome-podcasts) – Spotify, Apple, Google, Overcast, Stitcher, Pocket Casts.
Deep Questions with Cal Newport – Cal Newport is a computer science professor and the New York Times bestselling author of Digital Minimalism and Deep Work. He writes about technology and the way it can both support and impede our efforts to live more meaningful, productive lives. In this podcast, he answers questions from his readers about work, technology, and the deep life. – Apple.
The Dark Horse Entrepreneur – From hitting the rock bottom of drugs, divorce, bankruptcy and even the death of an 18 month old daughter to running the planning & marketing of some of corporate america’s finest companies. My name is Tracy Brinkmann an entrepreneur, author and uplifting coach. You see, I know that life isn’t fair and participation awards do not feed your family… I invite you to learn from a fellow Dark Horse all that I have learned and am still learning about starting, restarting, kick starting and stepping up your entrepreneur business and marketing game while not ignoring that amazing tool between your ears..yep your personal development & psychology counts too! – Spotify, Apple, Stitcher, Overcast, TuneIn.
Sports
Running
The Morning Shakeout Podcast – On a weekly basis, host Mario Fraioli gleans unique insights and inspiration from a wide range of athletes, coaches, and personalities in the sport of running through compelling longform conversations you won’t hear anywhere else. – Spotify, Apple, Google, Overcast, Stitcher, SoundCloud.
Other
Brain Science – Brain Science, for the curious! We’re exploring the human brain to understand behavior change, habit formation & mental health. – Spotify, Apple, Android, Overcast.
Cautionary Tales – Cautionary Tales is my new podcast from Pushkin Industries, makers of Malcolm Gladwell’s Revisionist History, Michael Lewis’s Against The Rules, and Laurie Santos’s Happiness Lab. – Spotify, Apple, Stitcher.
Leaders in Supply Chain & Logistics Podcast – Leaders in Supply Chain and Logistics Podcast is one of our projects focused on bringing some of the best thought leaders in the industry, pick their brains and share it with as many interested listeners as possible. – Spotify, Apple, Google, Stitcher.
The Peter Attia Drive – The Peter Attia Drive is a weekly, deep-dive podcast focusing on maximizing longevity, and all that goes into that from physical to cognitive to emotional health. With over 25 million episodes downloaded, it features topics including fasting, ketosis, Alzheimer’s disease, cancer, mental health, and much more. The Drive is hosted by Dr. Peter Attia, a Stanford/Johns Hopkins/NIH-trained physician focusing on the applied science of longevity, the extension of human life and well-being. – Spotify, Apple, Google, Overcast.
Huberman Lab – The Huberman Lab Podcast discusses Neuroscience: how our brain and its connections with the organs of our body controls our perceptions, our behaviors, and our health. – Spotify, Apple.
Ελληνικά
Κωμωδία
Μαρμελάδα Φράουλα – Δύο stand up κωμικοί μιλάνε για τη ζωή, τις ευκολίες, τις δυσκολίες και τις ποικιλίες, περίεργα άρθρα της Wikipedia και το πού επιλέγουν να σπαταλούν τη ζωή τους στον αχανή θησαυρό του Netflix. – Spotify, Apple.
Aioresponses is a helper to mock/fake web requests in python aiohttp package.
For requests module there are a lot of packages that help us with testing (eg. httpretty, responses, requests-mock).
When it comes to testing asynchronous HTTP requests it is a bit harder (at least at the beginning).
The purpose of this package is to provide an easy way to test asynchronous HTTP requests.
Installing
$ pip install aioresponses
Supported versions
Python 3.7+
aiohttp>=3.3.0,<4.0.0
Usage
To mock out HTTP request use aioresponses as a method decorator or as a context manager.
Response status code, body, payload (for json response) and headers can be mocked.
Supported HTTP methods: GET, POST, PUT, PATCH, DELETE and OPTIONS.
importasyncioimportaiohttpfromaioresponsesimportaioresponses@aioresponses()deftest_http_headers(m):
loop=asyncio.get_event_loop()
session=aiohttp.ClientSession()
m.post(
'http://example.com',
payload=dict(),
headers=dict(connection='keep-alive'),
)
resp=loop.run_until_complete(session.post('http://example.com'))
# note that we pass 'connection' but get 'Connection' (capitalized)# under the neath `multidict` is used to work with HTTP headersassertresp.headers['Connection'] =='keep-alive'm.assert_called_once_with('http://example.com', method='POST')
allows to register different responses for the same url
E.g. for cases where you want to test retrying mechanisms.
By default, repeat=False means the response is not repeated (repeat=1 does the same).
Use repeat=n to repeat a response n times.
Use repeat=True to repeat a response indefinitely.
importasyncioimportaiohttpfromaioresponsesimportaioresponses@aioresponses()deftest_multiple_responses(m):
loop=asyncio.get_event_loop()
session=aiohttp.ClientSession()
m.get('http://example.com', status=500, repeat=2)
m.get('http://example.com', status=200) # will take effect after two preceding callsresp1=loop.run_until_complete(session.get('http://example.com'))
resp2=loop.run_until_complete(session.get('http://example.com'))
resp3=loop.run_until_complete(session.get('http://example.com'))
assertresp1.status==500assertresp2.status==500assertresp3.status==200
allows to passthrough to a specified list of servers
importasyncioimportaiohttpfromaioresponsesimportaioresponses@aioresponses(passthrough=['http://backend'])deftest_passthrough(m, test_client):
session=aiohttp.ClientSession()
# this will actually perform a requestresp=loop.run_until_complete(session.get('http://backend/api'))
also you can passthrough all requests except specified by mocking object
importasyncioimportaiohttpfromaioresponsesimportaioresponses@aioresponses(passthrough_unmatched=True)deftest_passthrough_unmatched(m, test_client):
url='https://httpbin.org/get'm.get(url, status=200)
session=aiohttp.ClientSession()
# this will actually perform a requestresp=loop.run_until_complete(session.get('http://backend/api'))
# this will not perform a request and resp2.status will return 200resp2=loop.run_until_complete(session.get(url))
aioresponses allows to throw an exception
importasynciofromaiohttpimportClientSessionfromaiohttp.http_exceptionsimportHttpProcessingErrorfromaioresponsesimportaioresponses@aioresponses()deftest_how_to_throw_an_exception(m, test_client):
loop=asyncio.get_event_loop()
session=ClientSession()
m.get('http://example.com/api', exception=HttpProcessingError('test'))
# calling# loop.run_until_complete(session.get('http://example.com/api'))# will throw an exception.
aioresponses allows to use callbacks to provide dynamic responses