Did you ever get that feeling when a random song pops into your brain and you can’t get rid of it? Well, that happened to me recently and I couldn’t even remember the title of the damn song! In this talk, I want to share with you the story of how I was able to recover the details of the song by navigating some music-related APIs using JavaScript, Node.js and the magic of async iterators!
Finding a lost song with Node.js and async iteratorsLuciano Mammino
Did you ever get that feeling when a random song pops into your brain and you can’t get rid of it? Well, that happened to me recently and I couldn’t even remember the title of the damn song! In this talk, I want to share with you the story of how I was able to recover the details of the song by navigating some music-related APIs using JavaScript, Node.js and the magic of async iterators!
Finding a lost song with Node.js and async iterators - NodeConf Remote 2021Luciano Mammino
Did you ever get that feeling when a random song pops into your brain and you can’t get rid of it? Well, that happened to me recently and I couldn’t even remember the title of the damn song! In this talk, I want to share with you the story of how I was able to recover the details of the song by navigating some music-related APIs using JavaScript, Node.js and the magic of async iterators!
Finding a lost song with Node.js and async iterators - EnterJS 2021Luciano Mammino
The document discusses using the Last.fm API and Node.js async iterators to search a user's listening history when only a fragment of a song title is remembered. It describes making requests to retrieve the user's recent tracks paginated over time windows to avoid duplicate results. Code examples show iterating over the pages as a stream to expose the track data for processing.
This document provides an overview of 0MQ (also known as ZeroMQ), a messaging library that enables various messaging patterns like request/reply, publish/subscribe, and queueing. It includes code examples in multiple languages like Erlang, Python, and PHP demonstrating how to implement common 0MQ patterns. Links are also provided for additional 0MQ resources.
This document provides an overview of 0MQ and examples of how to use it with PHP. It introduces 0MQ patterns like request/response, pub/sub, queue, and pipeline. Code snippets in PHP demonstrate implementing these patterns using 0MQ sockets. Additional resources for learning more about 0MQ and using it with PHP are provided at the end.
This document summarizes a penetration test of the Hack The Box machine OpenAdmin. The writer found that ports 22 and 80 were open. Enumerating port 80 revealed an Apache default page and dirbuster found a page at /ona. This page disclosed an opennetadmin installation vulnerable to RCE. Exploiting this gave a www-data shell. Credentials in a database settings file were used to SSH as user jimmy. Further enumeration revealed an internal site at port 52846 containing Joanna's SSH key, which was extracted using SSH tunneling or curl. John the Ripper cracked the key's passphrase and the writer SSHed as Joanna. Sudo privileges without a password allowed escalating to root using a nano privilege
ZeroMQ Is The Answer: PHP Tek 11 VersionIan Barber
This document provides an overview of ZeroMQ (0MQ), an asynchronous messaging library. It discusses 0MQ concepts like request/response, publish/subscribe, and pipelines. It includes code examples in PHP and Python demonstrating how to implement these patterns using 0MQ sockets and messaging. Additional sections cover 0MQ transport types, installation, and integrating 0MQ with other systems like Mongrel2.
Finding a lost song with Node.js and async iteratorsLuciano Mammino
Did you ever get that feeling when a random song pops into your brain and you can’t get rid of it? Well, that happened to me recently and I couldn’t even remember the title of the damn song! In this talk, I want to share with you the story of how I was able to recover the details of the song by navigating some music-related APIs using JavaScript, Node.js and the magic of async iterators!
Finding a lost song with Node.js and async iterators - NodeConf Remote 2021Luciano Mammino
Did you ever get that feeling when a random song pops into your brain and you can’t get rid of it? Well, that happened to me recently and I couldn’t even remember the title of the damn song! In this talk, I want to share with you the story of how I was able to recover the details of the song by navigating some music-related APIs using JavaScript, Node.js and the magic of async iterators!
Finding a lost song with Node.js and async iterators - EnterJS 2021Luciano Mammino
The document discusses using the Last.fm API and Node.js async iterators to search a user's listening history when only a fragment of a song title is remembered. It describes making requests to retrieve the user's recent tracks paginated over time windows to avoid duplicate results. Code examples show iterating over the pages as a stream to expose the track data for processing.
This document provides an overview of 0MQ (also known as ZeroMQ), a messaging library that enables various messaging patterns like request/reply, publish/subscribe, and queueing. It includes code examples in multiple languages like Erlang, Python, and PHP demonstrating how to implement common 0MQ patterns. Links are also provided for additional 0MQ resources.
This document provides an overview of 0MQ and examples of how to use it with PHP. It introduces 0MQ patterns like request/response, pub/sub, queue, and pipeline. Code snippets in PHP demonstrate implementing these patterns using 0MQ sockets. Additional resources for learning more about 0MQ and using it with PHP are provided at the end.
This document summarizes a penetration test of the Hack The Box machine OpenAdmin. The writer found that ports 22 and 80 were open. Enumerating port 80 revealed an Apache default page and dirbuster found a page at /ona. This page disclosed an opennetadmin installation vulnerable to RCE. Exploiting this gave a www-data shell. Credentials in a database settings file were used to SSH as user jimmy. Further enumeration revealed an internal site at port 52846 containing Joanna's SSH key, which was extracted using SSH tunneling or curl. John the Ripper cracked the key's passphrase and the writer SSHed as Joanna. Sudo privileges without a password allowed escalating to root using a nano privilege
ZeroMQ Is The Answer: PHP Tek 11 VersionIan Barber
This document provides an overview of ZeroMQ (0MQ), an asynchronous messaging library. It discusses 0MQ concepts like request/response, publish/subscribe, and pipelines. It includes code examples in PHP and Python demonstrating how to implement these patterns using 0MQ sockets and messaging. Additional sections cover 0MQ transport types, installation, and integrating 0MQ with other systems like Mongrel2.
Using Mikko Koppanen's PHP ZMQ extension we will look at how you can easily distribute work to background processes, provide flexible service brokering for your next service oriented architecture, and manage caches efficiently and easily with just PHP and the ZeroMQ libraries. Whether the problem is asynchronous communication, message distribution, process management or just about anything, ZeroMQ can help you build an architecture that is more resilient, more scalable and more flexible, without introducing unnecessary overhead or requiring a heavyweight queue manager node.
Asynchronous PHP and Real-time MessagingSteve Rhoades
The document discusses asynchronous programming in PHP using non-blocking I/O and event loops. It covers using asynchronous techniques like ReactPHP to scrape web pages concurrently without blocking. Promises and streams are also discussed as ways to handle asynchronous operations and pass data between components. Finally, messaging techniques like websockets and WAMP are presented as ways to build real-time applications.
Handling input languages like XML, YAML, or JSON is simple enough, just grab your favorite module and hammer it out. But what should one do when facing a more obscure markup language, configuration file or another artifact of a developer with acute NIH syndrome? In this talk we’ll (quickly) revisit formal languages basics and what can and cannot be parsed. We will then introduce parsimonious, a simple, fast, and economic Parsing Expression Grammar parser written by Eric Rose.
The document discusses setting up Python development tools like Python, easy_install, pip, and networkx to collect and analyze Twitter data. It describes retrieving tweets through Twitter's API, analyzing the lexical diversity and frequency of words in tweets, building a retweet graph from tweet data, and visualizing the graph using Graphviz and dot files. The document provides code examples for each step of the process.
Kotlin Coroutines Flow is coming to provide a cold asynchronous data stream that emits values sequentially within a coroutine. Flow allows mapping, filtering, and collecting values, handles exceptions transparently, and preserves context. It can integrate with existing APIs like Room and Retrofit using adapters, and is the primary way to handle async streams going forward. Channels will still be used for hot streams and synchronization between coroutines.
The Art, Joy, and Power of Creating Musical Programs (JFugue at SXSW Interact...David Koelle
This document discusses JFugue, an open source library for programmatically generating music. It provides examples of using JFugue to play simple notes, generate musical patterns and chord progressions, integrate with MIDI systems, and parse musical data into other formats. The document highlights features like JFugue's ease of use, basis in music theory, built-in functions, consistent architecture, and event-based design. It also presents ideas for using JFugue like algorithmic music generation, interactive experiences, and education.
This document discusses Clojure and the architecture used at Nuday Games for their game Rock Science. Key points include:
- Nuday Games uses Clojure for its backend due to benefits like concurrency, small team productivity, and attracting good engineers
- The architecture includes a frontend iOS app, load balancers, HTTP servers running a REST API on Tomcat, and databases
- The REST API is built with Liberator and routes/resources are defined with namespaces, schemas are used for validation
- Events are stored in a DynamoDB table and can be queried to retrieve events by player ID and timestamp
- Mutation commands could be replayed by reading from the event log in
This document introduces John Vlachoyiannis and discusses live programming of music using Clojure. It outlines how Clojure allows music to be treated as data that can be manipulated and transformed in real time. Examples are given showing how to define notes and samples as data, generate patterns, and manipulate those patterns by reversing, randomizing, or applying other transformations to the music structure. Live programming is enabled through use of the REPL and functions like play! that allow musical experiments to be conducted and heard immediately.
Java Streams Interview short reminder with examplesMark Papis
Streams API allows processing sequential and parallel operations on elements of a stream. It provides intermediate operations that are lazy evaluated, and terminal operations that initiate stream processing. Common uses of Streams API include summing values, finding maximum/minimum values, filtering collections, mapping properties, and grouping/counting elements.
Are you interested in TypeScript, but not sure where to start? Like most modern web development, it can feel like there are too many options and no obvious answers.
This talk will share best practices for integrating TypeScript into both Node.js and Webpack+React/JSX workflows, how you can benefit from the features TypeScript offers, and answer common questions about TypeScript.
This document discusses ES6 generators and how they can be used to avoid callback inception. Generators allow functions to pause execution and yield values using the yield keyword. Behind every generator is an iterator object that can be used to control execution. Generators can be iterated over using a for...of loop or by calling next() on the iterator. Examples demonstrate using generators to iterate through fibonacci numbers and to pause asynchronous code using yield instead of callbacks.
This document discusses the CGI.pm module and alternatives. It provides an overview of CGI.pm's capabilities including generating HTML forms and handling GET/POST parameters. It also discusses some issues with CGI.pm including losing access to file handles and incorrect UTF-8 handling. Finally, it shows how to use CGI.pm with different interfaces like mod_perl, FastCGI, POE by setting environment variables and request objects.
OpenSSH is a free software suite that implements secure, remote login and file transfer capabilities using the SSH protocol. It provides a secure replacement for older protocols like telnet, FTP, and rlogin. OpenSSH allows for remote login, file transfer, port forwarding, X11 forwarding, and more. It offers strong security features like public-key authentication and encrypted connections.
The document discusses using WebSockets, Unity3D, and Clojure to build mobile games. It describes how WebSockets enable bidirectional communication between a server and client. It also discusses using Clojure and AWS services like SNS, SQS, and DynamoDB to build a server that can handle real-time events and scale. The server uses HTTP Kit to implement WebSockets and pubsub to distribute messages between clients.
Absolute Beginners Guide to Puppet Through Types - PuppetConf 2014Puppet
This document provides a guide to Puppet through the use of types. It discusses Dijkstra's view on organizing complexity and NOOPing. It then covers differences between the DSL and RAL approaches, defined types, symmetry between resources and types, and implementing types and providers correctly through examples for trafficserver records and git configurations.
With Unicode you can program and accomplish many funny, cool and useful programs and tools as for instance, Abjad Calculator, Bubble Text Generator to write letters in circle, Flip Text Generator to write letters upside down, Google Transliteration to convert English names to Persian/Arabic, etc...
With Unicode you can program and accomplish many funny, cool and useful programs and tools as for instance, Abjad Calculator calculating the numerical value of letters derived from the Arabic alphabet through the use of the Abjad writing system, Bubble Text Generator to write letters in circle, Flip Text Generator to write letters upside down, Google Transliteration to convert English names to Persian/Arabic, etc.
Analyze one year of radio station songs aired with Spark SQL, Spotify, and Da...Paul Leclercq
Paris Spark Meetup - May 2017
Video : https://www.youtube.com/watch?v=w5Zd-1wIJrU
AdHoc analysis of radio stations broadcasts stored in a parquet files with plain SQL, the dataframe API.
The aim was to notice radio stations habits, differences and if radio stations brainwashing is a thing
This talk's Databricks notebook can be found here : https://databricks-prod-cloudfront.cloud.databricks.com/public/4027ec902e239c93eaaa8714f173bcfc/6937750999095841/3645330882010081/6197123402747553/latest.html
Stream Puzzlers – Traps and Pitfalls in Using Java 8 Streams langer4711
How well do you know the Stream-API in Java 8? Do you like brainteasers? Then you are invited to take a look at some short programs involving stream operations whose behavior isn’t obvious at first sight. Can you figure out what it does? Using these puzzlers we will take a closer look at some stream operations’ behavior and will show you how to avoid common traps and pitfalls.
Using Mikko Koppanen's PHP ZMQ extension we will look at how you can easily distribute work to background processes, provide flexible service brokering for your next service oriented architecture, and manage caches efficiently and easily with just PHP and the ZeroMQ libraries. Whether the problem is asynchronous communication, message distribution, process management or just about anything, ZeroMQ can help you build an architecture that is more resilient, more scalable and more flexible, without introducing unnecessary overhead or requiring a heavyweight queue manager node.
Asynchronous PHP and Real-time MessagingSteve Rhoades
The document discusses asynchronous programming in PHP using non-blocking I/O and event loops. It covers using asynchronous techniques like ReactPHP to scrape web pages concurrently without blocking. Promises and streams are also discussed as ways to handle asynchronous operations and pass data between components. Finally, messaging techniques like websockets and WAMP are presented as ways to build real-time applications.
Handling input languages like XML, YAML, or JSON is simple enough, just grab your favorite module and hammer it out. But what should one do when facing a more obscure markup language, configuration file or another artifact of a developer with acute NIH syndrome? In this talk we’ll (quickly) revisit formal languages basics and what can and cannot be parsed. We will then introduce parsimonious, a simple, fast, and economic Parsing Expression Grammar parser written by Eric Rose.
The document discusses setting up Python development tools like Python, easy_install, pip, and networkx to collect and analyze Twitter data. It describes retrieving tweets through Twitter's API, analyzing the lexical diversity and frequency of words in tweets, building a retweet graph from tweet data, and visualizing the graph using Graphviz and dot files. The document provides code examples for each step of the process.
Kotlin Coroutines Flow is coming to provide a cold asynchronous data stream that emits values sequentially within a coroutine. Flow allows mapping, filtering, and collecting values, handles exceptions transparently, and preserves context. It can integrate with existing APIs like Room and Retrofit using adapters, and is the primary way to handle async streams going forward. Channels will still be used for hot streams and synchronization between coroutines.
The Art, Joy, and Power of Creating Musical Programs (JFugue at SXSW Interact...David Koelle
This document discusses JFugue, an open source library for programmatically generating music. It provides examples of using JFugue to play simple notes, generate musical patterns and chord progressions, integrate with MIDI systems, and parse musical data into other formats. The document highlights features like JFugue's ease of use, basis in music theory, built-in functions, consistent architecture, and event-based design. It also presents ideas for using JFugue like algorithmic music generation, interactive experiences, and education.
This document discusses Clojure and the architecture used at Nuday Games for their game Rock Science. Key points include:
- Nuday Games uses Clojure for its backend due to benefits like concurrency, small team productivity, and attracting good engineers
- The architecture includes a frontend iOS app, load balancers, HTTP servers running a REST API on Tomcat, and databases
- The REST API is built with Liberator and routes/resources are defined with namespaces, schemas are used for validation
- Events are stored in a DynamoDB table and can be queried to retrieve events by player ID and timestamp
- Mutation commands could be replayed by reading from the event log in
This document introduces John Vlachoyiannis and discusses live programming of music using Clojure. It outlines how Clojure allows music to be treated as data that can be manipulated and transformed in real time. Examples are given showing how to define notes and samples as data, generate patterns, and manipulate those patterns by reversing, randomizing, or applying other transformations to the music structure. Live programming is enabled through use of the REPL and functions like play! that allow musical experiments to be conducted and heard immediately.
Java Streams Interview short reminder with examplesMark Papis
Streams API allows processing sequential and parallel operations on elements of a stream. It provides intermediate operations that are lazy evaluated, and terminal operations that initiate stream processing. Common uses of Streams API include summing values, finding maximum/minimum values, filtering collections, mapping properties, and grouping/counting elements.
Are you interested in TypeScript, but not sure where to start? Like most modern web development, it can feel like there are too many options and no obvious answers.
This talk will share best practices for integrating TypeScript into both Node.js and Webpack+React/JSX workflows, how you can benefit from the features TypeScript offers, and answer common questions about TypeScript.
This document discusses ES6 generators and how they can be used to avoid callback inception. Generators allow functions to pause execution and yield values using the yield keyword. Behind every generator is an iterator object that can be used to control execution. Generators can be iterated over using a for...of loop or by calling next() on the iterator. Examples demonstrate using generators to iterate through fibonacci numbers and to pause asynchronous code using yield instead of callbacks.
This document discusses the CGI.pm module and alternatives. It provides an overview of CGI.pm's capabilities including generating HTML forms and handling GET/POST parameters. It also discusses some issues with CGI.pm including losing access to file handles and incorrect UTF-8 handling. Finally, it shows how to use CGI.pm with different interfaces like mod_perl, FastCGI, POE by setting environment variables and request objects.
OpenSSH is a free software suite that implements secure, remote login and file transfer capabilities using the SSH protocol. It provides a secure replacement for older protocols like telnet, FTP, and rlogin. OpenSSH allows for remote login, file transfer, port forwarding, X11 forwarding, and more. It offers strong security features like public-key authentication and encrypted connections.
The document discusses using WebSockets, Unity3D, and Clojure to build mobile games. It describes how WebSockets enable bidirectional communication between a server and client. It also discusses using Clojure and AWS services like SNS, SQS, and DynamoDB to build a server that can handle real-time events and scale. The server uses HTTP Kit to implement WebSockets and pubsub to distribute messages between clients.
Absolute Beginners Guide to Puppet Through Types - PuppetConf 2014Puppet
This document provides a guide to Puppet through the use of types. It discusses Dijkstra's view on organizing complexity and NOOPing. It then covers differences between the DSL and RAL approaches, defined types, symmetry between resources and types, and implementing types and providers correctly through examples for trafficserver records and git configurations.
With Unicode you can program and accomplish many funny, cool and useful programs and tools as for instance, Abjad Calculator, Bubble Text Generator to write letters in circle, Flip Text Generator to write letters upside down, Google Transliteration to convert English names to Persian/Arabic, etc...
With Unicode you can program and accomplish many funny, cool and useful programs and tools as for instance, Abjad Calculator calculating the numerical value of letters derived from the Arabic alphabet through the use of the Abjad writing system, Bubble Text Generator to write letters in circle, Flip Text Generator to write letters upside down, Google Transliteration to convert English names to Persian/Arabic, etc.
Analyze one year of radio station songs aired with Spark SQL, Spotify, and Da...Paul Leclercq
Paris Spark Meetup - May 2017
Video : https://www.youtube.com/watch?v=w5Zd-1wIJrU
AdHoc analysis of radio stations broadcasts stored in a parquet files with plain SQL, the dataframe API.
The aim was to notice radio stations habits, differences and if radio stations brainwashing is a thing
This talk's Databricks notebook can be found here : https://databricks-prod-cloudfront.cloud.databricks.com/public/4027ec902e239c93eaaa8714f173bcfc/6937750999095841/3645330882010081/6197123402747553/latest.html
Stream Puzzlers – Traps and Pitfalls in Using Java 8 Streams langer4711
How well do you know the Stream-API in Java 8? Do you like brainteasers? Then you are invited to take a look at some short programs involving stream operations whose behavior isn’t obvious at first sight. Can you figure out what it does? Using these puzzlers we will take a closer look at some stream operations’ behavior and will show you how to avoid common traps and pitfalls.
Amazing SQL your ORM can (or can't) do | PGConf EU 2019 | Louise GrandjoncCitus Data
SQL can seem like an obscure and complex but powerful language. Learning it can be intimidating. As a developer, we can easily be tempted using basic SQL provided by the ORM. But did you know that you can use window functions in some ORMs? Same goes for a lot of other fun SQL functionalities.
In this talk we will explore some advanced SQL features that you might find useful. We will discover the wonderful world of joins (lateral, cross…), subqueries, grouping sets, window functions, common table expressions.
But most importantly this talk is not only a talk to show you how great SQL is. This talk is here to show you how to use it in real life. What are the features supported by your ORM? And how can you use them if they don’t support them?
Wether you know SQL or not, whether you are a developer or a DBA working with developers, you might learn a lot about SQL, ORMs, and application development using Postgres.
1. The document discusses using Kotlin with MicroProfile for building microservices, teaching Kotlin newer techniques from Java and MicroProfile.
2. It provides examples of configuring Kotlin projects using Maven to work with MicroProfile libraries and annotations for dependency injection and JAX-RS.
3. The examples demonstrate a demo project using Kotlin with Jakarta EE and MicroProfile for entities, repositories, and controllers, and deploying the application to Oracle Cloud.
This document discusses creating an Android app using Kotlin. It begins by explaining some of the limitations of using Java for Android development and how Kotlin addresses these issues. It then provides examples of Kotlin code showing functions, variables, parameter defaults, string templates, collections, lambdas, equality checks, destructuring, extension functions, null safety, smart casts, classes, interfaces, data classes, and delegated properties. It concludes by outlining steps for creating an Android app in Kotlin, including configuring the project, converting Java code to Kotlin, and initializing basic app components.
À la découverte des Observables - HumanTalks Paris 2017Nicolas Carlo
The document discusses using Observables to manage asynchronous scenarios in a reactive way. It introduces Observables and RxJS, showing how events can be modeled as Observables streams. Various examples are given of composing Observables using operators like flatMap, filter, and delay to implement features like asynchronous fetching of data on keypress with debouncing and polling for new data. Using Observables results in more declarative, testable code by separating the asynchronous logic from side effects.
Apple's Swift has achieved the top place in Stack Overflow's "Most Loved" list of programming languages in its 2015 Developer Survey. Based on information gleaned from GitHub and Stack Overflow, analyst firm RedMonk has seen Swift's popularity ranking soar from 68 to 22 in an unprecedented 6 months.
The "Extreme Swift" event does not require advanced, or even any, knowledge of Swift. Learn about some of the more outrageous features of the language which help explain what the fuss is all about!
Never look at programming the same way again — even if you never end up writing a single line of Swift code in your life.
This document discusses refactoring Java code to Clojure using macros. It provides examples of refactoring Java code that uses method chaining to equivalent Clojure code using the threading macros (->> and -<>). It also discusses other Clojure features like type hints, the doto macro, and polyglot projects using Leiningen.
The document discusses using the MusicKit API to develop iOS applications that interact with Apple Music. It provides details on authentication, searching the catalog, playback, and interacting with user data like playlists and ratings. Code examples are given for common tasks like authorization, making API requests, and parsing JSON responses.
This document discusses tools and techniques for diagnosing and debugging MongoDB deployments, drawing parallels to Sherlock Holmes' methods of investigation. It provides an overview of OS-level and MongoDB-specific tools for gathering data from logs and systems, including mtools for analyzing MongoDB logs. Examples demonstrate using mloginfo to extract query statistics and mplotqueries to visualize query patterns and collections scanned over time. The document advocates applying Holmes' principles of eliminating factors, balancing probabilities, and using imagination to scientifically analyze data and reveal the truth.
This document discusses data visualization in Python and Django. It introduces common data visualization libraries like Matplotlib. It then covers the steps for gathering and preprocessing data from sources like CSV files and databases. Various types of visual representations are described, and factors for choosing visualizations like whether they are server-based or client-based are addressed. Examples of real-time and batch-based visualization are provided in the appendices along with code samples.
What can be done with Java, but should better be done with Erlang (@pavlobaron)Pavlo Baron
Erlang excels at building distributed, fault-tolerant, concurrent applications due to its lightweight process model and built-in support for distribution. However, Java is more full-featured and is generally a better choice for applications that require more traditional object-oriented capabilities or need to interface with existing Java libraries and frameworks. Both languages have their appropriate uses depending on the requirements of the specific application being developed.
Tuga IT 2018 Summer Edition - The Future of C#Paulo Morgado
This document outlines the agenda for the Tuga IT Summer Edition conference to be held in Lisbon, Portugal from July 19-21, 2018. It thanks sponsors and lists the schedule of speakers including Paulo Morgado who will present on recent and upcoming features in C# like tuples, default literals, and nullable reference types. The document provides links to documentation and proposals for these new language features.
Reactive stream processing using Akka streams Johan Andrén
This document discusses Akka streams and Reactive Streams. It provides an example of creating an Akka streams application that exposes an HTTP service serving an infinite stream of numbers. The example demonstrates how Akka streams provides asynchronous stream processing with back pressure to prevent out of memory errors.
This document discusses developing Android apps with Kotlin. It begins by noting some limitations of Java for Android development and how Kotlin addresses these issues through features like null safety, data classes, extensions, and interoperability with Java. It then provides code examples demonstrating Kotlin's syntax for various language constructs and how they can simplify Android development tasks. Finally, it recommends additional Kotlin resources and libraries that can enhance the Android development experience.
festival ICT 2013: Solid as diamond: use ruby in an web application penetrati...festival ICT 2016
The document discusses using Ruby for web application penetration testing. It begins by introducing the speaker and their background. It then outlines the OWASP Top 10 vulnerabilities it will focus on exploring with Ruby code, including injection, authentication issues, cross-site scripting, and more. The document demonstrates various Ruby gems and techniques for fingerprinting targets, discovering URLs, checking transport security, and searching for vulnerabilities like reflected cross-site scripting. Code examples are provided throughout to demonstrate how Ruby can be leveraged for penetration testing activities.
Writing a REST Interconnection Library in SwiftPablo Villar
The document summarizes Pablo Luciano Villar's presentation on writing a REST interconnection library in Swift. The presentation covered the motivation for such a library, proposed an architectural concept using repositories and backends to abstract network calls, and provided an implementation example in Swift using protocols, generics, enums, and other features. Key aspects included defining a common API for CRUD operations across different entities, handling asynchronous network requests with Futures, and enhancing error handling and data parsing. The full implementation is available as an open source library called Jayme.
The document describes the key abstractions in Akka Streams - Source, Sink, and Flow. It provides examples of creating Sources from single values, iterators, and ticks. It also gives examples of Sinks like foreach, head, fold, and reduce. Various Flow operations are demonstrated like map, filter, take, drop, and flatMapConcat. The document then gives an example problem of reading log files from HDFS in parallel to find 100 fraudulent transactions using Akka Streams.
Similar to Finding a lost song with Node.js and async iterators (20)
Did you know JavaScript has iterators? DublinJSLuciano Mammino
How many ways do you know to do iteration with JavaScript and Node.js? While, for loop, for…in, for..of, .map(), .forEach(), streams, iterators, etc! Yes, there are a lot of ways! But did you know that JavaScript has iteration protocols to standardise synchronous and even asynchronous iteration? In this workshop we will learn about these protocols and discover how to build iterators and iterable objects, both synchronous and asynchronous. We will learn about some common use cases for these protocols, explore generators and async generators (great tools for iteration) and finally discuss some hot tips, common pitfalls, and some (more or less successful) wild ideas!
What I learned by solving 50 Advent of Code challenges in Rust - RustNation U...Luciano Mammino
The document discusses using iterator combinators in Rust to solve an Advent of Code puzzle in a more functional style compared to a classic imperative approach. It shows code to parse input data into batches, map lines to values, sum the values, and take the maximum. It then extends this to sort batches descending and take the top 3 sums to solve part 2 of the puzzle in a flexible way using combinators.
Building an invite-only microsite with Next.js & Airtable - ReactJS MilanoLuciano Mammino
The document outlines steps to build an invite-only website using Next.js and Airtable. It discusses:
1) Organizing guest data like name and favorite color in an Airtable database.
2) Setting up a Next.js project and retrieving invite data from Airtable using its API and creating an Invite interface.
3) Creating a Next.js API to fetch invite data based on an invite code parameter.
A design pattern provides a general reusable solution for the common problems that occur in software design. The pattern typically shows relationships and interactions between classes or objects. The idea is to speed up the development process by providing well-tested, proven development/design paradigms. Design patterns come in three different categories. Creational patterns include the generation of object instances. Structure refers to how an object is made and how things behave and interact In this Webinar(Live Meetup) we will be covering - What is node js - When to use node js - Async I/O operations in node js - Advantages of Async/Await - Some interesting - async patterns - Performance comparison
Let's build a 0-cost invite-only website with Next.js and Airtable!Luciano Mammino
The document describes building an invite-only website using Next.js and Airtable. It outlines:
1) Organizing guest data like names and preferences in an Airtable database.
2) Creating a Next.js project and APIs to retrieve invite data from Airtable by invite code.
3) Authenticating access to Next.js pages by checking for a valid invite code parameter.
Almost every web application at some point needs a way to upload or download files… and no one seems to enjoy building reliable and scalable upload/download servers… and for good reasons too! In fact, you’ll probably need to manage long-running connections and handle files that can be quite large (i.e videos). If you are running a fully serverless backend using API Gateway and Lambda, you probably know that you are limited in terms of payload size and execution time, so things get even more complicated there. In all these cases you should consider offloading this problem to S3 by using S3 pre-signed URLs. Pre-signed URLs are a fantastic tool to handle file download and upload directly in S3 in a managed and scalable fashion. But all that glitters is not gold and S3 pre-signed URLs come with quite a few gotchas… So in this talk, we will explore some use cases, see some potential implementations of S3 pre-signed URLs and uncover some of the gotchas that I discovered while using them. By the end of this talk, you should know exactly when to use pre-signed URLs and how to avoid most of the many mistakes I made with them!
Serverless is great for web applications and APIs, but this does not mean it cannot be used successfully for other use cases. In this talk, we will discuss a successful application of serverless in the field of High Performance Computing. Specifically we will discuss how Lambda, Fargate, Kinesis and other serverless technologies are being used to run sophisticated financial models at one of the major reinsurance companies in the World. We we learn about the architecture, the tradeoffs, some challenges and some unresolved pain points. Most importantly, we'll find out if serverless can be a great fit for HPC and if we can finally stop managing those boring EC2 instances!
Serverless is great for web applications and APIs, but this does not mean it cannot be used successfully for other use cases. In this talk, we will discuss a successful application of serverless in the field of High Performance Computing. Specifically we will discuss how Lambda, Fargate, Kinesis and other serverless technologies are being used to run sophisticated financial models at one of the major reinsurance companies in the World. We we learn about the architecture, the tradeoffs, some challenges and some unresolved pain points. Most importantly, we'll find out if serverless can be a great fit for HPC and if we can finally stop managing those boring EC2 instances!
JavaScript Iteration Protocols - Workshop NodeConf EU 2022Luciano Mammino
The document discusses JavaScript iteration protocols including generators, iterators, iterables, async iterators, and async iterables.
It provides examples of using generator functions to create custom iterables. It explains that generator objects are both iterators and iterables.
The document also explains the iterator and iterable protocols, defining what makes an object an iterator and what makes an object iterable. It shows how to implement these protocols using generator functions, anonymous objects, and classes.
Finally, it covers async iteration protocols, showing how to create async iterators and async iterables, typically using async generator functions. It provides examples of built-in Node.js async iterables like readable streams.
Building an invite-only microsite with Next.js & AirtableLuciano Mammino
Imagine you are hosting a private event and you want to create a website to invite all your guests. Of course you'd like to have an easy way to just share a URL with every guest and they should be able to access all the details of the event. Everyone else should not be allowed to see the page. Even nicer if the website is customized for every guest and if you could use the same website to collect information from the guests (who is coming and who is not). Ok, how do we build all of this? But, most importantly, how do we build it quickly? How do we keep it simple and possibly host it 100% for FREE? I had to do something like this recently so, in this talk, I am going to share my solution, which involves a React SPA (built with Next.js & Vercel) and AirTable as a backend!
How can you take an existing monolith to the cloud with very minimal effort? In this talk we will explore an architecture that can help you to achieve that while focusing on scalability and resilience.
A look inside the European Covid Green Certificate - Rust DublinLuciano Mammino
When I saw how dense the European Covid Green Pass QR code is, I got immediately curious: "WOW, there must be a lot of interesting data in here". So, I started to dig deeper and I found that there's really a great wealth of interesting encoding and verification technologies being used in it! In this talk, I will share what I learned! We will go on a journey where we will explore Base54 encoding, COSE tokens, CBOR serialization, elliptic curve crypto, and much more! Finally, I will also show you how to write a decoder for Green Pass certificates in the most hyped language ever: Rust!
How can you take an existing monolith to the cloud with very minimal effort? In this talk we will explore an architecture that can help you to achieve that while focusing on scalability and resilience.
A presentation by Luciano Mammino(@loige) about what it takes to be recognised as a Senior Software Engineer:
The goal of this slides deck is to:
- Discuss what is expected from a senior software engineer (skills, mindset, duties)
- Packed with opinions (my own and more)
- For devs to be inspired
- For managers to hire, set expectations, support, and evaluate
Node.js: scalability tips - Azure Dev Community VijayawadaLuciano Mammino
You finally built that amazing start-up idea you had in mind for years and you did it using Node.js! That's Great! You just launched it on Hacker News and you are very happy and proud... but now more and more people are using it and you start to have a nasty fear that Node.js won't scale because you now... it's single-threaded! Is your project doomed now? Do you have to invest your time on rewriting it in something like C++ or maybe Rust or even Go? You'd rather invest your time on adding valuable features for your users rather than learning a new language and rewriting everything from scratch, but what if nothing works anymore? And... by the way, what the heck "single-threaded" really means?! Fear no more, dear fellow developer! In this talk, we will discuss the architecture of Node.js going through its strengths and its weaknesses. We will then talk about scalability and I will share some valuable tips and tricks to make your Node.js app scale! Spoiler alert: you probably won't need Go or Rust :)
A look inside the European Covid Green Certificate (Codemotion 2021)Luciano Mammino
When I saw how dense the European Covid Green Pass QR code is, I got immediately curious: "WOW, there must be a lot of interesting data in here". So, I started to dig deeper and I found that there's really a great wealth of interesting encoding and verification technologies being used in it! In this talk, I will share what I learned! We will go on a journey where we will explore Base54 encoding, COSE tokens, CBOR serialization, elliptic curve crypto, and much more! Finally, I will also show you how to write a decoder for Green Pass certificates in the most hyped language ever: Rust!
1. The document discusses observability in AWS and introduces a tool called SLIC Watch that automates the configuration of CloudWatch alarms and dashboards for serverless applications.
2. SLIC Watch generates CloudFormation templates that set up application-specific dashboards and alarms using metrics from services like Lambda, DynamoDB, and API Gateway to help operators more quickly identify issues.
3. The document provides an example of how SLIC Watch could help diagnose issues like DynamoDB throttling and Lambda timeouts by automating the creation of relevant metrics and alarms without requiring manual configuration of CloudWatch.
Semplificare l'observability per progetti ServerlessLuciano Mammino
Hai mai pensato che le tue lambda functions possano fallire senza che tu te ne accorga? Se la risposta é "SI" probabilmente é perché ti sei giá "bruciato" giocando con il cloud, dove errori e fallimenti sono sempre dietro l'angolo. Purtroppo non possiamo prevenire tutti i fallimenti, pero' possiamo essere notificati quando qualcosa va storto cosí da poter reagire tempestivamente. Ma come fare a configurare il nostro ambiente AWS per raggiungere un buon livello di "Observability"? Se hai giá provato ad utilizzare CloudWatch saprai giá quanto possa essere complesso. In questo talk, esploreremo il tema dell'observability per applicazioni Serverless su AWS. Discuteremo problemi e best practices. Infine vi proporró un tool che permette di automatizzare la configurazione di CloudWatch per l'80% delle esigenze in pochi minuti!
Most AWS APIs will have limits on the amount of data you can send in one request and sometimes you really need to send a lot of data! To try to maximise the amount of data you can send, while still staying within the limits, some APIs support sending gzip-compressed payloads. But how can you send a gzipped request when using the Python SDK for AWS (boto3)? Well, I needed to answer this question recently and it turned out not to be as easy as I anticipated… Let’s jump into this rabbit hole together and let’s find out the answer!
Good observability is a must-have for modern AWS applications. CloudWatch gives you the tools but leaves you with a lot of work to do. To accelerate this, we created a serverless plugin to quickly build best practice alarms and dashboards.
Conversational agents, or chatbots, are increasingly used to access all sorts of services using natural language. While open-domain chatbots - like ChatGPT - can converse on any topic, task-oriented chatbots - the focus of this paper - are designed for specific tasks, like booking a flight, obtaining customer support, or setting an appointment. Like any other software, task-oriented chatbots need to be properly tested, usually by defining and executing test scenarios (i.e., sequences of user-chatbot interactions). However, there is currently a lack of methods to quantify the completeness and strength of such test scenarios, which can lead to low-quality tests, and hence to buggy chatbots.
To fill this gap, we propose adapting mutation testing (MuT) for task-oriented chatbots. To this end, we introduce a set of mutation operators that emulate faults in chatbot designs, an architecture that enables MuT on chatbots built using heterogeneous technologies, and a practical realisation as an Eclipse plugin. Moreover, we evaluate the applicability, effectiveness and efficiency of our approach on open-source chatbots, with promising results.
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor IvaniukFwdays
At this talk we will discuss DDoS protection tools and best practices, discuss network architectures and what AWS has to offer. Also, we will look into one of the largest DDoS attacks on Ukrainian infrastructure that happened in February 2022. We'll see, what techniques helped to keep the web resources available for Ukrainians and how AWS improved DDoS protection for all customers based on Ukraine experience
From Natural Language to Structured Solr Queries using LLMsSease
This talk draws on experimentation to enable AI applications with Solr. One important use case is to use AI for better accessibility and discoverability of the data: while User eXperience techniques, lexical search improvements, and data harmonization can take organizations to a good level of accessibility, a structural (or “cognitive” gap) remains between the data user needs and the data producer constraints.
That is where AI – and most importantly, Natural Language Processing and Large Language Model techniques – could make a difference. This natural language, conversational engine could facilitate access and usage of the data leveraging the semantics of any data source.
The objective of the presentation is to propose a technical approach and a way forward to achieve this goal.
The key concept is to enable users to express their search queries in natural language, which the LLM then enriches, interprets, and translates into structured queries based on the Solr index’s metadata.
This approach leverages the LLM’s ability to understand the nuances of natural language and the structure of documents within Apache Solr.
The LLM acts as an intermediary agent, offering a transparent experience to users automatically and potentially uncovering relevant documents that conventional search methods might overlook. The presentation will include the results of this experimental work, lessons learned, best practices, and the scope of future work that should improve the approach and make it production-ready.
Getting the Most Out of ScyllaDB Monitoring: ShareChat's TipsScyllaDB
ScyllaDB monitoring provides a lot of useful information. But sometimes it’s not easy to find the root of the problem if something is wrong or even estimate the remaining capacity by the load on the cluster. This talk shares our team's practical tips on: 1) How to find the root of the problem by metrics if ScyllaDB is slow 2) How to interpret the load and plan capacity for the future 3) Compaction strategies and how to choose the right one 4) Important metrics which aren’t available in the default monitoring setup.
In the realm of cybersecurity, offensive security practices act as a critical shield. By simulating real-world attacks in a controlled environment, these techniques expose vulnerabilities before malicious actors can exploit them. This proactive approach allows manufacturers to identify and fix weaknesses, significantly enhancing system security.
This presentation delves into the development of a system designed to mimic Galileo's Open Service signal using software-defined radio (SDR) technology. We'll begin with a foundational overview of both Global Navigation Satellite Systems (GNSS) and the intricacies of digital signal processing.
The presentation culminates in a live demonstration. We'll showcase the manipulation of Galileo's Open Service pilot signal, simulating an attack on various software and hardware systems. This practical demonstration serves to highlight the potential consequences of unaddressed vulnerabilities, emphasizing the importance of offensive security practices in safeguarding critical infrastructure.
Introducing BoxLang : A new JVM language for productivity and modularity!Ortus Solutions, Corp
Just like life, our code must adapt to the ever changing world we live in. From one day coding for the web, to the next for our tablets or APIs or for running serverless applications. Multi-runtime development is the future of coding, the future is to be dynamic. Let us introduce you to BoxLang.
Dynamic. Modular. Productive.
BoxLang redefines development with its dynamic nature, empowering developers to craft expressive and functional code effortlessly. Its modular architecture prioritizes flexibility, allowing for seamless integration into existing ecosystems.
Interoperability at its Core
With 100% interoperability with Java, BoxLang seamlessly bridges the gap between traditional and modern development paradigms, unlocking new possibilities for innovation and collaboration.
Multi-Runtime
From the tiny 2m operating system binary to running on our pure Java web server, CommandBox, Jakarta EE, AWS Lambda, Microsoft Functions, Web Assembly, Android and more. BoxLang has been designed to enhance and adapt according to it's runnable runtime.
The Fusion of Modernity and Tradition
Experience the fusion of modern features inspired by CFML, Node, Ruby, Kotlin, Java, and Clojure, combined with the familiarity of Java bytecode compilation, making BoxLang a language of choice for forward-thinking developers.
Empowering Transition with Transpiler Support
Transitioning from CFML to BoxLang is seamless with our JIT transpiler, facilitating smooth migration and preserving existing code investments.
Unlocking Creativity with IDE Tools
Unleash your creativity with powerful IDE tools tailored for BoxLang, providing an intuitive development experience and streamlining your workflow. Join us as we embark on a journey to redefine JVM development. Welcome to the era of BoxLang.
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...Jason Yip
The typical problem in product engineering is not bad strategy, so much as “no strategy”. This leads to confusion, lack of motivation, and incoherent action. The next time you look for a strategy and find an empty space, instead of waiting for it to be filled, I will show you how to fill it in yourself. If you’re wrong, it forces a correction. If you’re right, it helps create focus. I’ll share how I’ve approached this in the past, both what works and lessons for what didn’t work so well.
inQuba Webinar Mastering Customer Journey Management with Dr Graham HillLizaNolte
HERE IS YOUR WEBINAR CONTENT! 'Mastering Customer Journey Management with Dr. Graham Hill'. We hope you find the webinar recording both insightful and enjoyable.
In this webinar, we explored essential aspects of Customer Journey Management and personalization. Here’s a summary of the key insights and topics discussed:
Key Takeaways:
Understanding the Customer Journey: Dr. Hill emphasized the importance of mapping and understanding the complete customer journey to identify touchpoints and opportunities for improvement.
Personalization Strategies: We discussed how to leverage data and insights to create personalized experiences that resonate with customers.
Technology Integration: Insights were shared on how inQuba’s advanced technology can streamline customer interactions and drive operational efficiency.
LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...DanBrown980551
This LF Energy webinar took place June 20, 2024. It featured:
-Alex Thornton, LF Energy
-Hallie Cramer, Google
-Daniel Roesler, UtilityAPI
-Henry Richardson, WattTime
In response to the urgency and scale required to effectively address climate change, open source solutions offer significant potential for driving innovation and progress. Currently, there is a growing demand for standardization and interoperability in energy data and modeling. Open source standards and specifications within the energy sector can also alleviate challenges associated with data fragmentation, transparency, and accessibility. At the same time, it is crucial to consider privacy and security concerns throughout the development of open source platforms.
This webinar will delve into the motivations behind establishing LF Energy’s Carbon Data Specification Consortium. It will provide an overview of the draft specifications and the ongoing progress made by the respective working groups.
Three primary specifications will be discussed:
-Discovery and client registration, emphasizing transparent processes and secure and private access
-Customer data, centering around customer tariffs, bills, energy usage, and full consumption disclosure
-Power systems data, focusing on grid data, inclusive of transmission and distribution networks, generation, intergrid power flows, and market settlement data
"Scaling RAG Applications to serve millions of users", Kevin GoedeckeFwdays
How we managed to grow and scale a RAG application from zero to thousands of users in 7 months. Lessons from technical challenges around managing high load for LLMs, RAGs and Vector databases.
GlobalLogic Java Community Webinar #18 “How to Improve Web Application Perfor...GlobalLogic Ukraine
Під час доповіді відповімо на питання, навіщо потрібно підвищувати продуктивність аплікації і які є найефективніші способи для цього. А також поговоримо про те, що таке кеш, які його види бувають та, основне — як знайти performance bottleneck?
Відео та деталі заходу: https://bit.ly/45tILxj
As AI technology is pushing into IT I was wondering myself, as an “infrastructure container kubernetes guy”, how get this fancy AI technology get managed from an infrastructure operational view? Is it possible to apply our lovely cloud native principals as well? What benefit’s both technologies could bring to each other?
Let me take this questions and provide you a short journey through existing deployment models and use cases for AI software. On practical examples, we discuss what cloud/on-premise strategy we may need for applying it to our own infrastructure to get it to work from an enterprise perspective. I want to give an overview about infrastructure requirements and technologies, what could be beneficial or limiting your AI use cases in an enterprise environment. An interactive Demo will give you some insides, what approaches I got already working for real.
Keywords: AI, Containeres, Kubernetes, Cloud Native
Event Link: https://meine.doag.org/events/cloudland/2024/agenda/#agendaId.4211
11. Let me introduce myself first...
I'm Luciano ( 🍕🍝) 👋
Senior Architect @ fourTheorem (Dublin )
9
12. Let me introduce myself first...
I'm Luciano ( 🍕🍝) 👋
Senior Architect @ fourTheorem (Dublin )
nodejsdp.link
Co-Author of Node.js Design Patterns 👉
9
13. Let me introduce myself first...
I'm Luciano ( 🍕🍝) 👋
Senior Architect @ fourTheorem (Dublin )
nodejsdp.link
Co-Author of Node.js Design Patterns 👉
20% eBook discount on Packt
20NODEDUBLIN
9
14. Let me introduce myself first...
I'm Luciano ( 🍕🍝) 👋
Senior Architect @ fourTheorem (Dublin )
nodejsdp.link
Co-Author of Node.js Design Patterns 👉
Connect with me:
(blog)
(twitter)
(github)
loige.co
@loige
lmammino
20% eBook discount on Packt
20NODEDUBLIN
9
15. We are business focused technologists that
deliver.
| |
Accelerated Serverless AI as a Service Platform Modernisation
Do you want to ?
work with us
loige 10
27. loige
Let's give it a shot
curl "http://ws.audioscrobbler.com/2.0/?
method=user.getrecenttracks&user=loige&api_key
=${API_KEY}&format=json" | jq .
19
33. loige
We are getting a "paginated" response
with 50 tracks per page
but there are 51 here! 🤔
23
34. loige
We are getting a "paginated" response
with 50 tracks per page
but there are 51 here! 🤔
(let's ignore this for now...)
23
35. loige
We are getting a "paginated" response
with 50 tracks per page
but there are 51 here! 🤔
How do we fetch the next pages?
(let's ignore this for now...)
23
49. loige
* Note that page size
here is 10 tracks per
page
Every page has a song with undefined time...
This is the song I am currently listening to!
It appears at the top of every page.
29
50. loige
* Note that page size
here is 10 tracks per
page
Sometimes there are duplicated tracks
between pages... 😨
29
63. loige
...*
tracks (newest to oldest)
34
Page1 before t1
(page 1 "to" t1)
t1
* we are done when we get an empty page (or num pages is 1)
64. loige
...*
tracks (newest to oldest)
34
Page1 before t1
(page 1 "to" t1)
t1 t2
* we are done when we get an empty page (or num pages is 1)
65. loige
...*
tracks (newest to oldest)
34
Page1 before t1
(page 1 "to" t1)
t1 t2
before t2
(page 1 "to" t2)
* we are done when we get an empty page (or num pages is 1)
66. let to
while (true) {
const query = querystring.stringify({
method: 'user.getrecenttracks',
user: 'loige',
api_key: process.env.API_KEY,
format: 'json',
limit: '10',
to
})
const url = `https://ws.audioscrobbler.com/2.0/?${query}`
const response = await axios.get(url)
const tracks = response.data.recenttracks.track
console.log(
`--- ↓ page to ${to}`,
`remaining pages: ${response.data.recenttracks['@attr'].totalPages} ---`
)
for (const track of tracks) {
console.log(track.date?.uts, `${track.artist['#text']} - ${track.name}`)
}
if (response.data.recenttracks['@attr'].totalPages <= 1) {
break // it's the last page!
}
const lastTrackInPage = tracks[tracks.length - 1]
to = lastTrackInPage.date.uts
} loige 35
67. let to
while (true) {
const query = querystring.stringify({
method: 'user.getrecenttracks',
user: 'loige',
api_key: process.env.API_KEY,
format: 'json',
limit: '10',
to
})
const url = `https://ws.audioscrobbler.com/2.0/?${query}`
const response = await axios.get(url)
const tracks = response.data.recenttracks.track
console.log(
`--- ↓ page to ${to}`,
`remaining pages: ${response.data.recenttracks['@attr'].totalPages} ---`
)
for (const track of tracks) {
console.log(track.date?.uts, `${track.artist['#text']} - ${track.name}`)
}
if (response.data.recenttracks['@attr'].totalPages <= 1) {
break // it's the last page!
}
const lastTrackInPage = tracks[tracks.length - 1]
to = lastTrackInPage.date.uts
} loige 35
68. let to
while (true) {
const query = querystring.stringify({
method: 'user.getrecenttracks',
user: 'loige',
api_key: process.env.API_KEY,
format: 'json',
limit: '10',
to
})
const url = `https://ws.audioscrobbler.com/2.0/?${query}`
const response = await axios.get(url)
const tracks = response.data.recenttracks.track
console.log(
`--- ↓ page to ${to}`,
`remaining pages: ${response.data.recenttracks['@attr'].totalPages} ---`
)
for (const track of tracks) {
console.log(track.date?.uts, `${track.artist['#text']} - ${track.name}`)
}
if (response.data.recenttracks['@attr'].totalPages <= 1) {
break // it's the last page!
}
const lastTrackInPage = tracks[tracks.length - 1]
to = lastTrackInPage.date.uts
} loige 35
69. let to
while (true) {
const query = querystring.stringify({
method: 'user.getrecenttracks',
user: 'loige',
api_key: process.env.API_KEY,
format: 'json',
limit: '10',
to
})
const url = `https://ws.audioscrobbler.com/2.0/?${query}`
const response = await axios.get(url)
const tracks = response.data.recenttracks.track
console.log(
`--- ↓ page to ${to}`,
`remaining pages: ${response.data.recenttracks['@attr'].totalPages} ---`
)
for (const track of tracks) {
console.log(track.date?.uts, `${track.artist['#text']} - ${track.name}`)
}
if (response.data.recenttracks['@attr'].totalPages <= 1) {
break // it's the last page!
}
const lastTrackInPage = tracks[tracks.length - 1]
to = lastTrackInPage.date.uts
} loige 35
70. let to
while (true) {
const query = querystring.stringify({
method: 'user.getrecenttracks',
user: 'loige',
api_key: process.env.API_KEY,
format: 'json',
limit: '10',
to
})
const url = `https://ws.audioscrobbler.com/2.0/?${query}`
const response = await axios.get(url)
const tracks = response.data.recenttracks.track
console.log(
`--- ↓ page to ${to}`,
`remaining pages: ${response.data.recenttracks['@attr'].totalPages} ---`
)
for (const track of tracks) {
console.log(track.date?.uts, `${track.artist['#text']} - ${track.name}`)
}
if (response.data.recenttracks['@attr'].totalPages <= 1) {
break // it's the last page!
}
const lastTrackInPage = tracks[tracks.length - 1]
to = lastTrackInPage.date.uts
} loige 35
79. const reader = LastFmRecentTracks({
apikey: process.env.API_KEY,
user: 'loige'
})
// ASYNC ITERATORS!
for await (const page of reader) {
/* ... */
}
// ... do more stuff when all the data is consumed
loige 43
80. const reader = LastFmRecentTracks({
apikey: process.env.API_KEY,
user: 'loige'
})
// ASYNC ITERATORS WITH ERROR HANDLING!
try {
for await (const page of reader) {
/* ... */
}
} catch (err) {
// handle errors
}
// ... do more stuff when all the data is consumed loige 44
81. How can we build an async iterator?
🧐
loige 45
82. Meet the iteration protocols!
loige
loige.co/javascript-iterator-patterns
46
83. The iterator protocol
An object is an iterator if it has a next() method.
Every time you call it, it returns an object with
the keys done (boolean) and value.
loige 47
84. function createCountdown (from) {
let nextVal = from
return {
next () {
if (nextVal < 0) {
return { done: true }
}
return {
done: false,
value: nextVal--
}
}
}
} loige 48
85. function createCountdown (from) {
let nextVal = from
return {
next () {
if (nextVal < 0) {
return { done: true }
}
return {
done: false,
value: nextVal--
}
}
}
} loige 48
86. function createCountdown (from) {
let nextVal = from
return {
next () {
if (nextVal < 0) {
return { done: true }
}
return {
done: false,
value: nextVal--
}
}
}
} loige 48
87. function createCountdown (from) {
let nextVal = from
return {
next () {
if (nextVal < 0) {
return { done: true }
}
return {
done: false,
value: nextVal--
}
}
}
} loige 48
88. function createCountdown (from) {
let nextVal = from
return {
next () {
if (nextVal < 0) {
return { done: true }
}
return {
done: false,
value: nextVal--
}
}
}
} loige 48
95. The iterable protocol
An object is iterable if it implements the
@@iterator* method, a zero-argument function
that returns an iterator.
loige
*Symbol.iterator
53
96. function createCountdown (from) {
let nextVal = from
return {
[Symbol.iterator]: () => ({
next () {
if (nextVal < 0) {
return { done: true }
}
return { done: false, value: nextVal-- }
}
})
}
}
loige 54
97. function createCountdown (from) {
let nextVal = from
return {
[Symbol.iterator]: () => ({
next () {
if (nextVal < 0) {
return { done: true }
}
return { done: false, value: nextVal-- }
}
})
}
}
loige 54
98. function createCountdown (from) {
let nextVal = from
return {
[Symbol.iterator]: () => ({
next () {
if (nextVal < 0) {
return { done: true }
}
return { done: false, value: nextVal-- }
}
})
}
}
loige 54
99. function createCountdown (from) {
return {
[Symbol.iterator]: function * () {
for (let i = from; i >= 0; i--) {
yield i
}
}
}
}
loige 55
100. const countdown = createCountdown(3)
for (const value of countdown) {
console.log(value)
}
// 3
// 2
// 1
// 0
loige 56
101. OK. So far this is all synchronous iteration.
What about async? 🙄
loige 57
102. The async iterator protocol
An object is an async iterator if it has a next()
method. Every time you call it, it returns a
promise that resolves to an object with the keys
done (boolean) and value.
loige 58
103. import { setTimeout } from 'timers/promises'
function createAsyncCountdown (from, delay = 1000) {
let nextVal = from
return {
async next () {
await setTimeout(delay)
if (nextVal < 0) {
return { done: true }
}
return { done: false, value: nextVal-- }
}
}
} loige 59
104. import { setTimeout } from 'timers/promises'
function createAsyncCountdown (from, delay = 1000) {
let nextVal = from
return {
async next () {
await setTimeout(delay)
if (nextVal < 0) {
return { done: true }
}
return { done: false, value: nextVal-- }
}
}
} loige 59
105. import { setTimeout } from 'timers/promises'
function createAsyncCountdown (from, delay = 1000) {
let nextVal = from
return {
async next () {
await setTimeout(delay)
if (nextVal < 0) {
return { done: true }
}
return { done: false, value: nextVal-- }
}
}
} loige 59
109. import { setTimeout } from 'timers/promises'
// async generators "produce" async iterators!
async function * createAsyncCountdown (from, delay = 1000) {
for (let i = from; i >= 0; i--) {
await setTimeout(delay)
yield i
}
}
loige 62
110. import { setTimeout } from 'timers/promises'
// async generators "produce" async iterators!
async function * createAsyncCountdown (from, delay = 1000) {
for (let i = from; i >= 0; i--) {
await setTimeout(delay)
yield i
}
}
loige 62
111. import { setTimeout } from 'timers/promises'
// async generators "produce" async iterators!
async function * createAsyncCountdown (from, delay = 1000) {
for (let i = from; i >= 0; i--) {
await setTimeout(delay)
yield i
}
}
loige 62
112. The async iterable protocol
An object is an async iterable if it implements
the @@asyncIterator* method, a zero-argument
function that returns an async iterator.
loige
*Symbol.asyncIterator
63
113. import { setTimeout } from 'timers/promises'
function createAsyncCountdown (from, delay = 1000) {
return {
[Symbol.asyncIterator]: async function * () {
for (let i = from; i >= 0; i--) {
await setTimeout(delay)
yield i
}
}
}
}
loige 64
114. import { setTimeout } from 'timers/promises'
function createAsyncCountdown (from, delay = 1000) {
return {
[Symbol.asyncIterator]: async function * () {
for (let i = from; i >= 0; i--) {
await setTimeout(delay)
yield i
}
}
}
}
loige 64
115. const countdown = createAsyncCountdown(3)
for await (const value of countdown) {
console.log(value)
}
loige 65
116. const countdown = createAsyncCountdown(3)
for await (const value of countdown) {
console.log(value)
}
loige 65
117. Now we know how to make our
LastFmRecentTracks an Async Iterable 🤩
loige 66
118. function createLastFmRecentTracks (apiKey, user) {
return {
[Symbol.asyncIterator]: async function * () {
let to
while (true) {
const query = querystring.stringify({
method: 'user.getrecenttracks',
user,
api_key: apiKey,
format: 'json',
to
})
const url = `https://ws.audioscrobbler.com/2.0/?${query}`
const response = await axios.get(url)
const tracks = response.data.recenttracks.track
yield tracks
if (response.data.recenttracks['@attr'].totalPages <= 1) {
break // it's the last page!
}
const lastTrackInPage = tracks[tracks.length - 1]
to = lastTrackInPage.date.uts
}
}
}
}
loige 67
119. function createLastFmRecentTracks (apiKey, user) {
return {
[Symbol.asyncIterator]: async function * () {
let to
while (true) {
const query = querystring.stringify({
method: 'user.getrecenttracks',
user,
api_key: apiKey,
format: 'json',
to
})
const url = `https://ws.audioscrobbler.com/2.0/?${query}`
const response = await axios.get(url)
const tracks = response.data.recenttracks.track
yield tracks
if (response.data.recenttracks['@attr'].totalPages <= 1) {
break // it's the last page!
}
const lastTrackInPage = tracks[tracks.length - 1]
to = lastTrackInPage.date.uts
}
}
}
}
loige 67
120. function createLastFmRecentTracks (apiKey, user) {
return {
[Symbol.asyncIterator]: async function * () {
let to
while (true) {
const query = querystring.stringify({
method: 'user.getrecenttracks',
user,
api_key: apiKey,
format: 'json',
to
})
const url = `https://ws.audioscrobbler.com/2.0/?${query}`
const response = await axios.get(url)
const tracks = response.data.recenttracks.track
yield tracks
if (response.data.recenttracks['@attr'].totalPages <= 1) {
break // it's the last page!
}
const lastTrackInPage = tracks[tracks.length - 1]
to = lastTrackInPage.date.uts
}
}
}
}
loige 67
121. const recentTracks = createLastFmRecentTracks(
process.env.API_KEY,
'loige'
)
for await (const page of recentTracks) {
console.log(page)
}
loige 68
122. Let's search for all the songs that contain the
word "dark" in their title! 🧐
loige 69
123. async function main () {
const recentTracks = createLastFmRecentTracks(
process.env.API_KEY,
'loige'
)
for await (const page of recentTracks) {
for (const track of page) {
if (track.name.toLowerCase().includes('dark')) {
console.log(`${track.artist['#text']} - ${track.name}`)
}
}
}
}
loige 70
126. For a more serious package that allows you to
fetch data from Last.fm:
loige
npm install scrobbles
72
127. Cover picture by on
Thanks to Jacek Spera, , , ,
for reviews and suggestions.
Rod Long Unsplash
@eoins @pelger @gbinside
@ManuEomm
-
loige.link/async-it loige.link/async-it-code
for await (const _ of createAsyncCountdown(1_000_000)) {
console.log("THANK YOU! 😍")
}
loige
nodejsdp.link
20% eBook discount on Packt
20NODEDUBLIN
73