GDG DevFest 2017 - Inspections of Kotlin implementations by Bytecode.
세션 이후 "Kotlin은 Java의 wrapper인가요?" 라는 질문을 몇번 받았습니다.
—
답변: 그렇지 않습니다.
특정한 언어로 구현된 코드는 파싱을 거쳐 추상화된 형태(AST)와 추가 정보들을 가지는 1차적인 결과물로 처리됩니다. 보통 이런 역할을 하는 것은 컴파일러에서 전단부(frontend)라고 호칭하며 이러한 AST 등의 결과물은 대상 머신이나 플랫폼에 맞추어 처리됩니다.
이를 바로 실행하면 인터프리터라고 하지만, 실행 가능한 형태(Executable)로 생성하는 경우라면 컴파일러 후단부(Backend)가 이를 수행합니다.
백엔드의 타겟 코드는 충분히 다양한 대상을 다룰 수 있으므로, 우리가 다양한 백엔드 구현을 통해 동일 코드를 멀티 플랫폼을 대상으로 실행할 수 있도록 할 수 있는 것입니다.
코틀린 역시 대상으로 하는 플랫폼(과 머신)은 현재 다음과 같은 실행 가능한 형태를 지원하고 있습니다. (물론 아직 모든 타겟이 완벽하지는 않겠죠.)
1. Bytecode 포맷에 따른 JVM(안드로이드 포함)
2. JavaScript에 의한 브라우저나 Node.js
3. llvm을 이용하여 여러 타겟의 네이티브 코드
이 자료는 이 중 1번을 기반으로 디컴파일된 코드를 살펴보고 코틀린의 코드 생성 목적이나 언어 설계의 원인(어떤 painpoint)를 찾아보는 과정의 일부였을 뿐입니다.
언어는 항상 요구되는 표현을 위해 가장 적합한 형태로 변화해나갑니다. 프로그래밍 언어는 비교적 단기간에 만들어지는 언어이고, 그에 따라 특정 사람과 집단의 목적에 충실합니다. 다만, 이 관점에서 봤을 때도 Kotlin이 Java의 wrapper로써 설계되었을 것보다는 다양한 타겟 플랫폼이 고려되고 있는 하나의 프로그래밍 언어로 받아들여 주시기를 바랍니다. :)
GDG DevFest 2017 - Inspections of Kotlin implementations by Bytecode.
세션 이후 "Kotlin은 Java의 wrapper인가요?" 라는 질문을 몇번 받았습니다.
—
답변: 그렇지 않습니다.
특정한 언어로 구현된 코드는 파싱을 거쳐 추상화된 형태(AST)와 추가 정보들을 가지는 1차적인 결과물로 처리됩니다. 보통 이런 역할을 하는 것은 컴파일러에서 전단부(frontend)라고 호칭하며 이러한 AST 등의 결과물은 대상 머신이나 플랫폼에 맞추어 처리됩니다.
이를 바로 실행하면 인터프리터라고 하지만, 실행 가능한 형태(Executable)로 생성하는 경우라면 컴파일러 후단부(Backend)가 이를 수행합니다.
백엔드의 타겟 코드는 충분히 다양한 대상을 다룰 수 있으므로, 우리가 다양한 백엔드 구현을 통해 동일 코드를 멀티 플랫폼을 대상으로 실행할 수 있도록 할 수 있는 것입니다.
코틀린 역시 대상으로 하는 플랫폼(과 머신)은 현재 다음과 같은 실행 가능한 형태를 지원하고 있습니다. (물론 아직 모든 타겟이 완벽하지는 않겠죠.)
1. Bytecode 포맷에 따른 JVM(안드로이드 포함)
2. JavaScript에 의한 브라우저나 Node.js
3. llvm을 이용하여 여러 타겟의 네이티브 코드
이 자료는 이 중 1번을 기반으로 디컴파일된 코드를 살펴보고 코틀린의 코드 생성 목적이나 언어 설계의 원인(어떤 painpoint)를 찾아보는 과정의 일부였을 뿐입니다.
언어는 항상 요구되는 표현을 위해 가장 적합한 형태로 변화해나갑니다. 프로그래밍 언어는 비교적 단기간에 만들어지는 언어이고, 그에 따라 특정 사람과 집단의 목적에 충실합니다. 다만, 이 관점에서 봤을 때도 Kotlin이 Java의 wrapper로써 설계되었을 것보다는 다양한 타겟 플랫폼이 고려되고 있는 하나의 프로그래밍 언어로 받아들여 주시기를 바랍니다. :)
Effective Java with Groovy - How Language Influences Adoption of Good PracticesNaresha K
Slides from my APACHECON@HOME 2020 talk - "Effective Java with Groovy - How Language Influences Adoption of Good Practices".
'Effective Java' presents the most effective ways of using language. However, the adoption of these practices among Java developers is less than satisfactory. In my observation, the effort required to implement them can be a barrier to the adoption of these practices. Since Groovy runs on JVM, most of the suggestions from Effective Java are equally relevant for Groovy developers. Groovy provides out of the box constructs for many of the recommended practices which can boost developer productivity. In this talk, I walk you through code examples that follow these good practices, highlighting the Groovy way of implementing the 'Effective Java' suggestions. As a participant, you walk away, appreciating the simplicity with which Groovy empowers the developers. The talk also provides food for thought - how a language can influence its users to adopt good practices. Java users learn the techniques a language can use to reduce the friction to adoption of good practices, instead of coming up with a prescription on how to implement good practices. Developers familiar with Groovy understand the reason behind the design of their favourite language features.
Groovy is a dynamic language that provides different types of metaprogramming techniques. In this talk we’ll mainly see runtime metaprogramming. You’ll understand the Groovy Meta-Object-Protocol (MOP), the metaclass, how to intercept method calls, how to deal with method missing and property missing, the use of mixins, traits and categories. All of these topics will be explained with examples in order to understand them. Also, you’ll see a little bit about compile-time metaprogramming with AST Transformations. AST Transformations provide a wonderful way of manipulating code at compile time via modifications of the Abstract Syntax Tree. You’ll see a basic but powerful example of what we can do with AST transformations.
Will talk about kotlin the language and new concepts introduced in the language including functional programming.
And how to use your springframework knowlege to write more concise and elegant backend systems.
We will demo a backend written in spring boot and kotlin and will see how it is so easy to interoperate between java and kotlin code.
If you thought Monads are a mystery, then this demonstration would show you how to evolve your code towards a Monad without knowing about it. This demo will neither go into any Category Theory nor begin with monadic laws. Instead, we will start with typical code that you see in your daily life as a developer, attempt to DRY (Don't Repeat Yourself) it up and eventually use Monad to remove duplication and verbosity. You'll also see how Monads make your code more declarative and succinct by sequencing the steps in your domain logic.
Also, we know in Java8 Checked Exceptions + λ == Pain! To be more precise, we will evolve a Try<t> (exception handling monad) which is missing in Java8, similar to one found in Scala.
Avec la version 9 sortie en septembre 2017, Java appuie sur la pédale ! Le rythme des livraisons passe à une version majeure tous les 6 mois. Java 10 est sorti en mars, prochaine version en septembre. Java 10 apporte le 'var' et l'inférence de type pour les variables locales. D'autres nouveautés sont en préparation : les constantes dynamiques, les classes de données, un nouveau switch à base de lambda, des interfaces fermées, de nouvelles choses du coté des génériques et bien plus encore.
Cela viendra-t-il en 11, 12, 15 ? Ne spéculons pas, mais quand ces nouveautés seront prêtes, elles sortiront en quelques mois. On se propose de présenter ces nouveautés, celles qui sont presque prêtes, celles qui seront prêtes bientôt, et celles qui ne seront pas prêtes avant un moment. Quels seront les impacts sur le langage, sur la JVM et donc sur les performances ? Que cela va-t-il nous apporter au quotidien, en tant que développeurs ? Quels seront les nouveaux patterns ? Voici le programme de cette présentation, avec des slides, du code, de la joie et de la bonne humeur !
Leveraging Completable Futures to handle your query results AsynchrhonouslyDavid Gómez García
The challenges of developing applications recently have increased. With the popularity of cloud environments, the scalability required by new architectures and the need to support more load efficiently, there has been an increase in attention that we need to pay to concurrency and efficiency.
One strategy to achieve that efficiency consists of distributing the modules of your application in several different smaller components running concurrently. But one of the problems that arise from such distribution of running modules comes when you need to send a request (and wait for the response) to several different modules. How do you design that request(s)-response(s) to be as efficient as possible?
CompletableFutures was introduced with Java 8 but has evolved over the years with every new version of Java released. In this talk, we will take a look at it, to:
understand how to use CompletableFutures,
how they can help us to split our workload into different request and coordinate them asynchronously and concurrently
How you can chain behavior to the responses.
How you can use CompletableFuture in your design to create APIs that enable your users to get the most of your Component/library/module.
Use PEG to Write a Programming Language ParserYodalee
PEG is a replacement to CFG. It is more powerful and can be more precise. In this slide I give a short introduction to PEG, the concept behind a programming language. Finally I write a parser for our programming language simple.
Effective Java with Groovy - How Language Influences Adoption of Good PracticesNaresha K
Slides from my APACHECON@HOME 2020 talk - "Effective Java with Groovy - How Language Influences Adoption of Good Practices".
'Effective Java' presents the most effective ways of using language. However, the adoption of these practices among Java developers is less than satisfactory. In my observation, the effort required to implement them can be a barrier to the adoption of these practices. Since Groovy runs on JVM, most of the suggestions from Effective Java are equally relevant for Groovy developers. Groovy provides out of the box constructs for many of the recommended practices which can boost developer productivity. In this talk, I walk you through code examples that follow these good practices, highlighting the Groovy way of implementing the 'Effective Java' suggestions. As a participant, you walk away, appreciating the simplicity with which Groovy empowers the developers. The talk also provides food for thought - how a language can influence its users to adopt good practices. Java users learn the techniques a language can use to reduce the friction to adoption of good practices, instead of coming up with a prescription on how to implement good practices. Developers familiar with Groovy understand the reason behind the design of their favourite language features.
Groovy is a dynamic language that provides different types of metaprogramming techniques. In this talk we’ll mainly see runtime metaprogramming. You’ll understand the Groovy Meta-Object-Protocol (MOP), the metaclass, how to intercept method calls, how to deal with method missing and property missing, the use of mixins, traits and categories. All of these topics will be explained with examples in order to understand them. Also, you’ll see a little bit about compile-time metaprogramming with AST Transformations. AST Transformations provide a wonderful way of manipulating code at compile time via modifications of the Abstract Syntax Tree. You’ll see a basic but powerful example of what we can do with AST transformations.
Will talk about kotlin the language and new concepts introduced in the language including functional programming.
And how to use your springframework knowlege to write more concise and elegant backend systems.
We will demo a backend written in spring boot and kotlin and will see how it is so easy to interoperate between java and kotlin code.
If you thought Monads are a mystery, then this demonstration would show you how to evolve your code towards a Monad without knowing about it. This demo will neither go into any Category Theory nor begin with monadic laws. Instead, we will start with typical code that you see in your daily life as a developer, attempt to DRY (Don't Repeat Yourself) it up and eventually use Monad to remove duplication and verbosity. You'll also see how Monads make your code more declarative and succinct by sequencing the steps in your domain logic.
Also, we know in Java8 Checked Exceptions + λ == Pain! To be more precise, we will evolve a Try<t> (exception handling monad) which is missing in Java8, similar to one found in Scala.
Avec la version 9 sortie en septembre 2017, Java appuie sur la pédale ! Le rythme des livraisons passe à une version majeure tous les 6 mois. Java 10 est sorti en mars, prochaine version en septembre. Java 10 apporte le 'var' et l'inférence de type pour les variables locales. D'autres nouveautés sont en préparation : les constantes dynamiques, les classes de données, un nouveau switch à base de lambda, des interfaces fermées, de nouvelles choses du coté des génériques et bien plus encore.
Cela viendra-t-il en 11, 12, 15 ? Ne spéculons pas, mais quand ces nouveautés seront prêtes, elles sortiront en quelques mois. On se propose de présenter ces nouveautés, celles qui sont presque prêtes, celles qui seront prêtes bientôt, et celles qui ne seront pas prêtes avant un moment. Quels seront les impacts sur le langage, sur la JVM et donc sur les performances ? Que cela va-t-il nous apporter au quotidien, en tant que développeurs ? Quels seront les nouveaux patterns ? Voici le programme de cette présentation, avec des slides, du code, de la joie et de la bonne humeur !
Leveraging Completable Futures to handle your query results AsynchrhonouslyDavid Gómez García
The challenges of developing applications recently have increased. With the popularity of cloud environments, the scalability required by new architectures and the need to support more load efficiently, there has been an increase in attention that we need to pay to concurrency and efficiency.
One strategy to achieve that efficiency consists of distributing the modules of your application in several different smaller components running concurrently. But one of the problems that arise from such distribution of running modules comes when you need to send a request (and wait for the response) to several different modules. How do you design that request(s)-response(s) to be as efficient as possible?
CompletableFutures was introduced with Java 8 but has evolved over the years with every new version of Java released. In this talk, we will take a look at it, to:
understand how to use CompletableFutures,
how they can help us to split our workload into different request and coordinate them asynchronously and concurrently
How you can chain behavior to the responses.
How you can use CompletableFuture in your design to create APIs that enable your users to get the most of your Component/library/module.
Use PEG to Write a Programming Language ParserYodalee
PEG is a replacement to CFG. It is more powerful and can be more precise. In this slide I give a short introduction to PEG, the concept behind a programming language. Finally I write a parser for our programming language simple.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
UiPath Test Automation using UiPath Test Suite series, part 5DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 5. In this session, we will cover CI/CD with devops.
Topics covered:
CI/CD with in UiPath
End-to-end overview of CI/CD pipeline with Azure devops
Speaker:
Lyndsey Byblow, Test Suite Sales Engineer @ UiPath, Inc.
UiPath Test Automation using UiPath Test Suite series, part 6DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 6. In this session, we will cover Test Automation with generative AI and Open AI.
UiPath Test Automation with generative AI and Open AI webinar offers an in-depth exploration of leveraging cutting-edge technologies for test automation within the UiPath platform. Attendees will delve into the integration of generative AI, a test automation solution, with Open AI advanced natural language processing capabilities.
Throughout the session, participants will discover how this synergy empowers testers to automate repetitive tasks, enhance testing accuracy, and expedite the software testing life cycle. Topics covered include the seamless integration process, practical use cases, and the benefits of harnessing AI-driven automation for UiPath testing initiatives. By attending this webinar, testers, and automation professionals can gain valuable insights into harnessing the power of AI to optimize their test automation workflows within the UiPath ecosystem, ultimately driving efficiency and quality in software development processes.
What will you get from this session?
1. Insights into integrating generative AI.
2. Understanding how this integration enhances test automation within the UiPath platform
3. Practical demonstrations
4. Exploration of real-world use cases illustrating the benefits of AI-driven test automation for UiPath
Topics covered:
What is generative AI
Test Automation with generative AI and Open AI.
UiPath integration with generative AI
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Climate Impact of Software Testing at Nordic Testing DaysKari Kakkonen
My slides at Nordic Testing Days 6.6.2024
Climate impact / sustainability of software testing discussed on the talk. ICT and testing must carry their part of global responsibility to help with the climat warming. We can minimize the carbon footprint but we can also have a carbon handprint, a positive impact on the climate. Quality characteristics can be added with sustainability, and then measured continuously. Test environments can be used less, and in smaller scale and on demand. Test techniques can be used in optimizing or minimizing number of tests. Test automation can be used to speed up testing.
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
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.
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.
GridMate - End to end testing is a critical piece to ensure quality and avoid...ThomasParaiso2
End to end testing is a critical piece to ensure quality and avoid regressions. In this session, we share our journey building an E2E testing pipeline for GridMate components (LWC and Aura) using Cypress, JSForce, FakerJS…
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfPaige Cruz
Monitoring and observability aren’t traditionally found in software curriculums and many of us cobble this knowledge together from whatever vendor or ecosystem we were first introduced to and whatever is a part of your current company’s observability stack.
While the dev and ops silo continues to crumble….many organizations still relegate monitoring & observability as the purview of ops, infra and SRE teams. This is a mistake - achieving a highly observable system requires collaboration up and down the stack.
I, a former op, would like to extend an invitation to all application developers to join the observability party will share these foundational concepts to build on:
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofsAlex Pruden
This paper presents Reef, a system for generating publicly verifiable succinct non-interactive zero-knowledge proofs that a committed document matches or does not match a regular expression. We describe applications such as proving the strength of passwords, the provenance of email despite redactions, the validity of oblivious DNS queries, and the existence of mutations in DNA. Reef supports the Perl Compatible Regular Expression syntax, including wildcards, alternation, ranges, capture groups, Kleene star, negations, and lookarounds. Reef introduces a new type of automata, Skipping Alternating Finite Automata (SAFA), that skips irrelevant parts of a document when producing proofs without undermining soundness, and instantiates SAFA with a lookup argument. Our experimental evaluation confirms that Reef can generate proofs for documents with 32M characters; the proofs are small and cheap to verify (under a second).
Paper: https://eprint.iacr.org/2023/1886
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
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.
Maruthi Prithivirajan, Head of ASEAN & IN Solution Architecture, Neo4j
Get an inside look at the latest Neo4j innovations that enable relationship-driven intelligence at scale. Learn more about the newest cloud integrations and product enhancements that make Neo4j an essential choice for developers building apps with interconnected data and generative AI.
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.
Mind map of terminologies used in context of Generative AI
The Ring programming language version 1.4 book - Part 11 of 30
1. Ring Documentation, Release 1.4
nIwantwindow++
ok
func getwant
if nIwantwindow = 1
nIwantwindow++
ok
func getwindow
if nIwantwindow = 2
nIwantwindow= 0
see "Instruction : I want window" + nl
ok
if nWindowTitle = 0
nWindowTitle++
ok
func settitle cValue
if nWindowTitle = 1
nWindowTitle=0
see "Instruction : Window Title = " + cValue + nl
ok
42.6 Using Eval() with our Natural Code
Example:
func Main
cProgram = ' I want window and the window title is "hello world" '
MyLanguage(cProgram)
Func MyLanguage cCode
# We add to the code the instructions that change keywords and operators
# Because Eval() uses a new Compiler Object (the original keywords and operatos).
cCode = '
ChangeRingKeyword and _and
ChangeRingOperator = is
' + cCode
New App
{
eval(cCode)
}
Class App
# Attributes for the instruction I want window
i want window
nIwantwindow = 0
# Attributes for the instruction Window title
# Here we don't define the window attribute again
42.6. Using Eval() with our Natural Code 278
2. Ring Documentation, Release 1.4
title
nWindowTitle = 0
# Keywords to ignore, just give them any value
the=0
ChangeRingKeyword and _and
and=0
ChangeRingKeyword _and and
func geti
if nIwantwindow = 0
nIwantwindow++
ok
func getwant
if nIwantwindow = 1
nIwantwindow++
ok
func getwindow
if nIwantwindow = 2
nIwantwindow= 0
see "Instruction : I want window" + nl
ok
if nWindowTitle = 0
nWindowTitle++
ok
func settitle cValue
if nWindowTitle = 1
nWindowTitle=0
see "Instruction : Window Title = " + cValue + nl
ok
42.7 BraceStart and BraceEnd Methods
We can write code that will be executed before/after using { }
Example:
o1 = new test {
see "Hello" + nl
}
o1 {}
class test
func bracestart
see "start" + nl
func braceend
see "end" + nl
Output:
42.7. BraceStart and BraceEnd Methods 279
3. Ring Documentation, Release 1.4
start
Hello
end
start
end
42.8 BraceExprEval Method
The next example demonstrates how to use the “BraceExprEval” method to get expressions in Natural code.
Example:
new natural {
create 5
}
class natural
create=0
lkeyword = false
func braceexpreval r
if lkeyword lkeyword=false return ok
see "expr eval" + nl
see "type: " + type(r) see nl
see "value : " see r see nl
func getcreate
lkeyword = true
see "create" + nl
Output:
create
expr eval
type: NUMBER
value : 5
42.9 Real Natural Code
The next example is a more advanced example
# Natural Code
new program {
Accept 2 numbers then print the sum
}
# Natural Code Implementation
class program
# Keywords
Accept=0 numbers=0 then=0 print=0 the=0 sum=0
# Execution
func braceexpreval x
value = x
func getnumbers
for x=1 to value
see "Enter Number ("+x+") :" give nNumber
42.8. BraceExprEval Method 280
4. Ring Documentation, Release 1.4
aNumbers + nNumber
next
func getsum
nSUm = 0
for x in aNumbers nSum+= x next
see "The Sum : " + nSum
private
value=0 aNumbers=[]
Output:
Enter Number (1) :3
Enter Number (2) :4
The Sum : 7
42.10 BraceError() Method
The next examples demonstrates how to use the “BraceError” method to handle errors when accessing the object using
braces {}.
Example:
func main
o1 = new point {
x=10 y=20 z=30
TEST
SEE test
}
class point x y z
func braceerror
see "Handle Error!" + nl
SEE "Message :" + cCatchError + nl
if ( left(cCatchError,11) = "Error (R24)" ) and not isattribute(self,"test")
see "add attribute" + nl
addattribute(self,"test")
test = 10
ok
see "done" + nl
return
Output:
Handle Error!
Message :Error (R24) : Using uninitialized variable : test
add attribute
done
10
Example:
new point {
x=10 y=20 z=30
test()
see "mmm..." + NL
}
42.10. BraceError() Method 281
5. Ring Documentation, Release 1.4
class point x y z
func braceerror
see "Handle Error!" + nl
see "Message :" + cCatchError + nl
see self
see "Done" + NL
Output:
Handle Error!
Message :Error (R3) : Calling Function without definition !: test
x: 10.000000
y: 20.000000
z: 30.000000
Done
mmm...
42.11 Clean Natural Code
Instead of typing the literal as “literal” we can accept the words directly.
Example:
The next example accept hello world instead of “hello world”
But this example uses braceend() to check the end of the instruction
This means that this class process only one natural statement that end with literal.
ChangeRingKeyword and _and
New App
{
I want window and the window title is hello world
}
Class App
# Attributes for the instruction I want window
i want window
nIwantwindow = 0
# Attributes for the instruction Window title
# Here we don't define the window attribute again
title is
nWindowTitle = 0
# Keywords to ignore, just give them any value
the=0 and=0
# Data
literal = ""
ChangeRingKeyword _and and
func geti
if nIwantwindow = 0
nIwantwindow++
ok
func getwant
42.11. Clean Natural Code 282
6. Ring Documentation, Release 1.4
if nIwantwindow = 1
nIwantwindow++
ok
func getwindow
if nIwantwindow = 2
nIwantwindow= 0
see "Instruction : I want window" + nl
ok
if nWindowTitle = 0
nWindowTitle++
ok
func gettitle
if nWindowTitle = 1
nWindowTitle=2
ok
func getis
if nWindowTitle = 2
nWindowTitle=3
ok
func braceend
if nWindowTitle = 3
see "Instruction : Window Title = " + literal + nl
nWindowTitle = 0
ok
func braceerror
c= substr(cCatchError,":")
while c > 0
c= substr(cCatchError,":")
cCatchError=substr(cCatchError,c+1)
end
literal += substr(cCatchError,1)
42.11. Clean Natural Code 283
7. CHAPTER
FORTYTHREE
USING THE NATURAL LIBRARY
In this chapter we will learn how to use the Natural Library to quickly define a language that contains a group of
commands.
To start using the library, We need to call naturallib.ring
load "naturallib.ring"
After loading the library, We can use the NaturalLanguage class that contains the next methods :-
• SetLanguageName(cLanguageName)
• setCommandsPath(cFolder)
• SetPackageName(cPackageName)
• UseCommand(cCommandName)
• SetOperators(cOperators)
• RunFile(cFileName)
• RunString(cString)
43.1 Natural Library - Demo Program
We will write the natural code in a Text file, for example program.txt
File: program.txt
Welcome to the Ring programming language!
What you are reading now is not comments, I swear!
After many years of programming I decided to think different about
programming and solve the problems in a better way.
We are writing commands or code and the Ring language is reading
it to understand us! Sure, What you are seeing now is
just ***part of the code - Not the Complete Program***
You have to write little things before and after this
part to be able to run it!
It is the natural part of our code where we can write in English,
Arabic or any Natural Language Then we will tell the computer
through the Ring language what must happens! in a way that we can scale
for large frameworks and programs.
284
8. Ring Documentation, Release 1.4
Just imagine what will happens to the world of programming once
we create many powerful frameworks using the Ring language that
uses this way (Natural Programming).
For example When we say Hello to the Machine, It can reply! and when we
say count from 1 to 5 it will understand us, Also if
we said count from 5 to 1 it will
understand us too! You can see the Output window!
This Goal is not new, but the Ring language comes
with an innovative solution to this problem.
Output:
Hello, Sire!
The Numbers!
1
2
3
4
5
I will count Again!
5
4
3
2
1
To execute the natural code, We have start.ring
In start.ring we define the language and the commands.
File: start.ring
load "stdlib.ring"
load "naturallib.ring"
New NaturalLanguage {
SetLanguageName(:MyLanguage)
SetCommandsPath(CurrentDir()+"/../command")
SetPackageName("MyLanguage.Natural")
UseCommand(:Hello)
UseCommand(:Count)
RunFile("program.txt")
}
We defined a language called MyLanguage, We have folder for the language commands.
43.1. Natural Library - Demo Program 285
9. Ring Documentation, Release 1.4
Each command will define a class that belong to the MyLanguage.Natural package.
We will define two commands, Hello and Count.
So we must have two files for defining the commands in the CurrentDir()+”/../command” folder
File: hello.ring
DefineNaturalCommand.SyntaxIsKeyword([
:Package = "MyLanguage.Natural",
:Keyword = :hello,
:Function = func {
See "Hello, Sire!" + nl + nl
}
])
File: count.ring
DefineNaturalCommand.SyntaxIsKeywordNumberNumber([
:Package = "MyLanguage.Natural",
:Keyword = :count,
:Function = func {
if not isattribute(self,:count_times) {
AddAttribute(self,:count_times)
Count_Times = 0
}
if Expr(1) > Expr(2) {
nStep = -1
else
nStep = 1
}
if Count_Times = 0 {
see nl+"The Numbers!" + nl
Count_Times++
else
see nl + "I will count Again!" +nl
}
for x = Expr(1) to Expr(2) step nStep {
see nl+x+nl
}
CommandReturn(fabs(Expr(1)-Expr(2))+1)
}
])
43.2 Defining Commands
To define new command we can use the DefineNaturalCommand object
This object provides the next methods :-
• SyntaxIsKeyword(aPara)
• SyntaxIsKeywordNumber(aPara)
• SyntaxIsKeywordNumberNumber(aPara)
• SyntaxIsKeywordNumbers(aPara,nCount)
• SyntaxIsKeywordString(aPara)
• SyntaxIsKeywordStringString(aPara)
43.2. Defining Commands 286
10. Ring Documentation, Release 1.4
• SyntaxIsKeywordStrings(aPara,nCount)
• SyntaxIsKeywordExpression(aPara)
• SyntaxIsKeywordExpressionExpression(aPara)
• SyntaxIsKeywordExpressions(aPara,nCount)
• SyntaxIsCommand(aPara)
• SyntaxIsCommandNumber(aPara)
• SyntaxIsCommandNumberNumber(aPara)
• SyntaxIsCommandNumbers(aPara,nCount)
• SyntaxIsCommandString(aPara)
• SyntaxIsCommandStringString(aPara)
• SyntaxIsCommandStrings(aPara,nCount)
• SyntaxIsCommandExpression(aPara)
• SyntaxIsCommandExpressionExpression(aPara)
• SyntaxIsCommandExpressions(aPara,nCount)
File: mylanguage.ring
load "stdlib.ring"
load "naturallib.ring"
MyLanguage = New NaturalLanguage {
SetLanguageName(:MyLanguage)
setCommandsPath(CurrentDir()+"/../command")
SetPackageName("MyLanguage.Natural")
UseCommand(:Hello)
UseCommand(:Count)
UseCommand(:Print)
UseCommand(:IWantWindow)
UseCommand(:WindowTitleIs)
UseCommand(:IWantButton)
}
Example (1)
In the next example we will define the Print command.
We will use the SyntaxIsKeywordExpression() Method.
We pass list (as Hash) to the method. We determine the package name, the keyword and the function that will be
executed.
Inside this function we uses the Expr(nExprNumber) function to get the expression value that the user will write after
the keyword.
File: print.ring
DefineNaturalCommand.SyntaxIsKeywordExpression([
:Package = "MyLanguage.Natural",
:Keyword = :print,
:Function = func {
See Expr(1)
}
])
43.2. Defining Commands 287
11. Ring Documentation, Release 1.4
Usage:
load "mylanguage.ring"
MyLanguage.RunString('
print "Hello, World!"
')
Output:
Hello, World!
Example (2)
File: iwantwindow.ring
DefineNaturalCommand.SyntaxIsCommand([
:Package = "MyLanguage.Natural",
:Command = "i want window",
:Function = func {
See "Command: I want window" + nl
}
])
Usage:
load "mylanguage.ring"
MyLanguage.RunString('
i want window
')
Output:
Command: I want window
Example (3)
File: windowtitleis.ring
DefineNaturalCommand.SyntaxIsCommandString([
:Package = "MyLanguage.Natural",
:Command = "window title is",
:Function = func {
See "Command: Window title is " + Expr(1) + nl
}
])
Usage:
load "mylanguage.ring"
MyLanguage.RunString('
I want window and the window title is "Hello World"
')
Output:
Command: I want window
Command: Window title is Hello World
43.2. Defining Commands 288
12. Ring Documentation, Release 1.4
43.3 Natural Library - Operators
In the next example we uses the Count command without using operators
load "mylanguage.ring"
MyLanguage.RunString("
Hello
Count 1 5
Count 5 1
")
We can add more description
load "mylanguage.ring"
MyLanguage.RunString("
Hello, Please Count from 1 to 5 then count from 5 to 1
")
Also we can use operators like “(” and ”)” around the instruction
load "mylanguage.ring"
MyLanguage {
SetOperators("()")
RunString("
Here we will play and will try something
that looks like Lisp Syntax
(count (count 1 5) (count 20 15))
Just for fun!
")
}
43.4 Defining commands using classes
This section is related to the implementation details.
When we define new command, Each command is defined by the Natural Library as a class.
We have the choice to define commands using the simple interface provided by the DefineNaturalCommand object or
by defining new class as in the next examples.
If we used DefineNaturalCommand (More Simple), The class will be defined during the runtime.
File: hello.ring
Package MyLanguage.Natural
class Hello
func AddAttributes_Hello
AddAttribute(self,:hello)
func GetHello
See "Hello, Sire!" + nl + nl
File: count.ring
43.3. Natural Library - Operators 289
13. Ring Documentation, Release 1.4
Package MyLanguage.Natural
class Count
func Getcount
StartCommand()
CommandData()[:name] = :Count
CommandData()[:nExpr] = 0
CommandData()[:aExpr] = []
func BraceExprEval_Count nValue
if isCommand() and CommandData()[:name] = :Count {
if isNumber(nValue) {
CommandData()[:nExpr]++
CommandData()[:aExpr] + nValue
if CommandData()[:nExpr] = 2 {
Count_Execute()
}
}
}
func AddAttributes_Count
AddAttribute(self,:count)
func Count_Execute
if not isattribute(self,:count_times) {
AddAttribute(self,:count_times)
Count_Times = 0
}
if Expr(1) > Expr(2) {
nStep = -1
else
nStep = 1
}
if Count_Times = 0 {
see nl+"The Numbers!" + nl
Count_Times++
else
see nl + "I will count Again!" +nl
}
for x = Expr(1) to Expr(2) step nStep {
see nl+x+nl
}
CommandReturn(fabs(Expr(1)-Expr(2))+1)
43.4. Defining commands using classes 290
14. CHAPTER
FORTYFOUR
WEB DEVELOPMENT (CGI LIBRARY)
In this chapter we will learn about developing Web applications using a CGI Library written in the Ring language.
44.1 Configure the Apache web server
We can use Ring with any web server that support CGI. In this section we will learn about using Ring with the Apache
HTTP Server.
You can download Apache from : http://httpd.apache.org/
Or you can get it included with other projects like
XAMPP : https://www.apachefriends.org/download.html
Install then open the file:
xamppapacheconfhttpd.conf
search for
<Directory />
Then after it add
Options FollowSymLinks +ExecCGI
So we have
<Directory />
Options FollowSymLinks +ExecCGI
Search for the next line and be sure that it’s not commented
LoadModule cgi_module modules/mod_cgi.so
Search for : AddHandler cgi-script
Then add ”.ring” to the supported cgi extensions
Example
AddHandler cgi-script .cgi .ring
Example
AddHandler cgi-script .cgi .pl .asp .ring
291
15. Ring Documentation, Release 1.4
Run/Start the server
Create your web applications in a directory supported by the web server.
Example:
Apache2.2htdocsmywebapplicationfolder
Example:
xampphtdocsmywebapplicationfolder
Inside the source code file (*.ring), Add this line
#!c:ringbinring.exe -cgi
Note: Change the previous line based on the path to ring.exe in your machine
44.2 Ring CGI Hello World Program
The next program is the Hello World program
#!c:ringbinring.exe -cgi
See "content-type : text/html" +nl+nl+
"Hello World!" + nl
44.3 Hello World Program using the Web Library
We can use the web library to write CGI Web applications quickly
Example (1) :
#!c:ringbinring.exe -cgi
Load "weblib.ring"
Import System.Web
New Page
{
Text("Hello World!")
}
Example (2) :
#!c:ringbinring.exe -cgi
Load "weblib.ring"
Import System.Web
WebPage()
{
Text("Hello World!")
}
44.2. Ring CGI Hello World Program 292
16. Ring Documentation, Release 1.4
Tip: the difference between ex. 1 and ex. 2 is using WebPage() function to return the page object instead of creating
the object using new statement.
44.4 Web Library Features
The next features are provided by the Web library to quickly create web applications.
• Generate HTML pages using functions
• Generate HTML pages using objects
• HTTP Get
• HTTP Post
• Files Upload
• URL Encode
• Templates
• CRUD MVC Sample
• Users Logic & Registration Sample
44.5 HTTP Get Example
The Page User Interface
#!c:ringbinring.exe -cgi
Load "weblib.ring"
Import System.Web
New Page
{
Title = "Test HTTP Get"
divstart([ :style = StyleSizeFull() ] )
boxstart()
text( "Test HTTP GET" )
newline()
boxend()
divstart([ :style = Styledivcenter("600px","550px") +
StyleGradient(21) ])
divstart([:style = stylefloatleft() + stylesize("100px","100%") +
stylecolor("black") + stylegradient(58)])
formstart("ex5.ring")
tablestart([ :style = stylesize("65%","90%") +
stylemarginleft("35%") +
stylemargintop("30%") ])
rowstart([])
cellstart([])
text ( "Name : " )
cellend()
cellstart([])
cTextboxStyle = StyleMarginLeft("5%") +
StyleWidth("250px") +
StyleColor("black") +
44.4. Web Library Features 293