This document provides an overview of Lua tables and their use as different data structures. It discusses how Lua tables can be used as arrays, hash tables, matrices, linked lists, stacks, queues, sets and more. It covers common table operations like creation, accessing and modifying elements, iterating over elements, and more. The document aims to explain how to adapt Lua tables to represent multiple data structures.
Lua: the world's most infuriating languagejgrahamc
Slides from a talk I gave at the Lua London Meetup on October 17: "When first confronted with Lua an experienced programmer (like me!) finds themselves infuriated by the languages little differences and hopes that can dismiss it as not worth learning :-) Later they find themselves infuriated to learn that they can't dismiss it: Lua is just too fast, too useful and too flexible. This talk will look at my experience of learning Lua and using it to send a high-altitude balloon into the stratosphere and build CloudFlare's new low latency WAF."
Contents:
1. Direct Address Table
2. Hashing
3. Characteristics of a good hash function
4. Collision Resolution using Chaining and Probing
5. Static vs Dynamic Hashing
6. Extendible Hashing
7. B+ tree vs Hashing
THREADED BINARY TREE AND BINARY SEARCH TREESiddhi Shrivas
The document discusses threaded binary trees. It begins by defining a regular binary tree. It then explains that in a threaded binary tree, null pointers are replaced by threads (pointers) to other nodes. Threading rules specify that a null left/right pointer is replaced by a pointer to the inorder predecessor/successor. Boolean fields distinguish threads from links. Non-recursive traversals are possible by following threads. Insertion and deletion of nodes may require updating threads. Threaded binary trees allow efficient non-recursive traversals without a stack.
Jeff Davis
UNIQUE indexes have long held a unique position among constraints: they are the only way to express a constraint that two tuples in a table conflict without resorting to triggers and locks (which severely impact performance). But what if you want to impose the constraint that one person can't be in two places at the same time? In other words, you have a schedule, and you want to be sure that two periods of time for the same person do not overlap. This is nearly impossible to do efficiently with the current version of PostgreSQL -- and most other database systems. I will be presenting Exclusion Constraints, which has been accepted for the next PostgreSQL release, along with the PERIOD data type (available now from PgFoundry). I will show how these can, together, offer a fast, scalable, and highly concurrent solution to a very common business requirement. A business requirement is still a requirement even if your current database system can't do it!
How to Analyze and Tune MySQL Queries for Better Performanceoysteing
The document discusses techniques for optimizing MySQL queries for better performance. It covers topics like cost-based query optimization in MySQL, selecting optimal data access methods like indexes, the join optimizer, subquery optimizations, and tools for monitoring and analyzing queries. The presentation agenda includes introductions to index selection, join optimization, subquery optimizations, ordering and aggregation, and influencing the optimizer. Examples are provided to illustrate index selection, ref access analysis, and the range optimizer.
The document discusses balanced binary search trees, specifically AVL trees. It explains that AVL trees ensure the height of the tree remains O(log N) during insertions and deletions by enforcing that the heights of all nodes' left and right subtrees differ by at most 1. The document outlines the process for inserting and deleting nodes from an AVL tree, which may require rotations to restore balance. Rotations are classified based on the position of inserted/deleted nodes and include left-left, left-right, right-right, and right-left varieties.
The document provides guidelines for optimizing SQL and PL/SQL code for performance. It discusses best practices for using indexes like creating them on frequently queried columns and avoiding functions on indexed columns. Other topics covered include using EXISTS instead of JOINs when possible, avoiding DISTINCT, and placing filters in the WHERE clause instead of HAVING. Modular code design, avoiding negatives and LIKE patterns, and letting the optimizer do its work are also recommended. The goal is to help programmers write efficient code by understanding query execution and tuning techniques.
M|18 Deep Dive: InnoDB Transactions and Write PathsMariaDB plc
The document discusses the write path for transactions in InnoDB from the client connection to physical storage. It compares InnoDB's transaction and storage layers to the OSI model. Key aspects covered include how SQL statements are executed, how rows are locked, written to indexes and undo logs, and how transactions are committed or rolled back. Mini-transactions provide atomic durable changes to multiple pages using write-ahead logging to the redo log.
Lua: the world's most infuriating languagejgrahamc
Slides from a talk I gave at the Lua London Meetup on October 17: "When first confronted with Lua an experienced programmer (like me!) finds themselves infuriated by the languages little differences and hopes that can dismiss it as not worth learning :-) Later they find themselves infuriated to learn that they can't dismiss it: Lua is just too fast, too useful and too flexible. This talk will look at my experience of learning Lua and using it to send a high-altitude balloon into the stratosphere and build CloudFlare's new low latency WAF."
Contents:
1. Direct Address Table
2. Hashing
3. Characteristics of a good hash function
4. Collision Resolution using Chaining and Probing
5. Static vs Dynamic Hashing
6. Extendible Hashing
7. B+ tree vs Hashing
THREADED BINARY TREE AND BINARY SEARCH TREESiddhi Shrivas
The document discusses threaded binary trees. It begins by defining a regular binary tree. It then explains that in a threaded binary tree, null pointers are replaced by threads (pointers) to other nodes. Threading rules specify that a null left/right pointer is replaced by a pointer to the inorder predecessor/successor. Boolean fields distinguish threads from links. Non-recursive traversals are possible by following threads. Insertion and deletion of nodes may require updating threads. Threaded binary trees allow efficient non-recursive traversals without a stack.
Jeff Davis
UNIQUE indexes have long held a unique position among constraints: they are the only way to express a constraint that two tuples in a table conflict without resorting to triggers and locks (which severely impact performance). But what if you want to impose the constraint that one person can't be in two places at the same time? In other words, you have a schedule, and you want to be sure that two periods of time for the same person do not overlap. This is nearly impossible to do efficiently with the current version of PostgreSQL -- and most other database systems. I will be presenting Exclusion Constraints, which has been accepted for the next PostgreSQL release, along with the PERIOD data type (available now from PgFoundry). I will show how these can, together, offer a fast, scalable, and highly concurrent solution to a very common business requirement. A business requirement is still a requirement even if your current database system can't do it!
How to Analyze and Tune MySQL Queries for Better Performanceoysteing
The document discusses techniques for optimizing MySQL queries for better performance. It covers topics like cost-based query optimization in MySQL, selecting optimal data access methods like indexes, the join optimizer, subquery optimizations, and tools for monitoring and analyzing queries. The presentation agenda includes introductions to index selection, join optimization, subquery optimizations, ordering and aggregation, and influencing the optimizer. Examples are provided to illustrate index selection, ref access analysis, and the range optimizer.
The document discusses balanced binary search trees, specifically AVL trees. It explains that AVL trees ensure the height of the tree remains O(log N) during insertions and deletions by enforcing that the heights of all nodes' left and right subtrees differ by at most 1. The document outlines the process for inserting and deleting nodes from an AVL tree, which may require rotations to restore balance. Rotations are classified based on the position of inserted/deleted nodes and include left-left, left-right, right-right, and right-left varieties.
The document provides guidelines for optimizing SQL and PL/SQL code for performance. It discusses best practices for using indexes like creating them on frequently queried columns and avoiding functions on indexed columns. Other topics covered include using EXISTS instead of JOINs when possible, avoiding DISTINCT, and placing filters in the WHERE clause instead of HAVING. Modular code design, avoiding negatives and LIKE patterns, and letting the optimizer do its work are also recommended. The goal is to help programmers write efficient code by understanding query execution and tuning techniques.
M|18 Deep Dive: InnoDB Transactions and Write PathsMariaDB plc
The document discusses the write path for transactions in InnoDB from the client connection to physical storage. It compares InnoDB's transaction and storage layers to the OSI model. Key aspects covered include how SQL statements are executed, how rows are locked, written to indexes and undo logs, and how transactions are committed or rolled back. Mini-transactions provide atomic durable changes to multiple pages using write-ahead logging to the redo log.
This document provides guidance on tuning MySQL for optimal performance. It discusses adjusting various configuration settings related to I/O, memory allocation, query caching, and InnoDB settings. Tuning aspects like I/O, queries, maintenance and configurations are recommended to maximize speed within the constraints of other services. Transaction logs and temporary file storage especially impact performance as heavy consumers of I/O.
An animated explanation of the B+ tree data structure.
Including; B+ tree insertion, deletion, balancing, traversal and breaking and merging of nodes.
Comparative analysis with B-tree.
Properties and applications.
Oracle GoldenGate 18c - REST API ExamplesBobby Curtis
This document provides examples of using RESTful APIs with Oracle GoldenGate 18c. It includes examples of creating, deleting, and listing extracts, replicats, credentials, and distribution paths using cURL commands. It also provides examples of using RESTful APIs within shell scripts to automate administration tasks like adding extracts and replicats.
This document provides an overview and instructions for using Oracle's SQL Fundamentals II course. It discusses copyright and usage restrictions, outlines the course objectives and prerequisites. It also lists additional resources for SQL and describes the HR schema used in examples.
CMSC 56 | Lecture 12: Recursive Definition & Algorithms, and Program Correctnessallyn joy calcaben
This document discusses recursive definitions, algorithms, and program correctness. It provides examples of recursively defining functions and sets using a basis step and recursive step. Examples of recursive algorithms are given for computing factorials and exponentials. The difference between recursion and iteration is explained. Program verification and correctness are defined, and examples are worked through to show initial and final assertions for program segments. The document concludes with an announcement about an upcoming exam.
Fast and Furious: Handling Edge Computing Data With Oracle 19c Fast Ingest an...Jim Czuprynski
The Internet of Things (IoT) has deep use cases - energy grids, communications, policing, security, and manufacturing. I’ll show how to use Oracle 19c’s Fast Ingest and Fast Lookup features to load IoT data from “edge” sources to take immediate advantage of that information in nearly real time.
1. The document discusses AVL trees, which are self-balancing binary search trees. It provides examples of inserting values into an initially empty AVL tree, showing the tree after each insertion and any necessary rotations to maintain balance.
2. Deletion from an AVL tree is more complex than insertion, as it may require rotations at each level to restore balance, with a worst case of log2N rotations. The document outlines the deletion procedure and provides an example requiring multiple rotations.
The Query Optimizer is the “brain” of your Postgres database. It interprets SQL queries and determines the fastest method of execution. Using the EXPLAIN command , this presentation shows how the optimizer interprets queries and determines optimal execution.
This presentation will give you a better understanding of how Postgres optimally executes their queries and what steps you can take to understand and perhaps improve its behavior in your environment.
To listen to the webinar recording, please visit EnterpriseDB.com > Resources > Ondemand Webcasts
If you have any questions please email sales@enterprisedb.com
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAsZohar Elkayam
Oracle Week 2017 slides.
Agenda:
Basics: How and What To Tune?
Using the Automatic Workload Repository (AWR)
Using AWR-Based Tools: ASH, ADDM
Real-Time Database Operation Monitoring (12c)
Identifying Problem SQL Statements
Using SQL Performance Analyzer
Tuning Memory (SGA and PGA)
Parallel Execution and Compression
Oracle Database 12c Performance New Features
Oracle Golden Gate Bidirectional ReplicationArun Sharma
Golden gate bidirectional replication is two-way unidirectional replication. Let us setup bi-directional replication for a single table from source to target.
Full article link is here: https://www.support.dbagenesis.com/post/oracle-golden-gate-bidirectional-replication
The document describes Uber's use of Kafka for reliable messaging. Kafka is used for inter-service messaging, stream processing, database changelog transport, data ingestion, and logging. It provides ordered, partitioned streaming and unordered queueing semantics. The summary describes Uber's consumer wrapper that implements features like acknowledgments, redelivery, delays between retries, dead letter queues, competing consumers, and multi-datacenter failover to support reliable messaging on top of Kafka.
The document discusses MongoDB concepts including:
- MongoDB uses a document-oriented data model with dynamic schemas and supports embedding and linking of related data.
- Replication allows for high availability and data redundancy across multiple nodes.
- Sharding provides horizontal scalability by distributing data across nodes in a cluster.
- MongoDB supports both eventual and immediate consistency models.
An in-depth presentation on the WAND top-k retrieval algorithm for efficiently finding the top-k relevant documents for a given query from the inverted index. Compares performance of WAND with naive solutions.
Tanel Poder - Performance stories from Exadata MigrationsTanel Poder
Tanel Poder has been involved in a number of Exadata migration projects since its introduction, mostly in the area of performance ensurance, troubleshooting and capacity planning.
These slides, originally presented at UKOUG in 2010, cover some of the most interesting challenges, surprises and lessons learnt from planning and executing large Oracle database migrations to Exadata v2 platform.
This material is not just repeating the marketing material or Oracle's official whitepapers.
This document discusses stored procedures and functions in Oracle databases. It covers:
- What procedures and functions are and how they can be created using PL/SQL syntax.
- Parameters for procedures and functions, including IN, OUT, and IN OUT parameter modes.
- Developing procedures and functions, including compiling, storing, and executing them.
- Benefits of using procedures and functions such as improved maintainability and performance.
1) AVL trees are self-balancing binary search trees that maintain an O(log n) search time by ensuring the heights of the two child subtrees differ by at most 1 with rotations after insertions and deletions.
2) The balance factor of a node is defined as the height of its left subtree minus the height of its right subtree, and must be -1, 0, or 1 in an AVL tree.
3) There are four types of rotations (single, double) to rebalance the tree - right-right, left-left, left-right, and right-left - depending on the balance factor violated after an insertion or deletion.
MongoDB is the most famous and loved NoSQL database. It has many features that are easy to handle when compared to conventional RDBMS. These slides contain the basics of MongoDB.
A NULL value in a database represents a field with no value, which is different than a field containing a zero or spaces. To test for NULL values, the IS NULL and IS NOT NULL operators must be used instead of comparison operators. The IS NULL operator selects records where the column is empty/NULL, while IS NOT NULL selects records where the column contains a non-empty value. For example, to find employee names where the salary field is empty, use "SELECT names FROM Employee WHERE Salary IS NULL".
Redis is a key-value store that can be used as a database, cache, or message broker. It supports string, hash, list, set and sorted set data structures. Redis is written in C and works on most POSIX systems. It is single-threaded but can scale horizontally by running multiple Redis instances. Redis can persist data to disk and support master-slave replication. It can be scaled out using sentinel for automatic failover, Twemproxy for data sharding, or Redis Cluster for sharding with automatic failover.
1) The document discusses various issues and developments related to the evolution of web standards including ECMAScript, WebAssembly, and CSS.
2) It outlines goals and features of WebAssembly including being portable, efficient, safe, open, and integrated with the web. The MVP will have functionality similar to asm.js with future additions.
3) The author is available for contact and provides links to documentation on topics discussed in the slides like WebAssembly, PostCSS, and Houdini.
This document provides guidance on tuning MySQL for optimal performance. It discusses adjusting various configuration settings related to I/O, memory allocation, query caching, and InnoDB settings. Tuning aspects like I/O, queries, maintenance and configurations are recommended to maximize speed within the constraints of other services. Transaction logs and temporary file storage especially impact performance as heavy consumers of I/O.
An animated explanation of the B+ tree data structure.
Including; B+ tree insertion, deletion, balancing, traversal and breaking and merging of nodes.
Comparative analysis with B-tree.
Properties and applications.
Oracle GoldenGate 18c - REST API ExamplesBobby Curtis
This document provides examples of using RESTful APIs with Oracle GoldenGate 18c. It includes examples of creating, deleting, and listing extracts, replicats, credentials, and distribution paths using cURL commands. It also provides examples of using RESTful APIs within shell scripts to automate administration tasks like adding extracts and replicats.
This document provides an overview and instructions for using Oracle's SQL Fundamentals II course. It discusses copyright and usage restrictions, outlines the course objectives and prerequisites. It also lists additional resources for SQL and describes the HR schema used in examples.
CMSC 56 | Lecture 12: Recursive Definition & Algorithms, and Program Correctnessallyn joy calcaben
This document discusses recursive definitions, algorithms, and program correctness. It provides examples of recursively defining functions and sets using a basis step and recursive step. Examples of recursive algorithms are given for computing factorials and exponentials. The difference between recursion and iteration is explained. Program verification and correctness are defined, and examples are worked through to show initial and final assertions for program segments. The document concludes with an announcement about an upcoming exam.
Fast and Furious: Handling Edge Computing Data With Oracle 19c Fast Ingest an...Jim Czuprynski
The Internet of Things (IoT) has deep use cases - energy grids, communications, policing, security, and manufacturing. I’ll show how to use Oracle 19c’s Fast Ingest and Fast Lookup features to load IoT data from “edge” sources to take immediate advantage of that information in nearly real time.
1. The document discusses AVL trees, which are self-balancing binary search trees. It provides examples of inserting values into an initially empty AVL tree, showing the tree after each insertion and any necessary rotations to maintain balance.
2. Deletion from an AVL tree is more complex than insertion, as it may require rotations at each level to restore balance, with a worst case of log2N rotations. The document outlines the deletion procedure and provides an example requiring multiple rotations.
The Query Optimizer is the “brain” of your Postgres database. It interprets SQL queries and determines the fastest method of execution. Using the EXPLAIN command , this presentation shows how the optimizer interprets queries and determines optimal execution.
This presentation will give you a better understanding of how Postgres optimally executes their queries and what steps you can take to understand and perhaps improve its behavior in your environment.
To listen to the webinar recording, please visit EnterpriseDB.com > Resources > Ondemand Webcasts
If you have any questions please email sales@enterprisedb.com
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAsZohar Elkayam
Oracle Week 2017 slides.
Agenda:
Basics: How and What To Tune?
Using the Automatic Workload Repository (AWR)
Using AWR-Based Tools: ASH, ADDM
Real-Time Database Operation Monitoring (12c)
Identifying Problem SQL Statements
Using SQL Performance Analyzer
Tuning Memory (SGA and PGA)
Parallel Execution and Compression
Oracle Database 12c Performance New Features
Oracle Golden Gate Bidirectional ReplicationArun Sharma
Golden gate bidirectional replication is two-way unidirectional replication. Let us setup bi-directional replication for a single table from source to target.
Full article link is here: https://www.support.dbagenesis.com/post/oracle-golden-gate-bidirectional-replication
The document describes Uber's use of Kafka for reliable messaging. Kafka is used for inter-service messaging, stream processing, database changelog transport, data ingestion, and logging. It provides ordered, partitioned streaming and unordered queueing semantics. The summary describes Uber's consumer wrapper that implements features like acknowledgments, redelivery, delays between retries, dead letter queues, competing consumers, and multi-datacenter failover to support reliable messaging on top of Kafka.
The document discusses MongoDB concepts including:
- MongoDB uses a document-oriented data model with dynamic schemas and supports embedding and linking of related data.
- Replication allows for high availability and data redundancy across multiple nodes.
- Sharding provides horizontal scalability by distributing data across nodes in a cluster.
- MongoDB supports both eventual and immediate consistency models.
An in-depth presentation on the WAND top-k retrieval algorithm for efficiently finding the top-k relevant documents for a given query from the inverted index. Compares performance of WAND with naive solutions.
Tanel Poder - Performance stories from Exadata MigrationsTanel Poder
Tanel Poder has been involved in a number of Exadata migration projects since its introduction, mostly in the area of performance ensurance, troubleshooting and capacity planning.
These slides, originally presented at UKOUG in 2010, cover some of the most interesting challenges, surprises and lessons learnt from planning and executing large Oracle database migrations to Exadata v2 platform.
This material is not just repeating the marketing material or Oracle's official whitepapers.
This document discusses stored procedures and functions in Oracle databases. It covers:
- What procedures and functions are and how they can be created using PL/SQL syntax.
- Parameters for procedures and functions, including IN, OUT, and IN OUT parameter modes.
- Developing procedures and functions, including compiling, storing, and executing them.
- Benefits of using procedures and functions such as improved maintainability and performance.
1) AVL trees are self-balancing binary search trees that maintain an O(log n) search time by ensuring the heights of the two child subtrees differ by at most 1 with rotations after insertions and deletions.
2) The balance factor of a node is defined as the height of its left subtree minus the height of its right subtree, and must be -1, 0, or 1 in an AVL tree.
3) There are four types of rotations (single, double) to rebalance the tree - right-right, left-left, left-right, and right-left - depending on the balance factor violated after an insertion or deletion.
MongoDB is the most famous and loved NoSQL database. It has many features that are easy to handle when compared to conventional RDBMS. These slides contain the basics of MongoDB.
A NULL value in a database represents a field with no value, which is different than a field containing a zero or spaces. To test for NULL values, the IS NULL and IS NOT NULL operators must be used instead of comparison operators. The IS NULL operator selects records where the column is empty/NULL, while IS NOT NULL selects records where the column contains a non-empty value. For example, to find employee names where the salary field is empty, use "SELECT names FROM Employee WHERE Salary IS NULL".
Redis is a key-value store that can be used as a database, cache, or message broker. It supports string, hash, list, set and sorted set data structures. Redis is written in C and works on most POSIX systems. It is single-threaded but can scale horizontally by running multiple Redis instances. Redis can persist data to disk and support master-slave replication. It can be scaled out using sentinel for automatic failover, Twemproxy for data sharding, or Redis Cluster for sharding with automatic failover.
1) The document discusses various issues and developments related to the evolution of web standards including ECMAScript, WebAssembly, and CSS.
2) It outlines goals and features of WebAssembly including being portable, efficient, safe, open, and integrated with the web. The MVP will have functionality similar to asm.js with future additions.
3) The author is available for contact and provides links to documentation on topics discussed in the slides like WebAssembly, PostCSS, and Houdini.
Lua is a lightweight scripting language embedded in many applications like Wireshark and Redis. It is small but powerful, with features like closures, coroutines, and metatables. Lua is embedded via its C API and allows for extending applications with modules written in Lua. Popular modules include LuaSocket and LuaSQL. Lua sees widespread use due to its small size, speed, portability, and ability to extend large C/C++ applications with scripting.
Web development with Lua and Sailor @ GeeCon 2015Etiene Dalcol
Lua is a very fast and powerful scripting language that can be easily embeddable. It can be used to develop robust applications and has been shining in industries like game development, for example. Lua is also an excellent tool as a general purpose language. However, it's use in web development, despite its great potential and incredible benchmarks, needs to be more widespread. Having had experience as a web programmer, and aiming to learn more about this language, I started a marathon that produced Sailor 0.1, a web MVC framework completely written in Lua after only ten days. Once the quest was completed, the feedback was so interesting that I continued the development. Sailor keeps growing each day, also with the help of contributors. This talk presents the beginnings of Sailor framework, a comparison with other existing tools in Lua, the current stage of Sailor's development today, the official announcement of version 0.3 (Jupiter). This presentation also intends to start a debate on what we can do to spread the idea of using more Lua in web development.
Get started with Lua - Hackference 2016Etiene Dalcol
Lua is a very fast, elegant and powerful dynamic language. It’s an excellent tool for robust applications or slim embedded systems. It found a niche in game development with big names such as “Grim Fandango”, “World of Warcraft” and “Angry Birds”. This talk will present what makes Lua different from other interpreted languages, the evolution of the Lua ecosystem, some key concepts of the language, and show you why Lua is the next language to add to your skill set.
Lua as a business logic language in high load applicationIlya Martynov
This report covers our experience building custom HTTP web server used for the delivery of internet advertising. The application design has as one goals finding the right balance between high performance and ease of development. To achieve this goal we are using Lua as a business logic scripting language embedded into C++ application. The report tries to explain how and why we use Lua and how the choice of Lua affects architecture of the application.
Lua is a lightweight scripting language that is easily embeddable. It incorporates many innovations from other languages like Python and Ruby. The document discusses Lua's core concepts including data types, tables, functions, environments, object orientation, and the C API. It provides code examples to demonstrate Lua's features like iterators, coroutines, metatables, and using Lua to configure applications by loading rules from a file.
Session 10 in module 3 from the Master in Computer Vision by UPC, UAB, UOC & UPF.
This lecture provides an overview of state of the art applications of convolutional neural networks to the problems in video processing: semantic recognition, optical flow estimation and object tracking.
Script up your application with Lua! -- RyanE -- OpenWest 2014ryanerickson
Lua is a lightweight scripting language embedded in many applications and games to provide flexibility. It was created in 1993 and focuses on simplicity, portability, and being easily embedded in other applications. Lua runs faster than other dynamic languages like Python and Ruby. It is used extensively in games and by companies like Adobe, and was the first interpreted language allowed on iOS. Lua code runs safely sandboxed, and the host application controls exposed modules. Control4 embedded Lua in its C++ drivers to allow dynamic XML configuration. Lua has few types and is dynamically typed with tables serving as arrays/hashes. Functions are first-class objects and control structures include if/else, while, repeat/until, and for
The document provides an overview of the GNU Debugger (GDB). It lists common GDB commands for debugging programs like breakpoints, watching variables, backtracing functions, and examining runtime behavior. Additional debugger tools are also mentioned like gdbtui, Xcode, and Emacs plugins that build on GDB. The document ends with references to online resources for learning more about using GDB and debugging with it.
This document provides a tutorial on using the GNU Debugger (GDB) to debug C and C++ programs. It discusses starting GDB, loading programs into it, setting breakpoints to pause execution, single-stepping or continuing execution, and querying values of variables. It also covers conditional breakpoints, using GDB with pointers and data structures, and other useful commands like backtrace and watchpoints. The goal is to demonstrate how GDB can be used to inspect program execution and help debug issues like segmentation faults.
Jeff Johnson, Research Engineer, Facebook at MLconf NYCMLconf
Hacking GPUs for Deep Learning: GPUs have revolutionized machine learning in recent years, and have made both massive and deep multi-layer neural networks feasible. However, misunderstandings on why they seem to be winning persist. Many of deep learning’s workloads are in fact “too small” for GPUs, and require significantly different approaches to take full advantage of their power. There are many differences between traditional high-performance computing workloads, long the domain of GPUs, and those used in deep learning. This talk will cover these issues by looking into various quirks of GPUs, how they are exploited (or not) in current model architectures, and how Facebook AI Research is approaching deep learning programming through our recent work.
This document discusses using GDB to relearn C programming. It provides background on using GDB to debug a simple embedded Ajax system called eServ. Key steps outlined include downloading and compiling eServ, using basic GDB commands like run, break, list, and next to observe the program's execution and set breakpoints. The goal is to analyze the system and gain skills in UNIX system programming development.
This document discusses using NGINX with embedded Lua scripting via OpenResty. Lua is a lightweight scripting language used in many applications and games. OpenResty bundles NGINX with LuaJIT and modules to allow full control over every stage of request processing with non-blocking Lua scripts. Examples show how to build a REST API for user scores with Redis using Lua scripts to handle data retrieval, modification and aggregation directly from NGINX.
Soumith Chintala, Artificial Intelligence Research Engineer, Facebook at MLco...MLconf
Predicting the Future Using Deep Adversarial Networks: Learning With No Labeled Data: Labeling data to solve a certain task can be expensive, slow and does not scale. If unsupervised learning works, then one can have very little labelled data to help a machine solve a particular task. Most traditional unsupervised learning methods such as PCA and K-means clustering do not work well for complicated data distributions, making them useless for a lot of tasks. In this talk, I’ll go over recent advances in a technique for unsupervised learning called Generative Adversarial networks, which can learn to generate very complicated data distributions such as images and videos. These trained adversarial networks are then used to solve new tasks with very little labeled data, making them an attractive class of algorithms for many domains where there is limited labeled data but unlimited unlabeled data.
This document provides information about data structures in Python. It discusses lists, tuples, sets, and dictionaries. For lists and tuples, it covers defining, indexing, slicing, unpacking, methods, built-in functions, and list comprehensions. Lists can contain heterogeneous elements and support methods like append(), pop(), sort(), and reverse(). Tuples are similar to lists but are immutable ordered sequences. They also support indexing, slicing, and unpacking. This document serves as a guide to working with common Python data structures.
This document summarizes tuples and dictionaries in Python. Tuples are immutable sequences that are defined using round brackets. They can contain heterogeneous elements and support operations like indexing, slicing, and iteration. Dictionaries allow storing elements with non-integer keys and accessing them via indexing. They are mutable and support operations like adding/deleting elements and various functions. The next lecture will involve practicing with tuples and dictionaries.
Lists, tuples, and dictionaries are common data structures in Python. Lists are mutable sequences that are defined using square brackets. Tuples are immutable sequences defined using parentheses. Dictionaries store key-value pairs within curly braces, with unique keys. These data structures support operations like indexing, slicing, length checking, membership testing, and iteration.
This document discusses tuples and dictionaries in Python. Tuples are immutable sequences that are defined using parentheses, while dictionaries are mutable mappings that associate keys with values. The document provides examples of creating, accessing, iterating over, and modifying tuples and dictionaries using various built-in functions and methods. It also compares the differences between tuples, lists, and dictionaries.
This document discusses representations of sparse matrices using linked lists. It explains that sparse matrices, which contain mostly zero values, can be stored more efficiently using a triplet representation or linked representation rather than a standard 2D array. The triplet representation stores only the non-zero elements, their row and column indices, and matrix size information. It provides an example of a 4x5 sparse matrix represented as a triplet array with 6 non-zero elements. Linked representation stores the sparse matrix as a linked list, where each node contains the row, column and value of a non-zero element. Applications of sparse matrix representations include storing large sparse datasets efficiently.
The document provides information about the course GE3151 Problem Solving and Python Programming. It includes the objectives of the course, which are to understand algorithmic problem solving and learn to solve problems using Python constructs like conditionals, loops, functions, and data structures. It also outlines the 5 units that will be covered in the course, which include computational thinking, Python basics, control flow and functions, lists/tuples/dictionaries, and files/modules. Example problems and programs are provided for different sorting algorithms, quadratic equations, and list operations.
This document discusses tuples in Python. Some key points:
1. Tuples are immutable sequences that are similar to lists but defined using parentheses. They can contain heterogeneous elements and support indexing, slicing, and repetition operations.
2. Tuples can be created using parentheses or the tuple() function. They cannot be modified once created.
3. Common tuple operations include accessing elements, mathematical operations, sorting, and using tuples as dictionary keys due to their immutability.
4. The differences between tuples and lists are that tuples are immutable while lists are mutable, tuples use parentheses and lists use brackets, and tuples can be used as dictionary keys while lists cannot.
5. Tuples can be
The document discusses container data types in Python, including lists, tuples, sets, and dictionaries.
Lists allow indexing, slicing, and various methods like append(), insert(), pop(), and sort(). Tuples are like lists but immutable, and have methods like count(), index(), and tuple comprehension. Sets store unique elements and support operations like union and intersection. Dictionaries map keys to values and allow accessing elements via keys along with functions like get() and update().
This document discusses functional programming concepts like map, reduce, and filter and provides Swift code examples for applying these concepts. It begins with an introduction to functional programming and key concepts. It then covers Swift basics like function types and passing functions. The bulk of the document explains and demonstrates map, reduce, filter and their uses on arrays and optionals in Swift. It concludes with suggestions for further functional programming topics and resources.
Python tutorial notes for all the beginners. It is covered with core topics in python with example programs. It is useful for all types of students (school, college (lower and higher level)) and also for teachers, lecturers, assistant professors, and professors.
Please help solve this in C++ So the program is working fin.pdfankit11134
Please help solve this in C++. So the program is working fine but when submitting it, it gives me a
code -11, and I believe the problem is that after inserting the numbers it removes them one by one
until the last in the list, and when it tries to remove the last number in the list that is when it
counters the problem. Below is the full code but you just need to change something in the
SortedNumberList.h file under the bool remove function.
4.18 LAB: Sorted number list implementation with linked lists Step 1: Inspect the Node.h file
Inspect the class declaration for a doubly-linked list node in Node.h. Access Node.h by clicking on
the orange arrow next to main.cpp at the top of the coding window. The Node class has three
member variables: - a double data value, - a pointer to the next node, and - a pointer to the
previous node. Each member variable is protected. So code outside of the class must use the
provided getter and setter member functions to get or set a member variable. Node.h is read only,
since no changes are required. Step 2: Implement the Insert() member function A class for a
sorted, doubly-linked list is declared in SortedNumberList.h. Implement the SortedNumberList
class's Insert() member function. The function must create a new node with the parameter value,
then insert the node into the proper sorted position in the linked list. Ex: Suppose a
SortedNumberList's current list is 2347.2586, then Insert(33.5) is called. A new node with data
value 33.5 is created and inserted between 23 and 47.25, thus preserving the list's sorted order
and yielding: 2335.547.2586Step 3: Test in develop mode Code in main() takes a space-
separated list of numbers and inserts each into a SortedNumberList. The list is displayed after
each insertion. Ex: If input is 77154263.5 then output is: List after inserting 77 : 77 List after
inserting 15 : 1577 List after inserting -42 : -421577 List after inserting 63.5: -421563.577 Try
various program inputs, ensuring that each outputs a sorted list. Step 4: Implement the Remove()
member function Implement the SortedNumberList class's Remove(0 member function. The
function takes a parameter for the number to be removed from the list. If the number does not
exist in the list, the list is not changed and false is returned. Otherwise, the first instance of the
number is removed from the list and true is returned. Uncomment the commented-out part in
main() that reads a second input line and removes numbers from the list. Test in develop mode to
ensure that insertion and removal both work properly, then submit code for grading. Ex: If input is
841972841961 then output is: List after inserting 84: 84 List after inserting 72 : 7284 List after
inserting 19: 1972 84 List after inserting 61: 1961 : 72 8 List after removing 19: 6172 84 List after
removing 84: 6172Current file: main.cpp - // Insert each value and show the sorted List's contents
after each insertion sortedNumberList list; for (auto term : terms) { doubl.
in C++ , Design a linked list class named IntegerList to hold a seri.pdfeyewaregallery
in C++ , Design a linked list class named IntegerList to hold a series of integers. The class must
have public member functions for appending , inserting, deleting and displaying nodes. The
append function must append a node to the end of the list. The insert function must insert node in
ascending order. The delete function must delete the node with the given value. The display
function should display the list from head to tail. The IntegerList class should also have a
destructor that destroys the list and release memory. The list node must be declared as a structure
using keyword struct. This structure is a private member of IntegerList. You should also store the
head of the list as a private member.
Write a test program to test the implementation your IntegerList class works properly.
Solution
Here is the code for the above scenario:
#include
using namespace std;
struct ListNode
{
float value;
ListNode *next;
};
ListNode *head;
class LinkedList
{
public:
int insertNode(float num);
int appendNode(float num);
void deleteNode(float num);
void destroyList();
void displayList();
LinkedList(void) {head = NULL;}
~LinkedList(void) {destroyList();}
};
int LinkedList::appendNode(float num)
{
ListNode *newNode, *nodePtr = head;
newNode = new ListNode;
if(newNode == NULL)
{
cout << \"Error allocating memory for new list member!\ \";
return 1;
}
newNode->value = num;
newNode->next = NULL;
if(head == NULL)
{
cout << \"List was empty - \" << newNode->value;
cout << \" is part of list\'s first node.\ \";
head = newNode;
}
else
{
while(nodePtr->next != NULL)
nodePtr = nodePtr->next;
nodePtr->next = newNode;
}
return 0;
}
int LinkedList::insertNode(float num)
{
struct ListNode *newNode, *nodePtr = head, *prevNodePtr = NULL;
newNode = new ListNode;
if(newNode == NULL)
{
cout << \"Error allocating memory for new list member!\ \";
return 1;
}
newNode->value = num;
newNode->next = NULL;
if(head==NULL) {
cout << \"List was empty - \" << newNode->value;
cout << \" is part of list\'s first node.\ \";
head = newNode;
}
else
{
while((nodePtr != NULL) && (nodePtr->value < num)) {
prevNodePtr = nodePtr;
nodePtr = nodePtr->next;
}
if(prevNodePtr==NULL)
newNode->next = head;
else
newNode->next = nodePtr; prevNodePtr->next = newNode;
}
return 0;
}
void LinkedList::deleteNode(float num)
{
struct ListNode *nodePtr = head, *prevNodePtr = NULL;
if(head==NULL) {
cout << \"The list was empty!\ \";
return;
}
if(head->value == num) {
head = nodePtr->next;
delete [] nodePtr;
}
else
{
while((nodePtr!= NULL)&&(nodePtr->value != num)) {
prevNodePtr = nodePtr;
nodePtr = nodePtr->next;
}
if(nodePtr==NULL)
cout << \"The value \" << num << \" is not in this list!\ \";
else {
prevNodePtr->next = nodePtr->next;
delete [] nodePtr;
}
}
}
void LinkedList::destroyList()
{
struct ListNode *nodePtr = head, *nextNode = nodePtr;
if(head==NULL) {
cout << \"The list is empty!\ \";
return;
}
while (nodePtr != NULL) {
nextNode = nodePtr->next;
delete [] nodePtr;
nodePtr = nextNode;
}
}
void LinkedList.
Tuple assignment allows multiple variables to be assigned values from an iterable like a list or tuple in a single statement. This is more concise than separate assignments and avoids using a temporary variable. For example, to swap the values of variables a and b, tuple assignment can be used: a, b = b, a. The left side must contain the same number of variables as there are elements on the right, and each value is assigned to the corresponding variable from left to right. Tuple assignment is useful for unpacking elements like splitting a string into parts.
This document provides an overview of lists and tuples in Python. It discusses how to create, access, modify, and iterate over lists and tuples. Some key points covered include:
- Lists are mutable sequences that can contain elements of different types. Common list methods allow appending, inserting, removing, and sorting elements.
- Tuples are immutable lists that cannot be modified after creation. They provide count and index methods similar to lists.
- Lists and tuples can be nested to represent multi-dimensional data structures. Iteration over nested lists/tuples requires multiple for loops.
- Examples demonstrate common list/tuple operations like slicing, concatenation, membership testing, and traversing 2D lists to represent matrices for
This document provides an overview of lists in Python. It defines what a list is, how to create and access list elements, and common list operations like slicing, concatenation, and modification. It also covers list methods such as append(), insert(), remove(), and sort(). The document discusses lists as mutable objects and the concepts of aliasing and passing lists to functions.
This document discusses different abstract data types (ADTs) including lists, stacks, and queues. It provides details on the operations and implementations of each:
- The List ADT can be implemented using arrays or linked lists. Common list operations like insertion and deletion have linear runtime for arrays but constant time for linked lists.
- A stack is a restricted list that only allows insertions and deletions at one end, following the last-in first-out (LIFO) principle. Stacks are often used for function calls and in operating systems.
- A queue is a list with first-in first-out (FIFO) restrictions, commonly used in operating systems and algorithms for organizing access to shared
The Ring programming language version 1.7 book - Part 26 of 196Mahmoud Samir Fayed
Ring provides several functions for manipulating strings. Strings can be accessed like lists, with individual characters retrieved using indexes. Functions like len(), lower(), upper(), left(), right(), and trim() allow manipulating case and extracting substrings. Strings can be compared using strcmp() and converted to and from lists with str2list() and list2str(). Substr() supports finding, extracting, and replacing substrings.
template ltclass Tgt struct nodeType T data n.pdfaceautomate
template <class T>
struct nodeType
{
T data;
nodeType *next;
};
template <class T>
class LinkedList {
nodeType<T> *head, *tail;
int count;
public:
LinkedList();
void insertFirst(T item);
void insertLast(T item);
void insertAt(T item, int pos);
void print();
bool simplecompare(LinkedList<T> &rL)
{
if (count != rL.count)
return false;
nodeType<T> *cur, *rCur;
for (cur = head, rCur = rL.head; cur != NULL; cur = cur->next, rCur = rCur->next)
if (cur->data != rCur->data)
return false;
return true;
}
int compare(LinkedList<T> &rL);
~LinkedList();
};
//driver program:
int main(void)
{
char item;
LinkedList<char> list1, list2;
cout << "Please enter the first list of characters"
<< "nPress Ctrl+Z to stop entering." << endl;
cin >> item;
while (!cin.eof()) {
list1.insertLast(item);
cin >> item;
}
cin.clear();
cout << "Please enter the second list of characters"
<< "nPress Ctrl+Z to stop entering." << endl;
cin >> item;
while (!cin.eof()) {
list2.insertLast(item);
cin >> item;
}
list1.print();
list2.print();
int result = list1.compare(list2);
if (result == 0)
cout << "The lists are same!n";
else if (result == -1)
cout << "first list < second listn" << endl;
else cout << "first list > second listn" << endl;
return 0;
}
1 Questions A simplified doublyLinkedList class is provided in lab03doublyLinkedList_template.h
file on CATS. Solve the following questions by using that elass. 1. The definition of insertFirst(T
item) function is missing. Complete it. 2. The definition of insertLast(T item) function is missing.
Complete it. 3. The definition of insertAt(T item, int order) function is missing. Complete it. 4.
Update print() function to print the list in forward direction. 5. The definition of deleteItem(T item)
function is missing. Complete it. 6. Add an extractMax(T max) function to the doublyLinkedList
class. The function must extract all nodes containing elements less than max from the list, and
construct a new list using those nodes. After the function call, the original list must only have the
nodes whose data fields are greater than max, while the new list is containing the smaller ones.
The new list must be returned by the function. You're not allowed to delete and/or create new
nodes. Your function must just move the subjected nodes from one list to the other. Let the
following list be the original list: If the function is called as newList = myList.extractMax (30), then
the newList becomes: 2 Assignment Implement a class to represent a circular linked list. You can
directly adapt SinglyLinkedList class that we've already defined in linkedList.h. Only the following
member functions will be defined for the class: - default constructor to set the pointer data
members to NULL and count to 0 . - insertItem to insert a given item to the list. - deleteItem to
remove a specific item from the list. Item may occur multiple times, thus the function must remove
every occurrences of the item from the list. 1 - print to print the linked list from head to tail. .
The document discusses different data structures and their implementations and applications. It covers arrays, linked lists, stacks, queues, binary trees, and binary search. The key points are:
- Arrays allow fast access but have fixed size; linked lists can grow dynamically but access is slower.
- Binary trees allow fast (O(log n)) search, insertion, and deletion operations due to their hierarchical structure.
- Stacks and queues are useful for modeling LIFO and FIFO data access with applications like function calls and job scheduling.
- Binary search runs in O(log n) time by recursively dividing the search space for sorted data.
Similar to The basics and design of lua table (20)
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!SOFTTECHHUB
As the digital landscape continually evolves, operating systems play a critical role in shaping user experiences and productivity. The launch of Nitrux Linux 3.5.0 marks a significant milestone, offering a robust alternative to traditional systems such as Windows 11. This article delves into the essence of Nitrux Linux 3.5.0, exploring its unique features, advantages, and how it stands as a compelling choice for both casual users and tech enthusiasts.
Pushing the limits of ePRTC: 100ns holdover for 100 daysAdtran
At WSTS 2024, Alon Stern explored the topic of parametric holdover and explained how recent research findings can be implemented in real-world PNT networks to achieve 100 nanoseconds of accuracy for up to 100 days.
In his public lecture, Christian Timmerer provides insights into the fascinating history of video streaming, starting from its humble beginnings before YouTube to the groundbreaking technologies that now dominate platforms like Netflix and ORF ON. Timmerer also presents provocative contributions of his own that have significantly influenced the industry. He concludes by looking at future challenges and invites the audience to join in a discussion.
Threats to mobile devices are more prevalent and increasing in scope and complexity. Users of mobile devices desire to take full advantage of the features
available on those devices, but many of the features provide convenience and capability but sacrifice security. This best practices guide outlines steps the users can take to better protect personal devices and information.
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024Neo4j
Neha Bajwa, Vice President of Product Marketing, Neo4j
Join us as we explore breakthrough innovations enabled by interconnected data and AI. Discover firsthand how organizations use relationships in data to uncover contextual insights and solve our most pressing challenges – from optimizing supply chains, detecting fraud, and improving customer experiences to accelerating drug discoveries.
For the full video of this presentation, please visit: https://www.edge-ai-vision.com/2024/06/building-and-scaling-ai-applications-with-the-nx-ai-manager-a-presentation-from-network-optix/
Robin van Emden, Senior Director of Data Science at Network Optix, presents the “Building and Scaling AI Applications with the Nx AI Manager,” tutorial at the May 2024 Embedded Vision Summit.
In this presentation, van Emden covers the basics of scaling edge AI solutions using the Nx tool kit. He emphasizes the process of developing AI models and deploying them globally. He also showcases the conversion of AI models and the creation of effective edge AI pipelines, with a focus on pre-processing, model conversion, selecting the appropriate inference engine for the target hardware and post-processing.
van Emden shows how Nx can simplify the developer’s life and facilitate a rapid transition from concept to production-ready applications.He provides valuable insights into developing scalable and efficient edge AI solutions, with a strong focus on practical implementation.
How to Get CNIC Information System with Paksim Ga.pptxdanishmna97
Pakdata Cf is a groundbreaking system designed to streamline and facilitate access to CNIC information. This innovative platform leverages advanced technology to provide users with efficient and secure access to their CNIC details.
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...SOFTTECHHUB
The choice of an operating system plays a pivotal role in shaping our computing experience. For decades, Microsoft's Windows has dominated the market, offering a familiar and widely adopted platform for personal and professional use. However, as technological advancements continue to push the boundaries of innovation, alternative operating systems have emerged, challenging the status quo and offering users a fresh perspective on computing.
One such alternative that has garnered significant attention and acclaim is Nitrux Linux 3.5.0, a sleek, powerful, and user-friendly Linux distribution that promises to redefine the way we interact with our devices. With its focus on performance, security, and customization, Nitrux Linux presents a compelling case for those seeking to break free from the constraints of proprietary software and embrace the freedom and flexibility of open-source computing.
Essentials of Automations: The Art of Triggers and Actions in FMESafe Software
In this second installment of our Essentials of Automations webinar series, we’ll explore the landscape of triggers and actions, guiding you through the nuances of authoring and adapting workspaces for seamless automations. Gain an understanding of the full spectrum of triggers and actions available in FME, empowering you to enhance your workspaces for efficient automation.
We’ll kick things off by showcasing the most commonly used event-based triggers, introducing you to various automation workflows like manual triggers, schedules, directory watchers, and more. Plus, see how these elements play out in real scenarios.
Whether you’re tweaking your current setup or building from the ground up, this session will arm you with the tools and insights needed to transform your FME usage into a powerhouse of productivity. Join us to discover effective strategies that simplify complex processes, enhancing your productivity and transforming your data management practices with FME. Let’s turn complexity into clarity and make your workspaces work wonders!
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionAggregage
Join Maher Hanafi, VP of Engineering at Betterworks, in this new session where he'll share a practical framework to transform Gen AI prototypes into impactful products! He'll delve into the complexities of data collection and management, model selection and optimization, and ensuring security, scalability, and responsible use.
Removing Uninteresting Bytes in Software FuzzingAftab Hussain
Imagine a world where software fuzzing, the process of mutating bytes in test seeds to uncover hidden and erroneous program behaviors, becomes faster and more effective. A lot depends on the initial seeds, which can significantly dictate the trajectory of a fuzzing campaign, particularly in terms of how long it takes to uncover interesting behaviour in your code. We introduce DIAR, a technique designed to speedup fuzzing campaigns by pinpointing and eliminating those uninteresting bytes in the seeds. Picture this: instead of wasting valuable resources on meaningless mutations in large, bloated seeds, DIAR removes the unnecessary bytes, streamlining the entire process.
In this work, we equipped AFL, a popular fuzzer, with DIAR and examined two critical Linux libraries -- Libxml's xmllint, a tool for parsing xml documents, and Binutil's readelf, an essential debugging and security analysis command-line tool used to display detailed information about ELF (Executable and Linkable Format). Our preliminary results show that AFL+DIAR does not only discover new paths more quickly but also achieves higher coverage overall. This work thus showcases how starting with lean and optimized seeds can lead to faster, more comprehensive fuzzing campaigns -- and DIAR helps you find such seeds.
- These are slides of the talk given at IEEE International Conference on Software Testing Verification and Validation Workshop, ICSTW 2022.
Communications Mining Series - Zero to Hero - Session 1DianaGray10
This session provides introduction to UiPath Communication Mining, importance and platform overview. You will acquire a good understand of the phases in Communication Mining as we go over the platform with you. Topics covered:
• Communication Mining Overview
• Why is it important?
• How can it help today’s business and the benefits
• Phases in Communication Mining
• Demo on Platform overview
• Q/A
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
Unlocking Productivity: Leveraging the Potential of Copilot in Microsoft 365, a presentation by Christoforos Vlachos, Senior Solutions Manager – Modern Workplace, Uni Systems
20 Comprehensive Checklist of Designing and Developing a WebsitePixlogix Infotech
Dive into the world of Website Designing and Developing with Pixlogix! Looking to create a stunning online presence? Look no further! Our comprehensive checklist covers everything you need to know to craft a website that stands out. From user-friendly design to seamless functionality, we've got you covered. Don't miss out on this invaluable resource! Check out our checklist now at Pixlogix and start your journey towards a captivating online presence today.
4. OVERVIEWOFLUA
Lua is a powerful, e cient, lightweight, embeddable
scripting language.
multi-paradigm: Lua supports procedural
programming, object-oriented programming,
functional programming, etc.
dynamically-type: types are attached to values rather
than to variables.
Lua has automatic memory management with
incremental garbage collection.
5. OVERVIEWOFLUA
basic types ( rst-class):
1. nil (like "None" in Python, including unde ned
variables)
2. boolean: true, false
3. number: double-precision oating-point numbers
(like "double" in C)
4. string: immutable (once internalized, cannot be
changed)
5. table: associative arrays
6. function: Lua functions, C functions
7. heavy userdata
8. light userdata
6. 9. thread: coroutines
OVERVIEWOFTABLEINLUA
Tables are the main — in fact, the only — data-
structuring mechanism in Lua.
Tables in Lua are associative arrays, that is, they can be
indexed by any value (except nil) and can hold values
of any type.
Tables are dynamic in the sense that they may grow
when data is added to them (by assigning a value to a
hitherto non-existent eld) and shrink when data is
removed from them (by assigning nil to a eld).
8. TABLECREATION
-- This is a comment.
-- Empty table
local t1 = {}
-- Table as an array
local t2 = { 1, 2, "str", t1 }
-- Table as a hashtable
local t3 = {
["k1"] = "v1",
k2 = "v2",
}
-- Table as mixed data structure of array and hashtable
local t4 = {
"e1", -- stored in the array part
["k1"] = "v1", -- stored in the hash part
9. TABLEASANARRAY
Array Operations:
Set the element of position "n"
Get the element of position "n"
Get the number of elements
Iterate over all elements
Delete the element of position "n"
10. TABLEASANARRAY:SETTER
Set the element of position "n"
NOTE: index in Lua starts from 1
-- Way #1: specify the index
local t = {}
t[1] = "e1"
t[2] = "e2"
t[3] = "e3"
t[4] = "e4"
-- Way #2: use table.insert (list, [pos,] value)
local t = {}
table.insert(t, 1, "e1")
table.insert(t, 2, "e2")
-- table.insert(t, x) inserts x at the end of list t
table.insert(t, "e3")
table.insert(t, "e4")
See the manual of table.insert
11. TABLEASANARRAY:GETTER
Get the element of position "n"
local t = {"e1", "e2", "e3", "e4"}
-- Get the fourth element
print(t[4])
--[[
This is a multi-line comment.
Output:
e4
]]
12. TABLEASANARRAY:GETELEMENTNUMBER
Get the number of elements
local t = {"e1", "e2", "e3", "e4"}
-- Way #1: the length operator "#"
print(#t)
--[[
Output:
4
]]
-- Way #2
--[[
table.unpack(t) returns "e1", "e2", "e3", "e4"
so it becomes:
print(select('#', "e1", "e2", "e3", "e4"))
]]
print(select('#', table.unpack(t)))
Refer to:
manual of the length operator "#"
manual of select
manual of table.unpack
13. TABLEASANARRAY:ITERATION
Iterate over all elements
local t = {"e1", "e2", "e3", "e4"}
-- Forward iteration
for i = 1, 4 do
print(t[i])
end
--[[
Output:
e1
e2
e3
e4
]]
-- More general way:
for i = 1, #t do
print(t[i])
There's another way of using an iterator. We will talk
about that later.
14. TABLEASANARRAY:DELETE
Delete the element of position "n"
-- Way #1: set the specified element as nil
local t = {"e1", "e2", "e3", "e4"}
-- Delete the third element
t[3] = nil
--[[
NOTE:
1. Lua table will not pack the elements backward to fill the empty slot
2. the number of elements will not change
]]
print("The number of elements:", #t)
for i = 1, #t do
print(t[i])
end
--[[
Output:
15. TABLEASANARRAY:DELETE
Delete the element of position "n"
-- Way #2: use table.remove (list [, pos])
local t = {"e1", "e2", "e3", "e4"}
table.remove(t, 3)
print("The number of elements:", #t)
for i = 1, #t do
print(t[i])
end
--[[
Output:
The number of elements: 3
e1
e2
e4
]]
-- table.remove(t) removes the last element of list t.
See the manual of table.remove
16. TABLEASANARRAY:DELETE
Common misuse of table.remove in a loop
local t = {1, 2, 3, 4}
for i = 1, #t do
if t[i] < 4 then
table.remove(t, i)
end
end
--[[
Opps...
lua: xxx.lua:4: attempt to compare nil with number
stack traceback:
xxx.lua:4: in main chunk
[C]: in ?
]]
Why?
17. TABLEASANARRAY:DELETE
Trace the source code using print
local t = {1, 2, 3, 4}
for i = 1, #t do
print(i, t[i])
if t[i] < 4 then
table.remove(t, i)
end
end
--[[
1 1
2 3
3 nil
lua: xxx.lua:5: attempt to compare nil with number
stack traceback:
xxx.lua:5: in main chunk
[C]: in ?
]]
18. TABLEASANARRAY:DELETE
Straightforward solution: use backward iteration.
local t = {1, 2, 3, 4}
for i = #t, 1, -1 do
if t[i] < 4 then
table.remove(t, i)
end
end
for i = 1, #t do
print(t[i])
end
--[[
Output:
4
]]
We will see another misuse case of table.remove when
we discuss iterator ;)
20. TABLEASAHASHTABLE:SETTER
local t = {}
-- Way #1
t["key"] = "value"
-- Way #2: syntactic sugar
t.key = "value"
-- Compare with the following code:
local key = "key"
t[key] = "value"
21. TABLEASAHASHTABLE:GETTER
local t = {
"key" = "value",
}
print("t["key"] = ", t["key"])
print("t.key = ", t.key)
local k = "key"
print("t[k] = ", t[k])
-- t.k is equivalent to t["k"]
print("t.k = ", t.k)
--[[
Output:
t["key"] = value
t.key = value
t[k] = value
t.k = nil
24. TABLEASAHASHTABLE:ITERATION
Meet `next (table [, index])`
Allows a program to traverse all elds of a table. Its
rst argument is a table and its second argument is
an index in this table. next returns the next index of
the table and its associated value. When called with nil
as its second argument, next returns an initial index
and its associated value. When called with the last
index, or with nil in an empty table, next returns nil. If
the second argument is absent, then it is interpreted
as nil. In particular, you can use next(t) to check
whether a table is empty.
25. TABLEASAHASHTABLE:ITERATION
local t = {
k1 = "v1",
k2 = "v2",
k3 = "v3",
}
local k, v
-- Note: equivalent to:
-- local k = nil
-- local v = nil
for i = 1, 3 do
k, v = next(t, k)
print(k, v)
end
-- NOTE: The order in which the indices are enumerated is not specified, even for
--[[
Output:
See the manual of next
26. TABLEASAHASHTABLE:ITERATION
What if we don't know there's three key-value pairs in
the table `t`?
local t = {
k1 = "v1",
k2 = "v2",
k3 = "v3",
}
local k, v = next(t, k)
while k do
-- Note: equivalent to:
-- while k ~= nil do
print(k, v)
k, v = next(t, k)
end
--[[
Output:
k2 v2
k1 v1
27. ITERATOR
Advanced skill: meet the "generic for" in Lua.
for {var-list} in {exp-list} do
{body}
end
Now we can write an iterator and use it in the generic
for loop!
28. ITERATOR
Hand-written iterator (V1):
local t = {
k1 = "v1",
k2 = "v2",
k3 = "v3",
}
local function iter(t)
local last_k
return function()
local v
last_k, v = next(t, last_k)
return last_k, v
end
end
-- Use the iterator in the generic for loop
for k, v in iter(t) do
print(k, v)
It would be di cult to understand if you don't know
anything about closure or lambda! :(
29. ITERATOR
Hand-written iterator (V2): we can pass a function and its
parameters in {exp-list} of "generic for".
local t = {
k1 = "v1",
k2 = "v2",
k3 = "v3",
}
for k, v in next, t do
print(k, v)
end
--[[
Output:
k3 v3
k2 v2
k1 v1
]]
Simpler code :)
It would still be di cult to understand if you don't
know functions in Lua are rst-class variables! :(
30. ITERATOR
There's a built-in iterator: `pairs`! XD
local t = {
k1 = "v1",
k2 = "v2",
k3 = "v3",
}
for k, v in pairs(t) do
print(k, v)
end
--[[
Output:
k3 v3
k1 v1
k2 v2
]]
See the manual of pairs
31. ITERATOR
There's another built-in iterator for array: `ipairs`! XD
local t = {"e1", "e2", "e3", "e4"}
-- Only forward iteration
for i, v in ipairs(t) do
print(i, v)
end
--[[
Output:
1 e1
2 e2
3 e3
4 e4
]]
See the manual of ipairs
32. Now we can talk about another common misuse of
table.remove in loop.
local t = {1, 2, 3, 4}
for i, v in ipairs(t) do
print("Access the element: ", v)
if v < 4 then
table.remove(t, i)
end
end
print("Result:")
for i, v in ipairs(t) do
print(i, v)
end
--[[
Output:
Access the element: 1
Access the element: 3
33. TABLEASAHASHTABLE:GETTHENUMBEROFKEY-VALUEPAIRS
local t = {
k1 = "v1",
k2 = "v2",
k3 = "v3",
}
-- Try the length operator "#":
print(#t)
--[[
Output:
0
]]
Opps...The length operator "#" only deals with the array
part of table. :(
34. TABLEASAHASHTABLE:GETTHENUMBEROFKEY-VALUEPAIRS
Since we know how to iterator over the table, we know
how to count all the key-value pairs. :)
local t = {
k1 = "v1",
k2 = "v2",
k3 = "v3",
}
local cnt = 0
for i, v in pairs(t) do
cnt = cnt + 1
end
print(cnt)
--[[
Output:
3
]]
Complexity: O(N)
36. MATRICES/MULTI-DIMENSIONALARRAYS
Like C array:
-- Create a matrix of zeros with dimensions N by M
-- Way #1
mt = {} -- create the matrix
for i = 1, N do
mt[i] = {} -- create a new row
for j = 1, M do
mt[i][j] = 0
end
end
-- Way #2
mt = {} -- create the matrix
for i = 1, N do
for j = 1, M do
mt[i*M + j] = 0
end
end
37. LINKEDLISTS
-- local node = {next = node, value = v}
-- local list = first_node
function traverse(list)
local node = list
while node do
print(node.value)
node = node.next
end
end
-- We counting the nodes from 1
function insert_kth_node(list, k, node)
assert(k > 0, "invalid k")
-- Insert from front
if k == 1 then
node.next = list
38. STACKS
-- Use Stack as a namespace
local Stack = {}
function Stack.push(stack, element)
table.insert(stack, element)
end
function Stack.pop(stack)
table.remove(stack)
end
function Stack.top(stack)
return stack[#stack]
end
return Stack
39. QUEUESANDDOUBLEQUEUES
local Queue = {}
function Queue.new()
return {first = 0, last = -1}
end
function Queue.pushleft(queue, value)
local first = queue.first - 1
queue.first = first
queue[first] = value
end
function Queue.pushright(queue, value)
local last = queue.last + 1
queue.last = last
queue[last] = value
end
40. SETS
local Set = {}
function Set.new()
return {}
end
function Set.add(set, element)
set[element] = true
end
function Set.has(set, element)
return set[element]
end
-- Union of two sets
function Set.union(set1, set2)
local union = {}
for _, set in ipairs({set1, set2}) do
43. HOWDOLUASTORETABLE?
De nition in lobject.h:
typedef struct Table {
lu_byte lsizenode; /* log2 of size of `node' array */
TValue *array; /* array part */
Node *node;
Node *lastfree; /* any free position is before this position */
int sizearray; /* size of `array' array */
} Table;
44. WHATDOES`TABLE`CONTAIN?
A `Table` instance has at lease three continued areas
in memory:
The `Table` instance itself.
`array`: array part of `Table`
`node`: hash part of `Table`
45. WHATDOES`TABLE`CONTAIN?
Fields of recording the size:
size of array part: `sizearray`
size of hash part: 2^`lsizenode`
#define twoto(x) (1<<(x))
#define sizenode(t) (twoto((t)->lsizenode))
46. Macros related to `Table`:
#define gnode(t,i) (&(t)->node[i])
We will meet this macro later. ;)
49. WHATIS`TVALUE`THEN?
typedef struct lua_TValue TValue;
/*
** Tagged Values. This is the basic representation of values in Lua,
** an actual value plus a tag with its type.
*/
struct lua_TValue {
Value value_;
int tt_;
};
`TValue` = Tagged Value
`TValue` contains the value and a type tag
Lua represents values as tagged unions, that is, as
pairs (t, v), where t is an integer tag identifying the type
of the value v, which is a union of C types
implementing Lua types.
omitted source code: NaN Trick
50. Macros related to `TValue`:
#define val_(o) ((o)->value_)
/* raw type tag of a TValue */
#define rttype(o) ((o)->tt_)
#define setobj(L,obj1,obj2)
{ const TValue *io2=(obj2); TValue *io1=(obj1);
io1->value_ = io2->value_; io1->tt_ = io2->tt_; }
We will meet these macros later. ;)
52. HOWDOESTHETAGDISTINGUISHDIFFERENTTYPESOFLUA
VALUE?
/* raw type tag of a TValue */
#define rttype(o) ((o)->tt_)
/* Macros to test type */
#define checktag(o,t) (rttype(o) == (t))
#define ttistable(o) checktag((o), LUA_TTABLE)
#define hvalue(o) check_exp(ttistable(o), &val_(o).gc->h)
Again, we will meet these macros later. ;)
53. WHATIS`VALUE`?
union Value {
GCObject *gc; /* collectable objects */
void *p; /* light userdata */
int b; /* booleans */
lua_CFunction f; /* light C functions */
lua_Number n; /* numbers */
};
`Value` can be:
`nil`? No! Tag of `TValue` is enough.
#define settt_(o,t) ((o)->tt_=(t))
#define setnilvalue(obj) settt_(obj, LUA_TNIL)
#define ttisnil(o) checktag((o), LUA_TNIL)
55. WHATIS`VALUE`?
union Value {
GCObject *gc; /* collectable objects */
void *p; /* light userdata */
int b; /* booleans */
lua_CFunction f; /* light C functions */
lua_Number n; /* numbers */
};
`Value` can be:
string, table, other function, heavy userdata, thread?
`Value` = `gc`
#define sethvalue(L,obj,x)
{ TValue *io=(obj);
val_(io).gc=cast(GCObject *, (x)); settt_(io, LUA_TTABLE); }
56. WHATIS`GCOBJECT`THEN?
lstate.h
/*
** Union of all collectable objects
*/
typedef union GCObject GCObject;
union GCObject {
GCheader gch; /* common header */
union TString ts;
union Udata u;
union Closure cl;
struct Table h;
struct Proto p;
struct UpVal uv;
struct lua_State th; /* thread */
};
64. BRIEFINTRODUCTIONOFLUAVMANDITSINSTRUCTIONS
xed size (32 bit unsigned integer)
register-based
instruction formats (`sBx' : signed Bx):
We will meet the following guys later:
R(A) : Register A
RK(B) : Register B or a constant index
65. STARTFROMTHENAIVEEXAMPLE
local t = {}
0+ params, 2 slots, 1 upvalue, 1 local, 0 constants, 0 functions
1 [1] NEWTABLE 0 0 0
2 [1] RETURN 0 1
Instructions related to table creation:
1 [1] NEWTABLE 0 0 0
66. NEWTABLEINSTRUCTION
NEWTABLE A B C R(A) := {} (size = B,C)
Creates a new empty table at register R(A).
B: encoded size information for the array part of the
table.
C: encoded size information for the hash part of the
table.
67. EXECUTENEWTABLEINLUAVM
void luaV_execute (lua_State *L) {
CallInfo *ci = L->ci;
LClosure *cl;
TValue *k;
StkId base;
newframe: /* reentry point when frame changes (call/return) */
lua_assert(ci == L->ci);
cl = clLvalue(ci->func);
k = cl->p->k;
base = ci->u.l.base;
/* main loop of interpreter */
for (;;) {
Instruction i = *(ci->u.l.savedpc++);
StkId ra;
if ((L->hookmask & (LUA_MASKLINE | LUA_MASKCOUNT)) &&
(--L->hookcount == 0 || L->hookmask & LUA_MASKLINE)) {
Protect(traceexec(L));
}
A bit confused?
68. EXECUTENEWTABLEINLUAVM
We only need to trace the following part of code for the
naive example. ;)
vmcase(OP_NEWTABLE,
// Get the operator B from the instruction
int b = GETARG_B(i);
// Get the operator C from the instruction
int c = GETARG_C(i);
Table *t = luaH_new(L);
// Remember this macro: `sethvalue` ? ;)
sethvalue(L, ra, t);
)
Now we only need to look at `luaH_new`. :)
69. EXECUTENEWTABLEINLUAVM
Table *luaH_new (lua_State *L) {
Table *t = &luaC_newobj(L, LUA_TTABLE, sizeof(Table), NULL, 0)->h;
t->array = NULL;
t->sizearray = 0;
setnodevector(L, t, 0);
return t;
}
static void setnodevector (lua_State *L, Table *t, int size) {
int lsize;
if (size == 0) { /* no elements to hash part? */
t->node = cast(Node *, dummynode); /* use common `dummynode' */
lsize = 0;
}
else {
int i;
lsize = luaO_ceillog2(size);
if (lsize > MAXBITS)
Confused by `setnodevector`?
75. GETTABLEINSTRUCTION
GETTABLE A B C R(A) := R(B)[RK(C)]
Copies the value from a table element into register
R(A).
The table is referenced by register R(B).
The index to the table is given by RK(C), which may be
the value of register R(C) or a constant number.
76. EXECUTEGETTABLEINLUAVM
Look at the for loop in `luaV_execute` (lvm.c):
vmcase(OP_GETTABLE,
Protect(luaV_gettable(L, RB(i), RKC(i), ra));
)
Now we need to look at `luaV_gettable`. :)
77. EXECUTEGETTABLEINLUAVM
void luaV_gettable (lua_State *L, const TValue *t, TValue *key, TValue *val)
// Remember this macro: `ttistable` ? ;)
if (ttistable(t)) { /* `t' is a table? */
// Remember this macro: `hvalue` ? ;)
Table *h = hvalue(t);
const TValue *res = luaH_get(h, key); /* do a primitive get */
// Remember this macro: `ttisnil` ? ;)
if (!ttisnil(res)) { /* result is not nil? */
// Remember this macro: `setobj` ? ;)
setobj(L, val, res);
}
}
return;
}
Now only the function `luaH_get` causes our
headaches.
78. DIVEINTO`LUAH_GET`
/*
** main search function
*/
const TValue *luaH_get (Table *t, const TValue *key) {
switch (ttype(key)) {
case LUA_TSHRSTR: return luaH_getstr(t, rawtsvalue(key));
case LUA_TNIL: return luaO_nilobject;
case LUA_TNUMBER: {
int k;
lua_Number n = nvalue(key);
lua_number2int(k, n);
if (luai_numeq(cast_num(k), n)) /* index is int? */
return luaH_getint(t, k); /* use specialized version */
/* else go through */
}
default: {
Node *n = mainposition(t, key);
do { /* check whether `key' is somewhere in the chain */
79. IT'SSIMPLERINOURCASE...
const TValue *luaH_get (Table *t, const TValue *key) {
int k;
// Remember this macro: `nvalue` ? ;)
lua_Number n = nvalue(key);
lua_number2int(k, n);
if (luai_numeq(cast_num(k), n)) /* index is int? */
return luaH_getint(t, k); /* use specialized version */
}
What's the so-called specialized function
`luaH_getint`?
80. DIVEINTO`LUAH_GET`
/*
** search function for integers
*/
const TValue *luaH_getint (Table *t, int key) {
/* (1 <= key && key <= t->sizearray) */
if (cast(unsigned int, key-1) < cast(unsigned int, t->sizearray))
return &t->array[key-1];
else {
lua_Number nk = cast_num(key);
Node *n = hashnum(t, nk);
do { /* check whether `key' is somewhere in the chain */
if (ttisnumber(gkey(n)) && luai_numeq(nvalue(gkey(n)), nk))
return gval(n); /* that's it */
else n = gnext(n);
} while (n);
return luaO_nilobject;
}
}
If the int key is smaller than the size of array, access
the array part.
Otherwises, compute the hash value of the key, and
access the hash part.
81. WHATDOESTHISLOOPDO?
do { /* check whether `key' is somewhere in the chain */
if (ttisnumber(gkey(n)) && luai_numeq(nvalue(gkey(n)), nk))
return gval(n); /* that's it */
else n = gnext(n);
} while (n);
return luaO_nilobject;
86. SETTABLEINSTRUCTION
SETTABLE A B C R(A)[RK(B)] := RK(C)
Copies the value from register R(C) or a constant into a
table element.
The table is referenced by register R(A).
The index to the table is given by RK(B), which may be
the value of register R(B) or a constant number.
87. EXECUTESETTABLEINLUAVM
Look at the for loop in `luaV_execute` (lvm.c):
vmcase(OP_SETTABLE,
Protect(luaV_settable(L, ra, RKB(i), RKC(i)));
)
It looks like the case of `GETTABLE`. XD
88. EXECUTESETTABLEINLUAVM
Now look at function `luaV_settable`:
void luaV_settable (lua_State *L, const TValue *t, TValue *key, TValue *val)
if (ttistable(t)) { /* `t' is a table? */
Table *h = hvalue(t);
// Remember `luaH_get`?
TValue *oldval = cast(TValue *, luaH_get(h, key));
/* is there a previous entry in the table? */
if (!ttisnil(oldval) ||
/* no previous entry; must create one. (The next test is
* always true; we only need the assignment.) */
(oldval = luaH_newkey(L, h, key), 1)) {
/* (now) there is an entry with given key */
setobj(L, oldval, val); /* assign new value to that entry */
}
}
return;
}
C trick of comma operator: (a, b, c) is a sequence of
expressions, separated by commas, which evaluates to
the last expression c.
89. WHATDOESLUAV_SETTABLEDO?
1. Get the old value of the key.
2. If
The old value is nil: create a new key by
`luaH_newkey` and write the corresponding value.
Otherwises, rewrite the value.
90. WHATDOESLUAH_NEWKEYDO?
/*
** inserts a new key into a hash table; first, check whether key's main
** position is free. If not, check whether colliding node is in its main
** position or not: if it is not, move colliding node to an empty place and
** put new key in its main position; otherwise (colliding node is in its main
** position), new key goes to an empty position.
*/
TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key) {
Node *mp;
if (ttisnil(key)) luaG_runerror(L, "table index is nil");
else if (ttisnumber(key) && luai_numisnan(L, nvalue(key)))
luaG_runerror(L, "table index is NaN");
mp = mainposition(t, key);
if (!ttisnil(gval(mp)) || isdummy(mp)) { /* main position is taken? */
Node *othern;
Node *n = getfreepos(t); /* get a free place */
if (n == NULL) { /* cannot find a free place? */
rehash(L, t, key); /* grow table */
Don't be scared, we will take it apart. ;D
91. THELUCKIESTCASE
There's free space. The main position has not been
occupied. XD
TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key) {
Node *mp;
mp = mainposition(t, key);
setobj(L, gkey(mp), key);
return gval(mp);
}
92. CASE2
There's free space. The main position has been occupied,
and that bad guy is occupying its main position. :|
TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key) {
Node *mp;
mp = mainposition(t, key);
if (!ttisnil(gval(mp)) || isdummy(mp)) { /* main position is taken? */
Node *othern;
Node *n = getfreepos(t); /* get a free place */
lua_assert(!isdummy(n));
/* colliding node is in its own main position */
/* new node will go into free position */
gnext(n) = gnext(mp); /* chain new position */
gnext(mp) = n;
mp = n;
}
setobj(L, gkey(mp), key);
return gval(mp);
}
93. CASE3
There's free space. The main position has been occupied,
and that bad guy is not occupying its main position. :(
TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key) {
Node *mp;
mp = mainposition(t, key);
if (!ttisnil(gval(mp)) || isdummy(mp)) { /* main position is taken? */
Node *othern;
Node *n = getfreepos(t); /* get a free place */
lua_assert(!isdummy(n));
othern = mainposition(t, gkey(mp));
if (othern != mp) { /* is colliding node out of its main position? */
/* yes; move colliding node into free position */
while (gnext(othern) != mp) othern = gnext(othern); /* find previous */
gnext(othern) = n; /* redo the chain with `n' in place of `mp' */
*n = *mp; /* copy colliding node into free pos. (mp->next also goes) */
gnext(mp) = NULL; /* now `mp' is free */
setnilvalue(gval(mp));
}
}
setobj(L, gkey(mp), key);
94. CASE4
There's no free space. :(
It will cause rehashing.
The array part may grow or shrink so that at lease half
of the array is occupied. If the array part shrinks, its
rest elements will be inserted into the hash part.
The hash part may grow or shrink, too. Its size is
determined by the number of valid key-value pair,
whose value is not nil, and the number of elements
from the shrinked array part. Moreover, the size is
guaranteed to be power of two. (Remember the
`lsizenode` eld of `Table`?)
I will not show the source code of rehashing in order not
to scare you. XD
96. COUNTINGTHEOCCURRENCESOF
REHASHING:
Zero rehash, resize the array part once at table creation.
:)
local t = {"e1", "e2", "e3", "e4", "e5"}
Rehash four times at SETTABLE. :(
local t = {}
t[1] = "e1" -- rehash
t[2] = "e2" -- rehash
t[3] = "e3" -- rehash
t[4] = "e4"
t[5] = "e5" -- rehash
The rehashing overhead can be much higher if there's
lots of small table in your Lua program.
99. REFERENCES
"The Implementation of Lua 5.0" by Roberto
Ierusalimschy, Luiz Henrique de Figueiredo, Waldemar
Celes
"Programming in Lua" by the leading architect of Lua,
Roberto Ierusalimschy:
"A No-Frills Introduction to Lua 5.1 VM Instructions" by
Kein-Hong Man
"Lua Performance Tips" by Roberto Ierusalimschy
Lua o cial website
First version is free online (Lua
5.0)