text
stringlengths 454
608k
| url
stringlengths 17
896
| dump
stringclasses 91
values | source
stringclasses 1
value | word_count
int64 101
114k
| flesch_reading_ease
float64 50
104
|
|---|---|---|---|---|---|
Unless you have been living under a rock last two years, you have certainly heard about these buzz words around you. I am developing since a decade and I was never impatient to write a simple Hello World or Database select before. All it takes was just installing some software and copying few lines of code either from a book or internet, but now it took me a while to understand each of these technology stack and run some basic programs. Though basic program is not a typical scenario for these but it’s a good start to understand each towards building a complex scenario.
Disclaimer:
I am not a Linux guy; I develop applications on the windows operating system and it was initially tough for me to understand and remember simple commands. With this blog, I have followed all the hands on with my local Windows 10 machine running Hypervisor virtual machine.
If you are a beginner and looking forward to learn these technology buzz, I could help you here. The intention of this blog is not to dive deep into each but to give you an end to end experience. However, I will try to give some reference to learn more in detail.
Let me start with some terminologies,
Microservices.
To read more in detail.
Cluster is a group of servers and other resources that act like a single system and enable high availability and, in some cases, load balancing and parallel processing.
Now let’s look at the technology.
To read more in detail.
To read more in detail
As a developer when you want to develop day-to-day in your local machine, you need some software packages. Here I have listed then
Docker for Windows
An integrated, easy-to-deploy development environment for building, debugging and testing Docker apps on a Windows PC. Docker for Windows is a native Windows app deeply integrated with Hyper-V virtualization, networking and file system, making it the fastest and most reliable Docker environment for Windows.
Get it from
Kubernetes on Windows
I am not going to use the Kubernetes tool ‘minikube’ with this blog, as I chose to use another platform. If you are looking forward to work with Google Cloud Platform, you can start with minikube refer here, However irrespective of the local set up you use to develop, you can run the containerized production application anywhere as the base technology is docker.
OpenShift Origin.
Minishift is a tool that helps you run OpenShift locally by launching a single-node OpenShift cluster inside a virtual machine. With Minishift you can try out OpenShift or develop with it, day-to-day, on your local machine. You can run Minishift on Windows, Mac OS, and GNU/Linux operating systems. Minishift uses libmachine for provisioning virtual machines, and OpenShift Origin for running the cluster. Refer here
If you had followed my older blogs, I am always the fan of Redhat’s OpenShift because of the community, documentation and user experience. Here I choose to use Minishift over minikube because of some technical challenges I had on Minikube running with hyperV, where as Docker for windows need hyperV. But Minishift and Docker for windows both can run parallely on hyperV with no issues.
Get it from
Enough of talking, let’s get started.
If Hyper-V is not enabled, you can do it under Windows Features
Search -> Windows Features -> Turn Windows Features on or off
Install Docker for Windows and make sure it’s running
Look at the VM created at the Hyper-V Manager
Search -> Hyper-V Manager
Before you install MiniShift, you should add a Virtual Switch using the Hyper-V Manager. Make sure that you pair the virtual switch with a network card (wired or wireless) that is connected to the network.
In Hyper-V Manager, select Virtual Switch Manager… from the ‘Actions’ menu on the right.
Under the ‘Virtual Switches’ section, select New virtual network switch.
Under ‘What type of virtual switch do you want to create?’, select External.
Select the Create Virtual Switch button.
Under ‘Virtual Switch Properties’, give the new switch a name such as External VM Switch.
Under ‘Connection Type’, ensure that External Network has been selected.
Select the physical network card to be paired with the new virtual switch. This is the network card that is physically connected to the network.
Select Apply to create the virtual switch. At this point you will most likely see the following message.
Click Yes to continue.
Select OK to close the Virtual Switch Manager Window.
Place minishift.exe in the C: folder
Open Powershell as an Administrator and execute the following statement
On successful creation of minishift VM you get the server and login details
You can also view the minishift VM created under the Hyper-V Manager
You can access the OpenShift server using the web console via a the https URL
By default a project named ‘My Project’ is created, You can choose to create a new project.
Let’s start the real development. I would like to build a simple Hello World node app and containerize the same and build the image and deploy it to OpenShift Origin.
Create a folder in your C: drive where you can place all your apps. In my case I have created a folder ‘home’ in C: drive and a folder named ‘nodejs-docker-webapp’ for this app.
I have followed the example from nodejs , I don’t want to get in to details of the same. you can refer here
For the ease of development, I would suggest you to use the Docker for Windows initially and then you can change to Docker daemon on the minishift VM. Build your container based on the dockerfile from the current folder.
Run your container
and verify the output in your browser
Go back to your powershell as an Administrator
Execute the following command to get the Docker-Environment of minishift VM
.\minishift.exe docker-env and invoke expression to reuse the docker daemon of VM from the Docker client.
Now let’s quickly repeat the same steps on the minishift docker and check the image.
OpenShift Origin provides an Integrated Container Registry that adds the ability to provision new image repositories on the fly. Whenever a new image is pushed to the integrated registry, the registry notifies OpenShift Origin about the new image, passing along all the information about it, such as the namespace, name, and image metadata.
All the docker images should be tagged and pushed to the Integrated Registry, so they will be available for deployment as an Image Stream in the Web Console.
The syntax for the tag should be docker tag <imageid> <registryip:port>/<projectname>/<appname>
You could also combine this step with the docker build statement as docker build -t <registryip:port>/<projectname>/<appname> .
To login to Integrated Registry for pushing the image, we need the token from OpenShift Origin, we can get the same using OpenShift Client command line
Use the command oc whoami -t to get the token and use the same in the docker login command and push the image.
We are done and now let’s deploy the application on the Web Console. You can also open the Web console using the command
PS C:\> .\minishift.exe console
On the web console, navigate to your project and click on ‘Add to Project’ -> Deploy Image
Select the Project, app and version on the Image Stream Tag.
With no change to any of the properties, just click on Create.
Navigate to the overview page.
Next step is to create a default route to access the app, just click on the Create Route link
Click on Create. The route will be updated on the overview page. You can access this application using the route.
You can scale up and scale down your application by increasing or decreasing the number of pods on the overview page. Pod is the basic building block of Kubernetes–the smallest and simplest unit in the Kubernetes object model that you create or deploy. A Pod represents a running process on your cluster. When making a connection to a service, OpenShift will automatically route the connection to one of the pods associated with that service.
Let’s quickly recap what we did.
- We developed a simple Hello World node application. We build and tested the same locally, containerized it using Docker for windows.
- Build a local OpenShift Cluster using MiniShift and rebuild the app image using the MiniShift Docker daemon.
- We pushed the image to Integrated registry and deployed the same using Image Stream in web console and looked the scale up and scale down options.You can group two services together depends on the dependancies.
You can also push your images to Docker hub, or using Google Cloud SDK easily deploy these images in to your Google cloud engine or any other cloud platform like AWS or Azure.
Before as a developer I was never bothered about how DevOps works, how scaling happens, and efficiency in maintenance and security. With Microservices architecture each microservice team is responsible for the entire business process. Technology is moving fast, especially SAP moving towards cloud company we don’t talk anymore about quarterly or monthly releases; we deliver the services over night or even on an hourly basis.
Feel free to share your comments and suggesstion. I am also in the process of learning these new concepts and technology and I am open to learn together.
Thanks for this really informative piece.
Very nice blog! You delivered on your promise….NOT a deep dive but is a good “dip your toes in the water” introduction….and you made it easy to understand and follow. THANKS for this and looking forward to more from you!
Thank you @christopher.solomon
|
https://blogs.sap.com/2017/04/17/microservices-containers-images-cluster-...-and-what-not/
|
CC-MAIN-2018-51
|
refinedweb
| 1,637
| 61.56
|
- NAME
- qw(:pushpop); print PUSHCOLOR RED ON_GREEN "This text is red on green.\n"; print PUSHCOLOR BRIGHT_BLUE "This text is bright blue on green.\n"; print RESET BRIGHT_BLUE "This text is just bright";).
Unfortunately, interpretation of colors 0 through 7 often depends on whether the emulator supports eight colors or sixteen colors. Emulators that only support eight colors (such as the Linux console) will display colors 0 through 7 with normal brightness and ignore colors 8 through 15, treating them the same as white. Emulators that support 16 colors, such as gnome-terminal, normally display colors 0 through 7 as dim or darker versions and colors 8 through 15 as normal brightness. On such emulators, the "normal" white (color 7) usually is shown as pale grey, requiring bright white (15) to be used to get a real white color. Bright black usually is a dark grey color, although some terminals display it as pure black. Some sixteen-color terminal emulators also treat normal yellow (color 3) as orange or brown, and bright yellow (color 11) as yellow.
Following the normal convention of sixteen-color emulators, this module provides a pair of attributes for each color. For every normal color (0 through 7), the corresponding bright color (8 through 15) is obtained by prepending the string
bright_ to the normal color name. For example,
red is color 1 and
bright_red is color 9. The same applies for background colors:
on_red is the normal color and
on_bright_red is the bright color. Capitalize these strings for the constant interface., which makes the choice of colors difficult. The most conservative choice is to use only the regular colors, which are at least displayed on all emulators. However, they will appear dark in sixteen-color terminal emulators, including most common emulators in UNIX X environments. If you know the display is one of those emulators, you may wish to use the bright variants instead. Even better, offer the user a way to configure the colors for a given application to fit their terminal emulator.
Function Interface
The function interface uses attribute strings to describe the colors and text attributes to assign to text. The recognized non-color attributes are clear, reset, bold, dark, faint, italic, underline, underscore, blink, reverse, and concealed. Clear and reset (reset to default attributes), dark and faint (dim and saturated), and underline and underscore are equivalent, so use whichever is the most intuitive to you.
Note that not all attributes are supported by all terminal types, and some terminals may not support any of these sequences. Dark and faint, italic, blink, and concealed in particular are frequently not implemented.
The recognized normal foreground color attributes (colors 0 to 7) are:
black red green yellow blue magenta cyan white
The corresponding bright foreground color attributes (colors 8 to 15) are:
bright_black bright_red bright_green bright_yellow bright_blue bright_magenta bright_cyan bright_white
The recognized normal background color attributes (colors 0 to 7) are:
on_black on_red on_green on yellow on_blue on_magenta on_cyan on_white
The recognized bright background color attributes (colors 8 to 15) are:
on_bright_black on_bright_red on_bright_green on_bright_yellow on_bright_blue on_bright_magenta on_bright_cyan on_bright_white R, G, and B values from 0 to 5.
For any of the above listed attributes, case is not significant.
Attributes, once set, last until they are unset (by printing the attribute
clear or
reset). Be careful to do this, or otherwise your attribute will last after your script is done running, and people get very annoyed at having their prompt and typing changed to weird colors.
- color(ATTR[, ATTR ...]).
- colored(STRING, ATTR[, ATTR ...])
-
- colored(ATTR-REF, STRING[, STRING...])
As an aid in resetting colors,.
- uncolor(ESCAPE)
uncolor() performs the opposite translation as color(), turning escape sequences into a list of strings corresponding to the attributes being set by those sequences.
- UNDERLINE UNDERSCORE BLINK REVERSE CONCEALED BLACK RED GREEN YELLOW BLUE MAGENTA CYAN WHITE BRIGHT_BLACK BRIGHT_RED BRIGHT_GREEN BRIGHT_YELLOW BRIGHT_BLUE BRIGHT_MAGENTA BRIGHT_CYAN BRIGHT_WHITE ON_BLACK ON_RED ON_GREEN ON_YELLOW ON_BLUE ON_MAGENTA ON_CYAN ON_WHITE ON_BRIGHT_BLACK ON_BRIGHT_RED ON_BRIGHT_GREEN ON_BRIGHT_YELLOW ON_BRIGHT_BLUE ON_BRIGHT_MAGENTA ON_BRIGHT_CYAN ON_BRIGHT_WHITE.) subroutine interface has the advantage over the constants interface in that only two subroutines are exported into your namespace, versus thirty-eight.
The Color Stack., 2013, 2014 Russ Allbery <rra@cpan.org>. Copyright 2012 Kurt Starsinic <kstarsinic@gmail.com>.. 256-color control sequences are documented at (search for 256-color).
The current version of this module is always available from its web site at. It is also part of the Perl core distribution as of 5.6.0.
|
https://metacpan.org/pod/release/RRA/Term-ANSIColor-4.03/lib/Term/ANSIColor.pm
|
CC-MAIN-2016-50
|
refinedweb
| 741
| 53.21
|
Blueprints
Daniel Furtado
Marcus Pennington
BIRMINGHAM - MUMBAI
Python Programming-78646-816-1
I dedicate this book to my family—my sister, Camila, my mother, Silvia, and my father, Simão,
who have done everything in their power to help me achieve all my dreams. There are no words
to express how grateful and lucky I feel for being their child.
To my lovely Maria, who every day gives me strength, encouragement, inspiration, and love. I
wouldn't have made it without you. I love you! Also, to my loyal French bulldog friends, Edit
and Ella.
– Daniel Furtado
My parents, Dawn and Robert, who over my lifetime have always pushed me to do my best.
They instilled in me the ability to accomplish anything I put my mind to.
Fabrizio Romano for convincing me to contribute to this book. He is the greatest mentor an
aspiring developer could ask for.
And finally, my partner, Emily, for always being there for me.
– Marcus Pennington
Contributors
He joined the Bioinformatics Laboratory of the Human Cancer Genome Project in Brazil,
where he developed web applications and tools in Perl and Python to help researchers
analyze data. He has never stopped developing in Python ever since.
Daniel has worked on various open source projects; the latest one is a PyTerrier web micro-
framework.
Marcus Pennington started his journey into computer science at Highams Park Sixth Form
College where he took a Cisco CCNA course.
I would like to acknowledge Tom Viner for giving my chapters a thorough review; his
insights not only improved the quality of my chapters but also taught me a great deal.
Julio Trigo, an expert at using PostgreSQL with Python; his knowledge supplemented my
own when creating the database dependency.
Edward Melly, a JavaScript and React craftsman, for reviewing the frontend code in my
chapters.
About the reviewers
Tom Viner is a senior software developer living in London. He has over 10 years of
experience in building web applications and has been using Python and Django for 8 years.
He has special interests in open source software, web security, and Test-driven
development.
Tom has given two conference talks, Testing with two failure seeking missiles: fuzzing
and property based testing and Exploring unit-testing, unittest v pytest: FIGHT!
Tom works for Sohonet in central London and sometimes goes backpacking around the
world.
I would like to thank Marcus Pennington for inviting me to review this book.
Radovan Kavický is the principal data scientist and president at GapData Institute based in
Bratislava, Slovakia, harnessing the power of data and wisdom of economics for public
good..
Table of Contents
Preface 1
[ ii ]
Table of Contents
[ iii ]
Table of Contents
[ iv ]
Table of Contents
[v]
Table of Contents
Summary 401
Chapter 9: Notification Serverless Application 402
Setting up the environment 403
Setting up the Amazon Web Services CLI 403
Configuring a Simple Email Service 405
Registering the emails 406
Creating an S3 bucket 407
Implementing the notification service 407
Deploying the application with Zappa 415
Restricting access to the API's endpoints 417
Modifying the order service 421
Testing all the pieces together 425
Summary 429
Other Books You May Enjoy 430
Index 433
[ vi ]
Preface
If you have been within the software development industry for the last 20 years, you most
certainly have heard of a programming language named Python. Created by Guido van
Rossum, Python first appeared in 1991 and has captured the hearts of many software
developers across the globe ever since.
However, how is it that a language that is over 20 years old is still around and is gaining
more and more popularity every day?
Well, the answer to this question is simple. Python is awesome for everything (or almost
everything). Python is a general-purpose programming language, which means that you
can create simple terminal applications, web applications, microservices, games, and also
complex scientific applications. Even though it is possible to use Python for different
purposes, Python is a language that is well known for being easy to learn, which is perfect
for beginners as well as people with no computer science background.
Python is a batteries included programming language, which means that most of the time you
will not need to make use of any external dependencies when developing your projects.
Python's standard library is feature rich and most of the time contains everything you need
to create your programs, and just in case you need something that is not in the standard
library, the PyPI (Python Package Index) currently contains 117,652 packages.
The Python community is welcoming, helpful, diverse, and extremely passionate about the
language, and everyone in the community is always happy to help each other.
If you still not convinced, the popular website StackOverflow published this year's statistics
about the popularity of programming languages based on the number of questions the
users add to the site, and Python is one of the top languages, only behind JavaScript, Java,
C#, and PHP.
Chapter 2, Creating a Remote-Control Application with Spotify, will teach you how to perform
authentication with the Spotify API using OAuth. We will use the curses library to make the
application more interesting and user-friendly.
Chapter 3, Casting Votes on Twitter, will teach you how to use the Tkinter library to create
beautiful user interfaces using Python. We will use Reactive Extensions for Python to detect
when a vote has been made in the backend, after which, we will publish the changes in the
user interface.
Chapter 4, Exchange Rates and the Currency Conversion Tool, will enable you to implement a
currency converter that will get foreign exchange rates in real time from different sources
and use the data to perform currency conversion. We will develop an API that contains
helper functions to perform the conversions. To start with, we will use opensource foreign
exchange rates and a currency conversion API ().
The second part of the chapter will teach you how to create a command-line application
makes use of our API to fetch data from the data sources and also get the currency
conversion results with a few parameters.
Chapter 5, Building a Web Messenger with Microservices, will teach you how to use Nameko,
a microservice framework for Python. You will also learn how to make dependency
providers for external resources such as Redis. This chapter will also touch upon integration
testing Nameko services and basic AJAX requests to an API.
Chapter 6, Extending TempMessenger with a User Authentication Microservice, will build upon
your app from Chapter 5, Building a Web Messenger with Microservices. You will create a user
authentication microservice that stores users in a Postgres database. Using Bcrypt, you will
also learn how to store passwords in a database securely. This chapter also covers creating a
Flask web interface and how to utilize cookies to store web session data. By the end of these
chapters, you will be well equipped to create scalable and cohesive microservices.
[2]
Preface
Chapter 7, Online Video Game Store with Django, will enable you to create an online video
game store. It will contain features such as browsing video games by category, performing
searches using different criteria, viewing detailed information about each game, and finally
adding games to a shopping cart and placing an order. Here, you will learn about Django
2.0, the administration UI, the Django data model, and much more.
Chapter 8, Order Microservice, will help you build a microservice that will be responsible for
receiving orders from the web application that we developed in the previous chapter. The
order microservice also provides other features such as the ability to update the status of
orders and provide order information using different criteria.
Chapter 9, Notification Serverless Application, will teach you about Serverless functions
architecture and how to build a notification service using Flask and deploy the final
application to AWS Lambda using the great project Zappa. You will also learn how to
integrate the web application that was developed in Chapter 7, Online Video Game Store with
Django, and the order microservice developed in Chapter 8, Order Microservice, with the
serverless notification application.
An internet connection
Virtualenv
Python 3.6
MongoDB 3.2.11
pgAdmin (refer to the official documentation at
pgadmin for installation instructions)
Docker (refer to the official documentation at
docker-install for installation instructions)
[3]
Preface
Once the file is downloaded, please make sure that you unzip or extract the folder using the
latest version of:
The code bundle for the book is also hosted on GitHub at
PacktPublishing/Python-Programming-Blueprints.: "This method will call the method exec of the Runner to execute the function that
performs the requests to the Twitter API."
[4]
Preface
When we wish to draw your attention to a particular part of a code block, the relevant lines
or items are set in bold:
def start_app(args):
root = Tk()
app = Application(hashtags=args.hashtags, master=root)
app.master.title("Twitter votes")
app.master.geometry("400x700+100+100")
app.mainloop()
Bold: Indicates a new term, an important word, or words that you see onscreen. For
example, words in menus or dialog boxes appear in the text like this. Here is an example: "It
says, Logged as with your username, and right after it there is a logout link. Give it a go,
and click on the link Log off"
[5]
Preface!
[6]
Implementing the Weather
1
Application
The first application in this book is going to be a web scraping application that will scrape
weather forecast information from and present it in a terminal. We
will add some options that can be passed as arguments to the application, such as:
Before we get started, it is important to say that when developing web scraping
applications, you should keep in mind that these types of applications are susceptible to
changes. If the developers of the site that you are getting data from change a CSS class
name, or the structure of the HTML DOM, the application will stop working. Also, if the
URL of the site we are getting the data from changes, the application will not be able to
send requests.
Virtual environments in Python are a broad subject, and beyond the scope of this book.
However, if you are not familiar with virtual environments, it will suffice to know that a
virtual environment is a contained Python environment that is isolated from your global
Python installation. This isolation allows developers to easily work with different versions
of Python, install packages within the environment, and manage project dependencies
without interfering with Python's global installation.
Python's installation comes with a module called venv, which you can use to create virtual
environments; the syntax is fairly straightforward. The application that we are going to
create is called weatherterm (weather terminal), so we can create a virtual environment
with the same name to make it simple.
To create a new virtual environment, open a terminal and run the following command:
$ python3 -m venv weatherterm
If everything goes well, you should see a directory called weatherterm in the directory you
are currently at. Now that we have the virtual environment, we just need to activate it with
the following command:
$ . weatherterm/bin/activate
[8]
Implementing the Weather Application Chapter 1
Now, we need to create a directory where we are going to create our application. Don't
create this directory in the same directory where you created the virtual environment;
instead, create a projects directory and create the directory for the application in there. I
would recommend you name it with the same name as the virtual environment for
simplicity.
Go into the project's directory that you just created and create a file named
requirements.txt with the following content:
beautifulsoup4==4.6.0
selenium==3.6.0
These are all the dependencies that we need for this project:
BeautifulSoup: This is a package for parsing HTML and XML files. We will be
using it to parse the HTML that we fetch from weather sites and to get the
weather data we need on the terminal. It is very simple to use and it has a great
documentation available online at:
en/latest/.
Selenium: This is a well-known set of tools for testing. There are many
applications, but it is mostly used for the automated testing of web applications.
To install the required packages in our virtual environment, you can run the following
command:
pip install -r requirements.txt
[9]
Implementing the Weather Application Chapter 1
One last tool that we need to install is PhantomJS; you can download it from: http://
phantomjs.org/download.html
After downloading it, extract the contents inside the weatherterm directory and rename
the folder to phantomjs.
With our virtual environment set up and PhantomJS installed, we are ready to start coding!
Core functionality
Let's start by creating a directory for your module. Inside of the project's root directory,
create a subdirectory called weatherterm. The subdirectory weatherterm is where our
module will live. The module directory needs two subdirectories - core and parsers. The
project's directory structure should look like this:
weatherterm
├── phantomjs
└── weatherterm
├── core
├── parsers
Create a file with a class implementing the methods for fetching the current
weather forecast as well as five-day, ten-day, and weekend weather forecasts
The file name has to end with parser, for example, weather_com_parser.py
The file name can't start with double underscores
[ 10 ]
Implementing the Weather Application Chapter 1
With that said, let's go ahead and create the parser loader. Create a file named
parser_loader.py inside of the weatherterm/core directory and add the following
content:
import os
import re
import inspect
def _get_parser_list(dirname):
files = [f.replace('.py', '')
for f in os.listdir(dirname)
if not f.startswith('__')]
return files
def _import_parsers(parserfiles):
m = re.compile('.+parser$', re.I)
_modules = __import__('weatherterm.parsers',
globals(),
locals(),
parserfiles,
0)
_classes = dict()
for k, v in _parsers:
_classes.update({k: v for k, v in inspect.getmembers(v)
if inspect.isclass(v) and m.match(k)})
return _classes
def load(dirname):
parserfiles = _get_parser_list(dirname)
return _import_parsers(parserfiles)
[ 11 ]
Implementing the Weather Application Chapter 1
First, the _get_parser_list function is executed and returns a list of all files located in
weatherterm/parsers; it will filter the files based on the rules of the parser described
previously. After returning a list of files, it is time to import the module. This is done by the
_import_parsers function, which first imports the weatherterm.parsers module and
makes use of the inspect package in the standard library to find the parser classes within the
module.
The inspect.getmembers function returns a list of tuples where the first item is a key
representing a property in the module, and the second item is the value, which can be of
any type. In our scenario, we are interested in a property with a key ending with
parser and with the value of type class.
Lastly, we loop through the items in the module and extract the parser classes, returning a
dictionary containing the name of the class and the class object that will be later used to
create instances of the parser.
@unique
class ForecastType(Enum):
[ 12 ]
Implementing the Weather Application Chapter 1
TODAY = 'today'
FIVEDAYS = '5day'
TENDAYS = '10day'
WEEKEND = 'weekend'
Enumerations have been in Python's standard library since version 3.4 and they can be
created using the syntax for creating classes. Just create a class inheriting from enum.Enum
containing a set of unique properties set to constant values. Here, we have values for the
four types of forecast that the application will provide, and where values such
as ForecastType.TODAY, ForecastType.WEEKEND, and so on can be accessed.
Note that we are assigning constant values that are different from the property item of the
enumeration, the reason being that later these values will be used to build the URL to make
requests to the weather website.
The application needs one more enumeration to represent the temperature units that the
user will be able to choose from in the command line. This enumeration will contain Celsius
and Fahrenheit items.
First, let's include a base enumeration. Create a file called base_enum.py in the
weatherterm/core directory with the following contents:
class BaseEnum(Enum):
def _generate_next_value_(name, start, count, last_value):
return name
BaseEnum is a very simple class inheriting from Enum . The only thing we want to do here
is override the method _generate_next_value_ so that every enumeration that inherits
from BaseEnum and has properties with the value set to auto() will automatically get the
same value as the property name.
[ 13 ]
Implementing the Weather Application Chapter 1
Now, we can create an enumeration for the temperature units. Create a file called unit.py
in the weatherterm/core directory with the following content:
from enum import auto, unique
@unique
class Unit(BaseEnum):
CELSIUS = auto()
FAHRENHEIT = auto()
This class inherits from the BaseEnum that we just created, and every property is set to
auto(), meaning the value for every item in the enumeration will be set automatically for
us. Since the Unit class inherits from BaseEnum, every time the auto() is called,
the _generate_next_value_ method on BaseEnum will be invoked and will return the
name of the property itself.
Before we try this out, let's create a file called __init__.py in the weatherterm/core
directory and import the enumeration that we just created, like so:
from .unit import Unit
If we load this class in the Python REPL and check the values, the following will occur:
Python 3.6.2 (default, Sep 11 2017, 22:31:28)
[GCC 6.3.0 20170516] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from weatherterm.core import Unit
>>> [value for key, value in Unit.__members__.items()]
[<Unit.CELSIUS: 'CELSIUS'>, <Unit.FAHRENHEIT: 'FAHRENHEIT'>]
Another item that we also want to add to the core module of our application is a class to
represent the weather forecast data that the parser returns. Let's go ahead and create a file
named forecast.py in the weatherterm/core directory with the following contents:
from datetime import date
class Forecast:
def __init__(
self,
current_temp,
[ 14 ]
Implementing the Weather Application Chapter 1
humidity,
wind,
high_temp=None,
low_temp=None,
description='',
forecast_date=None,
forecast_type=ForecastType.TODAY):
self._current_temp = current_temp
self._high_temp = high_temp
self._low_temp = low_temp
self._humidity = humidity
self._wind = wind
self._description = description
self._forecast_type = forecast_type
if forecast_date is None:
self.forecast_date = date.today()
else:
self._forecast_date = forecast_date
@property
def forecast_date(self):
return self._forecast_date
@forecast_date.setter
def forecast_date(self, forecast_date):
self._forecast_date = forecast_date.strftime("%a %b %d")
@property
def current_temp(self):
return self._current_temp
@property
def humidity(self):
return self._humidity
@property
def wind(self):
return self._wind
@property
def description(self):
return self._description
def __str__(self):
temperature = None
offset = ' ' * 4
[ 15 ]
Implementing the Weather Application Chapter 1
if self._forecast_type == ForecastType.TODAY:
temperature = (f'{offset}{self._current_temp}\xb0\n'
f'{offset}High {self._high_temp}\xb0 / '
f'Low {self._low_temp}\xb0 ')
else:
temperature = (f'{offset}High {self._high_temp}\xb0 / '
f'Low {self._low_temp}\xb0 ')
return(f'>> {self.forecast_date}\n'
f'{temperature}'
f'({self._description})\n'
f'{offset}Wind: '
f'{self._wind} / Humidity: {self._humidity}\n')
In the Forecast class, we will define properties for all the data we are going to parse:
We can also implement two methods called forecast_date with the decorators
@property and @forecast_date.setter . The @property decorator will turn the
method into a getter for the _forecast_date property of the Forecast class, and the
@forecast_date.setter will turn the method into a setter. The setter was defined here
because, every time we need to set the date in an instance of Forecast, we need to make
sure that it will be formatted accordingly. In the setter, we call the strftime method,
passing the format codes %a (weekday abbreviated name), %b (monthly abbreviated name),
and %d (day of the month).
[ 16 ]
Implementing the Weather Application Chapter 1
The format codes %a and %b will use the locale configured in the machine
that the code is running on.
Lastly, we override the __str__ method to allow us to format the output the way we
would like when using the print, format, and str functions.
class UnitConverter:
def __init__(self, parser_default_unit, dest_unit=None):
self._parser_default_unit = parser_default_unit
self.dest_unit = dest_unit
self._convert_functions = {
Unit.CELSIUS: self._to_celsius,
Unit.FAHRENHEIT: self._to_fahrenheit,
}
@property
def dest_unit(self):
return self._dest_unit
@dest_unit.setter
def dest_unit(self, dest_unit):
self._dest_unit = dest_unit
try:
temperature = float(temp)
except ValueError:
return 0
if (self.dest_unit == self._parser_default_unit or
self.dest_unit is None):
return self._format_results(temperature)
func = self._convert_functions[self.dest_unit]
[ 17 ]
Implementing the Weather Application Chapter 1
result = func(temperature)
return self._format_results(result)
This is the class that is going to make the temperature conversions from Celsius to
Fahrenheit and vice versa. The initializer of this class gets two arguments; the default unit
used by the parser and the destination unit. In the initializer, we will define a dictionary
containing the functions that will be used for temperature unit conversion.
The convert method only gets one argument, the temperature. Here, the temperature is a
string, so the first thing we need to do is try converting it to a float value; if it fails, it will
return a zero value right away.
You can also verify whether the destination unit is the same as the parser's default unit or
not. In that case, we don't need to continue and perform any conversion; we simply format
the value and return it.
The code snippet below shows the _format_results method, which is a utility method
that will format the temperature value for us:
return int(value) if value.is_integer() else f'{value:.1f}'
[ 18 ]
Implementing the Weather Application Chapter 1
Now, we only need to edit the __init__.py file in the weatherterm/core directory and
include the following import statements:
from .base_enum import BaseEnum
from .unit_converter import UnitConverter
from .forecast_type import ForecastType
from .forecast import Forecast
class Request:
def __init__(self, base_url):
self._phantomjs_path = os.path.join(os.curdir,
'phantomjs/bin/phantomjs')
self._base_url = base_url
self._driver = webdriver.PhantomJS(self._phantomjs_path)
return self._driver.page_source
This class is very simple; the initializer defines the base URL and creates a PhantomJS
driver, using the path where PhantomJS is installed. The fetch_data method formats the
URL, adding the forecast option and the area. After that, the webdriver performs a request
and returns the page source. If the title of the markup returned is 404 Not Found, it will
raise an exception. Unfortunately, Selenium doesn't provide a proper way of getting the
HTTP Status code; this would have been much better than comparing strings.
[ 19 ]
Implementing the Weather Application Chapter 1
You may notice that I prefix some of the class properties with an
underscore sign. I usually do that to show that the underlying property is
private and shouldn't be set outside the class. In Python, there is no need
to do that because there's no way to set private or public properties;
however, I like it because I can clearly show my intent.
Now we have a parser loader to load any parser that we drop into the directory
weatherterm/parsers, we have a class representing the forecast model, and an
enumeration ForecastType so we can specify which type of forecast we are parsing. The
enumeration represents temperature units and utility functions to convert temperatures
from Fahrenheit to Celsius and Celsius to Fahrenheit. So now, we should be ready
to create the application's entry point to receive all the arguments passed by the user, run
the parser, and present the data on the terminal.
We want to give the users of our application the best user experience possible, so the first
features that we need to add are the ability to receive and parse command line arguments,
perform argument validation, set arguments when needed, and, last but not least, show an
organized and informative help system so the users can see which arguments can be used
and how to use the application.
Luckily, Python has batteries included and the standard library contains a great module
that allows us to implement this in a very simple way; the module is called argparse.
Another feature that would be good to have is for our application to be easy to distribute to
our users. One approach is to create a __main__.py file in the weatherterm module
directory, and you can run the module as a regular script. Python will automatically run
the __main__.py file, like so:
$ python -m weatherterm
[ 20 ]
Implementing the Weather Application Chapter 1
Another option is to zip the entire application's directory and execute the Python passing
the name of the ZIP file instead. This is an easy, fast, and simple way to distribute our
Python programs.
There are many other ways of distributing your programs, but they are beyond the scope of
this book; I just wanted to give you some examples of the usage of the __main__.py file.
With that said, let's create a __main__.py file inside of the weatherterm directory with the
following content:
import sys
from argparse import ArgumentParser
def _validate_forecast_args(args):
if args.forecast_option is None:
err_msg = ('One of these arguments must be used: '
'-td/--today, -5d/--fivedays, -10d/--tendays, -
w/--weekend')
print(f'{argparser.prog}: error: {err_msg}',
file=sys.stderr)
sys.exit()
parsers = parser_loader.load('./weatherterm/parsers')
argparser = ArgumentParser(
prog='weatherterm',
description='Weather info from weather.com on your terminal')
required.add_argument('-p', '--parser',
choices=parsers.keys(),
required=True,
dest='parser',
help=('Specify which parser is going to be
used to '
'scrape weather information.'))
argparser.add_argument('-u', '--unit',
[ 21 ]
Implementing the Weather Application Chapter 1
choices=unit_values,
required=False,
dest='unit',
help=('Specify the unit that will be used to
display '
'the temperatures.'))
required.add_argument('-a', '--areacode',
required=True,
dest='area_code',
help=('The code area to get the weather
broadcast from. '
'It can be obtained at'))
argparser.add_argument('-v', '--version',
action='version',
version='%(prog)s 1.0')
argparser.add_argument('-td', '--today',
dest='forecast_option',
action='store_const',
const=ForecastType.TODAY,
help='Show the weather forecast for the
current day')
args = argparser.parse_args()
_validate_forecast_args(args)
cls = parsers[args.parser]
parser = cls()
results = parser.run(args)
The weather forecast options (today, five days, ten days, and weekend forecast) that our
application will accept will not be required; however, at least one option must be provided
in the command line, so we create a simple function called _validate_forecast_args to
perform this validation for us. This function will show a help message and exit the
application.
First, we get all the parsers available in the weatherterm/parsers directory. The list of
parsers will be used as valid values for the parser argument.
[ 22 ]
Implementing the Weather Application Chapter 1
It is the ArgumentParser object that does the job of defining the parameters, parsing the
values, and showing help, so we create an instance of ArgumentParser and also create an
argument group for the required parameters. This will make the help output look much
nicer and organized.
In order to make the parameters and the help output more organized, we are going to
create a group within the ArgumentParser object. This group will contain all the required
arguments that our application needs. This way, the users of our application can easily see
which parameters are required and the ones that are not required.
After creating the argument group for the required arguments, we get a list of all members
of the enumeration Unit and use the title() function to make only the first letter a capital
letter.
Now, we can start adding the arguments that our application will be able to receive on the
command line. Most argument definitions use the same set of keyword arguments, so I will
not be covering all of them.
Let's break down every parameter of the add_argument used when creating the parser
flag:
The first two parameters are the flags. In this case, the user passes a value to this
argument using either -p or --parser in the command line, for example, --
parser WeatherComParser.
The choices parameter specifies a list of valid values for that argument that we
are creating. Here, we are using parsers.keys(), which will return a list of
parser names. The advantage of this implementation is that if we add a new
parser, it will be automatically added to this list, and no changes will be required
in this file.
[ 23 ]
Implementing the Weather Application Chapter 1
The required parameter, as the name says, specifies if the argument will be
required or not.
The dest parameter specifies the name of the attribute to be added to the
resulting object of the parser argument. The object returned
by parser_args() will contain an attribute called parser with the value that
we passed to this argument in the command line.
Finally, the help parameter is the argument's help text, shown when using the -h
or --help flag.
Here we have two keyword arguments that we haven't seen before, action and const.
Actions can be bound to the arguments that we create and they can perform many things.
The argparse module contains a great set of actions, but if you need to do something
specific, you can create your own action that will meet your needs. Most actions defined in
the argparse module are actions to store values in the parse result's object attributes.
In the previous code snippet, we use the store_const action, which will store a constant
value to an attribute in the object returned by parse_args().
We also used the keyword argument const, which specifies the constant default value
when the flag is used in the command line.
Remember that I mentioned that it is possible to create custom actions? The argument unit
is a great use case for a custom action. The choices argument is just a list of strings, so we
use this comprehension to get the list of names of every item in the Unit enumeration, as
follows:
unit_values = [name.title() for name, value in
Unit.__members__.items()]
required.add_argument('-u', '--unit',
choices=unit_values,
required=False,
dest='unit',
help=('Specify the unit that will be used to
[ 24 ]
Implementing the Weather Application Chapter 1
display '
'the temperatures.'))
The object returned by parse_args() will contain an attribute called unit with a string
value (Celsius or Fahrenheit), but this is not exactly what we want. Wouldn't it be nice
to have the value as an enumeration item instead? We can change this behavior by creating
a custom action.
class SetUnitAction(Action):
This action class is very simple; it just inherits from argparse.Action and overrides
the __call__ method, which will be called when the argument value is parsed. This is
going to be set to the destination attribute.
The values parameter is the value that the user has passed on the command line; in our
case, it can be either Celsius or Fahrenheit. Lastly, the option_string parameter is the flag
defined for the argument. For the unit argument, the value of option_string will be -u.
Fortunately, enumerations in Python allow us to access their members and attributes using
item access:
Unit[values.upper()]
[ 25 ]
Implementing the Weather Application Chapter 1
After getting the correct enumeration member, we set the value of the property specified by
self.dest in the namespace object. That is much cleaner and we don't need to deal with
magic strings.
With the custom action in place, we need to add the import statement in
the __init__.py file in the weatherterm/core directory:
from .set_unit_action import SetUnitAction
Just include the line above at the end of the file. Then, we need to import it into the
__main__.py file, like so:
And we are going to add the action keyword argument in the definition of the unit
argument and set it to SetUnitAction, like so:
required.add_argument('-u', '--unit',
choices=unit_values,
required=False,
action=SetUnitAction,
dest='unit',
help=('Specify the unit that will be used to
display '
'the temperatures.'))
So, when the user of our application uses the flag -u for Celsius, the value of the attribute
unit in the object returned by the parse_args() function will be:
<Unit.CELSIUS: 'CELSIUS'>
The rest of the code is very straightforward; we invoke the parse_args function to parse
the arguments and set the result in the args variable. Then, we use the value of
args.parser (the name of the selected parser) and access that item in the parser's
dictionary. Remember that the value is the class type, so we create an instance of the parser,
and lastly, invoke the method run, which will kick off website scraping.
[ 26 ]
Implementing the Weather Application Chapter 1
class WeatherComParser:
def __init__(self):
self._forecast = {
ForecastType.TODAY: self._today_forecast,
ForecastType.FIVEDAYS:
self._five_and_ten_days_forecast,
ForecastType.TENDAYS: self._five_and_ten_days_forecast,
ForecastType.WEEKEND: self._weekend_forecast,
}
[ 27 ]
Implementing the Weather Application Chapter 1
The run method only does two things; it looks up the function that needs to be executed
using the forecast_option that we passed as an argument in the command line, and
executes the function returning its value.
Now, the application is finally ready to be executed for the first time if you run the
command in the command line:
$ python -m weatherterm --help
optional arguments:
-h, --help show this help message and exit
-u {Celsius,Fahrenheit}, --unit {Celsius,Fahrenheit}
Specify the unit that will be used to display
the temperatures.
-v, --version show program's version number and exit
-td, --today Show the weather forecast for the current day
require arguments:
-p {WeatherComParser}, --parser {WeatherComParser}
Specify which parser is going to be used to scrape
weather information.
-a AREA_CODE, --areacode AREA_CODE
The code area to get the weather broadcast from. It
can be obtained at
As you can see, the ArgumentParse module already provides out-of-the-box output for
help. There are ways you can customize the output how you want to, but I find the default
layout really good.
Notice that the -p argument already gave you the option to choose the
WeatherComParser. It wasn't necessary to hardcode it anywhere because the parser loader
did all the work for us. The -u (--unit) flag also contains the items of the enumeration
Unit. If someday you want to extend this application and add new units, the only thing
you need to do here is to add the new item to the enumeration, and it will be automatically
picked up and included as an option for the -u flag.
[ 28 ]
Implementing the Weather Application Chapter 1
Now, if you run the application again and this time pass some parameters:
$ python -m weatherterm -u Celsius -a SWXX2372:1:SW -p WeatherComParser -td
Don't worry -- this is exactly what we wanted! If you follow the stack trace, you can see that
everything is working as intended. When we run our code, we call the run method on the
selected parser from the __main__.py file, then we select the method associated with the
forecast option, in this case, _today_forecast, and finally store the result in the
forecast_function variable.
When the function stored in the forecast_function variable was executed, the
NotImplementedError exception was raised. So far so good; the code is working perfectly
and now we can start adding the implementation for each of these methods.
[ 29 ]
Implementing the Weather Application Chapter 1
Since I am in Sweden, I will use the area code SWXX2372:1:SW (Stockholm, Sweden);
however, you can use any area code you want. To get the area code of your choice, go to and search for the area you want. After selecting the area, the
weather forecast for the current day will be displayed. Note that the URL changes, for
example, when searching Stockholm, Sweden, the URL changes to:
Note that there is only one part of the URL that changes, and this is the area code that we
want to pass as an argument to our application.
self._temp_regex = re.compile('([0-9]+)\D{,2}([0-9]+)')
self._only_digits_regex = re.compile('[0-9]+')
self._unit_converter = UnitConverter(Unit.FAHRENHEIT)
In the initializer, we define the URL template we are going to use to perform requests to the
weather website; then, we create a Request object. This is the object that will perform the
requests for us.
Regular expressions are only used when parsing today's weather forecast temperatures.
[ 30 ]
Implementing the Weather Application Chapter 1
We also define a UnitConverter object and set the default unit to Fahrenheit.
Now, we are ready to start adding two methods that will be responsible for actually
searching for HTML elements within a certain class and return its contents. The first
method is called _get_data:
def _get_data(self, container, search_items):
scraped_data = {}
return scraped_data
The idea of this method is to search items within a container that matches some criteria. The
container is just a DOM element in the HTML and the search_items is a dictionary
where the key is a CSS class and the value is the type of the HTML element. It can be a DIV,
SPAN, or anything that you wish to get the value from.
It starts looping through search_items.items() and uses the find method to find the
element within the container. If the item is found, we use get_text to extract the text of the
DOM element and add it to a dictionary that will be returned when there are no more items
to search.
The second method that we will implement is the _parser method. This will make use of
the _get_data that we just implemented:
def _parse(self, container, criteria):
results = [self._get_data(item, criteria)
for item in container.children]
Here, we also get a container and criteria like the _get_data method. The container is
a DOM element and the criterion is a dictionary of nodes that we want to find. The first
comprehension gets all the container's children elements and passes them to the
_get_data method.
The results will be a list of dictionaries with all the items that have been found, and we will
only return the dictionaries that are not empty.
[ 31 ]
Implementing the Weather Application Chapter 1
There are only two more helper methods we need to implement in order to get today's
weather forecast in place. Let's implement a method called _clear_str_number:
def _clear_str_number(self, str_number):
result = self._only_digits_regex.match(str_number)
return '--' if result is None else result.group()
This method will use a regular expression to make sure that only digits are returned.
And the last method that needs to be implemented is the _get_additional_info method:
def _get_additional_info(self, content):
data = tuple(item.td.span.get_text()
for item in content.table.tbody.children)
return data[:2]
This method loops through the table rows, getting the text of every cell. This
comprehension will return lots of information about the weather, but we are only interested
in the first 2, the wind and the humidity.
content = self._request.fetch_data(args.forecast_option.value,
args.area_code)
bs = BeautifulSoup(content, 'html.parser')
[ 32 ]
Implementing the Weather Application Chapter 1
if len(weather_conditions) < 1:
raise Exception('Could not parse weather foreecast for
today.')
weatherinfo = weather_conditions[0]
temp_regex = re.compile(('H\s+(\d+|\-{,2}).+'
'L\s+(\d+|\-{,2})'))
temp_info = temp_regex.search(weatherinfo['today_nowcard-
hilo'])
high_temp, low_temp = temp_info.groups()
curr_temp = self._clear_str_number(weatherinfo['today_nowcard-
temp'])
self._unit_converter.dest_unit = args.unit
td_forecast = Forecast(self._unit_converter.convert(curr_temp),
humidity,
wind,
high_temp=self._unit_converter.convert(
high_temp),
low_temp=self._unit_converter.convert(
low_temp),
description=weatherinfo['today_nowcard-
phrase'])
return [td_forecast]
That is the function that will be called when the -td or --today flag is used on the
command line. Let's break down this code so that we can easily understand what it does.
Understanding this method is important because these methods parse data from other
weather forecast options (five days, ten days, and weekend) that are very similar to this one.
The method's signature is quite simple; it only gets args, which is the Argument object that
is created in the __main__ method. The first thing we do in this method is to create
a criteria dictionary with all the DOM elements that we want to find in the markup:
criteria = {
'today_nowcard-temp': 'div',
'today_nowcard-phrase': 'div',
'today_nowcard-hilo': 'div',
}
[ 33 ]
Implementing the Weather Application Chapter 1
As mentioned before, the key to the criteria dictionary is the name of the DOM element's
CSS class, and the value is the type of the HTML element:
Next, we are going to fetch, create, and use BeautifulSoup to parse the DOM:
content = self._request.fetch_data(args.forecast_option.value,
args.area_code)
bs = BeautifulSoup(content, 'html.parser')
if len(weather_conditions) < 1:
raise Exception('Could not parse weather forecast for today.')
weatherinfo = weather_conditions[0]
First, we make use of the fetch_data method of the Request class that we created on the
core module and pass two arguments; the first is the forecast option and the second
argument is the area code that we passed on the command line.
After fetching the data, we create a BeautifulSoup object passing the content and a
parser. Since we are getting back HTML, we use html.parser.
Now is the time to start looking for the HTML elements that we are interested in.
Remember, we need to find an element that will be a container, and the _parser function
will search through the children elements and try to find items that we defined in the
dictionary criteria. For today's weather forecast, the element that contains all the data we
need is a section element with the today_nowcard-container CSS class.
BeautifulSoup contains the find method, which we can use to find elements in the
HTML DOM with specific criteria. Note that the keyword argument is called class_ and
not class because class is a reserved word in Python.
[ 34 ]
Implementing the Weather Application Chapter 1
Now that we have the container element, we can pass it to the _parse method, which will
return a list. We perform a check if the result list contains at least one element and raise an
exception if it is empty. If it is not empty, we just get the first element and assign it to
the weatherinfo variable. The weatherinfo variable now contains a dictionary with all
the items that we were looking for.
We want to parse the text that has been extracted from the DOM element with
the today_nowcard-hilo CSS class, and the text should look something like H 50 L 60, H
-- L 60, and so on. An easy and simple way of extracting the text we want is to use a
regular expression:
H\s+(\d+|\-{,2}).L\s+(\d+|\-{,2})
We can break this regular expression into two parts. First, we want to get the highest
temperature—H\s+(\d+|\-{,2}); this means that it will match an H followed by some
spaces, and then it will group a value that matches either numbers or a maximum of two
dash symbols. After that, it will match any character. Lastly, comes the second part that
basically does the same; however, it starts matching an L.
After executing the search method, it gets regular expression groups that have been
returned calling the groups() function, which in this case will return two groups, one for
the highest temperature and the second for the lowest.
Other information that we want to provide to our users is information about wind and
humidity. The container element that contains this information has a CSS class called
today_nowcard-sidecar:
We just find the container and pass it into the _get_additional_info method that will
loop through the children elements of the container, extracting the text and finally returning
the results for us.
[ 35 ]
Implementing the Weather Application Chapter 1
self._unit_converter.dest_unit = args.unit
td_forecast = Forecast(self._unit_converter.convert(curr_temp),
humidity,
wind,
high_temp=self._unit_converter.convert(
high_temp),
low_temp=self._unit_converter.convert(
low_temp),
description=weatherinfo['today_nowcard-
phrase'])
return [td_forecast]
Since the current temperature contains a special character (degree sign) that we don't want
to have at this point, we use the _clr_str_number method to pass the today_nowcard-
temp item of the weatherinfo dictionary.
Now that we have all the information we need, we construct the Forecast object and
return it. Note that we are returning an array here; this is because all other options that we
are going to implement (five-day, ten-day, and weekend forecasts) will return a list, so to
make it consistent; also to facilitate when we will have to display this information on the
terminal, we are also returning a list.
Another thing to note is that we are making use of the convert method of our
UnitConverter to convert all the temperatures to the unit selected in the command line.
[ 36 ]
Implementing the Weather Application Chapter 1
Congratulations! You have implemented your first web scraping application. Next up, let's
add the other forecast options.
The markup of the pages that present data for five and ten days are very similar; they have
the same DOM structure and share the same CSS classes, which makes it easier for us to
implement just one method that will work for both options. Let's go ahead and add a new
method to the wheater_com_parser.py file with the following contents:
def _parse_list_forecast(self, content, args):
criteria = {
'date-time': 'span',
'day-detail': 'span',
'description': 'td',
'temp': 'td',
'wind': 'td',
'humidity': 'td',
}
bs = BeautifulSoup(content, 'html.parser')
As I mentioned before, the DOM for the five- and ten-day weather forecasts is very similar,
so we create the _parse_list_forecast method, which can be used for both options.
First, we define the criteria:
The date-time is a span element and contains a string representing the day of
the week
The day-detail is a span element and contains a string with the date, for
example, SEP 29
The description is a TD element and contains the weather conditions, for
example, Cloudy
[ 37 ]
Implementing the Weather Application Chapter 1
temp is a TD element and contains temperature information such as high and low
temperature
wind is a TD element and contains wind information
humidity is a TD element and contains humidity information
Now that we have the criteria, we create a BeatufulSoup object, passing the content and
the html.parser. All the data that we would like to get is on the table with a CSS class
named twc-table. We find the table and define the tbody element as a container.
Finally, we run the _parse method, passing the container and the criteria that we
defined. The return of this function will look something like this:
[{'date-time': 'Today',
'day-detail': 'SEP 28',
'description': 'Partly Cloudy',
'humidity': '78%',
'temp': '60°50°',
'wind': 'ESE 10 mph '},
{'date-time': 'Fri',
'day-detail': 'SEP 29',
'description': 'Partly Cloudy',
'humidity': '79%',
'temp': '57°48°',
'wind': 'ESE 10 mph '},
{'date-time': 'Sat',
'day-detail': 'SEP 30',
'description': 'Partly Cloudy',
'humidity': '77%',
'temp': '57°49°',
'wind': 'SE 10 mph '},
{'date-time': 'Sun',
'day-detail': 'OCT 1',
'description': 'Cloudy',
'humidity': '74%',
'temp': '55°51°',
'wind': 'SE 14 mph '},
{'date-time': 'Mon',
'day-detail': 'OCT 2',
'description': 'Rain',
'humidity': '87%',
'temp': '55°48°',
'wind': 'SSE 18 mph '}]
[ 38 ]
Implementing the Weather Application Chapter 1
Another method that we need to create is a method that will prepare the data for us, for
example, parsing and converting temperature values and creating a Forecast object. Add
a new method called _prepare_data with the following content:
def _prepare_data(self, results, args):
forecast_result = []
self._unit_converter.dest_unit = args.unit
try:
dateinfo = item['weather-cell']
date_time, day_detail = dateinfo[:3], dateinfo[3:]
item['date-time'] = date_time
item['day-detail'] = day_detail
except KeyError:
pass
day_forecast = Forecast(
self._unit_converter.convert(item['temp']),
item['humidity'],
item['wind'],
high_temp=self._unit_converter.convert(high_temp),
low_temp=self._unit_converter.convert(low_temp),
description=item['description'].strip(),
forecast_date=f'{item["date-time"]} {item["day-
detail"]}',
forecast_type=self._forecast_type)
forecast_result.append(day_forecast)
return forecast_result
This method is quite simple. First, loop through the results and apply the regex that we
created to split the high and low temperatures stored in item['temp']. If there's a match,
it will get the groups and assign the value to high_temp and low_temp.
After that, we create a Forecast object and append it to a list that will be returned later on.
[ 39 ]
Implementing the Weather Application Chapter 1
Lastly, we add the method that will be invoked when the -5d or -10d flag is used. Create
another method called _five_and_ten_days_forecast with the following contents:
def _five_and_ten_days_forecast(self, args):
content = self._request.fetch_data(args.forecast_option.value,
args.area_code)
results = self._parse_list_forecast(content, args)
return self._prepare_data(results)
This method only fetches the contents of the page passing the forecast_option value and
the area code, so it will be possible to build the URL to perform the request. When the data
is returned, we pass it down to the _parse_list_forecast, which will return a list of
Forecast objects (one for each day); finally, we prepare the data to be returned using the
_prepare_data method.
Before we run the command, we need to enable this option in the command line tool that
we implemented; go over to the __main__.py file, and, just after the definition of the -td
flag, add the following code:
argparser.add_argument('-5d', '--fivedays',
dest='forecast_option',
action='store_const',
const=ForecastType.FIVEDAYS,
help='Shows the weather forecast for the
5 days')
Now, run the application again, but this time using the -5d or --fivedays flag:
$ python -m weatherterm -u Fahrenheit -a SWXX2372:1:SW -p WeatherComParser
-5d
[ 40 ]
Implementing the Weather Application Chapter 1
To wrap this section up, let's include the option to get the weather forecast for the next ten
days as well, in the __main__.py file, just below the -5d flag definition. Add the
following code:
argparser.add_argument('-10d', '--tendays',
dest='forecast_option',
action='store_const',
const=ForecastType.TENDAYS,
help='Shows the weather forecast for the
10 days')
If you run the same command as we used to get the five-day forecast but replace the -5d
flag with -10d, like so:
$ python -m weatherterm -u Fahrenheit -a SWXX2372:1:SW -p WeatherComParser
-10d
[ 41 ]
Implementing the Weather Application Chapter 1
As you can see, the weather was not so great here in Sweden while I was writing this book.
[ 42 ]
Implementing the Weather Application Chapter 1
The DOM structure is different and some CSS class names are different as well. If you
remember the previous methods that we implemented, we always use
the _parser method, which gives us arguments such as the container DOM and a
dictionary with the search criteria. The return value of that method is also a dictionary
where the key is the class name of the DOM that we were searching and the value is the text
within that DOM element.
Since the CSS class names of the weekend page are different, we need to implement some
code to get that array of results and rename all the keys so the _prepare_data function can
use scraped results properly.
With that said, let's go ahead and create a new file in the weatherterm/core directory
called mapper.py with the following contents:
class Mapper:
def __init__(self):
self._mapping = {}
if not src_dict:
raise AttributeError('The source dictionary cannot be
empty or None')
[ 43 ]
Implementing the Weather Application Chapter 1
dest[new_key] = value
except KeyError:
dest[key] = value
return dest
The Mapper class gets a list with dictionaries and renames specific keys that we would like
to rename. The important methods here are remap_key and remap. The remap_key gets
two arguments, source and dest. source is the key that we wish to rename and dest is
the new name for that key. The remap_key method will add it to an internal dictionary
called _mapping, which will be used later on to look up the new key name.
The remap method simply gets a list containing the dictionaries and, for every item on that
list, it calls the _exec method that first creates a brand new dictionary, then checks whether
the dictionary is empty. In that case, it raises an AttributeError.
If the dictionary has keys, we loop through its items, search for whether the current item's
key has a new name in the mapping dictionary. If the new key name is found, will to create
a new item with the new key name; otherwise, we just keep the old name. After the loop,
the list is returned with all the dictionaries containing the keys with a new name.
Now, we just need to add it to the __init__.py file in the weatherterm/core directory:
from .mapper import Mapper
With the mapper in place, we can go ahead and create the _weekend_forecast method in
the weather_com_parser.py file, like so:
def _weekend_forecast(self, args):
criteria = {
'weather-cell': 'header',
'temp': 'p',
'weather-phrase': 'h3',
'wind-conditions': 'p',
'humidity': 'p',
}
mapper = Mapper()
mapper.remap_key('wind-conditions', 'wind')
mapper.remap_key('weather-phrase', 'description')
[ 44 ]
Implementing the Weather Application Chapter 1
content = self._request.fetch_data(args.forecast_option.value,
args.area_code)
bs = BeautifulSoup(content, 'html.parser')
The method starts off by defining the criteria in exactly the same way as the other
methods; however, the DOM structure is slightly different and some of the CSS names are
also different:
As you can see, to make it play nicely with the _prepare_data method, we will need to
rename some keys in the dictionaries in the result set—wind-conditions should be wind
and weather-phrase should be the description.
We create a Mapper object and say, remap wind-conditions to wind and weather-
phrase to description:
content = self._request.fetch_data(args.forecast_option.value,
args.area_code)
bs = BeautifulSoup(content, 'html.parser')
[ 45 ]
Implementing the Weather Application Chapter 1
We fetch all the data, create a BeautifulSoup object using the html.parser, and find the
container element that contains the children elements that we are interested in. For the
weekend forecast, we are interested in getting the article element with a CSS class called
ls-mod and within that article we go down to the first child element, which is a DIV, and
gets its first child element, which is also a DIV element.
That's the reason we first find the article, assign it to forecast_data, and then use
forecast_data.div.div so we get the DIV element we want.
After defining the container, we pass it to the _parse method together with the container
element; when we get the results back, we simply need to run the remap method of the
Mapper instance, which will normalize the data for us before we call _prepare_data.
Now, the last detail before we run the application and get the weather forecast for the
weekend is that we need to include the --w and --weekend flag to the ArgumentParser.
Open the __main__.py file in the weatherterm directory and, just below the --tenday
flag, add the following code:
argparser.add_argument('-w', '--weekend',
dest='forecast_option',
action='store_const',
const=ForecastType.WEEKEND,
help=('Shows the weather forecast for the
next or '
'current weekend'))
[ 46 ]
Implementing the Weather Application Chapter 1
Note that this time, I used the -u flag to choose Celsius. All the temperatures in the output
are represented in Celsius instead of Fahrenheit.
Summary
In this chapter, you learned the basics of object-oriented programming in Python; we
covered how to create classes, use inheritance, and use the @property decorators to create
getter and setters.
We covered how to use the inspect module to get more information about modules, classes,
and functions. Last but not least, we made use of the powerful package Beautifulsoup to
parse HTML and Selenium to make requests to the weather website.
We also learned how to implement command line tools using the argparse module from
Python's standard library, which allows us to provide tools that are easier to use and with
very helpful documentation.
Next up, we are going to develop a small wrapper around the Spotify Rest API and use it to
create a remote control terminal.
[ 47 ]
Creating a Remote-Control
2
Application with Spotify
Spotify is a music streaming service that was developed in Stockholm, Sweden. The first
version was released back in 2008 and today it doesn't only provide music, but video and
podcasts as well. Growing rapidly from a startup in Sweden to the biggest music service in
the world, Spotify has apps running on video game consoles and mobile phones, and has
integration with many social networks.
The company really has changed how we consume music and has also enabled not only
well-known artists but small indie artists to share their music with the world.
Luckily, Spotify is also a great platform for developers and provides a really nice and well-
documented REST API where it's possible to make searches by artists, albums, song names,
and also create and share playlists.
For the second application in this book, we are going to develop a terminal application
where we can:
Search artists
Search albums
Search tracks
Play music
Apart from all these features, we are going to implement functions so we can control the
Spotify application through the terminal.
Creating a Remote-Control Application with Spotify Chapter 2
First, we are going to go through the process of creating a new application on Spotify; then,
it will be time to develop a small framework that will wrap some parts of Spotify's REST
API. We are also going to work on implementing different types of authentication
supported by Spotify, in order to consume its REST API.
When all these core functionalities are in place, we are going to develop a terminal user
interface using the curses package that is distributed with Python.
I don't know about you, but I really feel like writing code and listening to some good music,
so let's get right into it!
Our application will be called musicterminal, so we can create a virtual environment with
the same name.
Make sure that you are using Python 3.6 or later, otherwise the
applications in this book may not work properly.
And to activate the virtual environment, you can run the following command:
$ . musicterminal/bin/activate
[ 49 ]
Creating a Remote-Control Application with Spotify Chapter 2
Perfect! Now that we have our virtual environment set up, we can create the project's
directory structure. It should have the following structure:
musicterminal
├── client
├── pytify
│ ├── auth
│ └── core
└── templates
The client directory will contain all the scripts related to the client application that we are
going to build.
Finally, the templates directory will contain some HTML files that will be used when we
build a small Flask application to perform Spotify authentication.
Now, let's create a requirements.txt file inside the musicterminal directory with the
following content:
requests==2.18.4
PyYAML==3.12
[ 50 ]
Creating a Remote-Control Application with Spotify Chapter 2
As you can see in the output, other packages have been installed in our virtual
environment. The reason for this is that the packages that our project requires also require
other packages, so they will also be installed.
which is an awesome Python packaging tool.
Another module that we are going to use is curses. The curses module is
simply a wrapper over the curses C functions and it is relatively simpler to
use than programming in C. If you worked with the curses C library
before, the curses module in Python should be familiar and easy to learn.
One thing to note is that Python includes the curses module on Linux and
Mac; however, it is not included by default on Windows. If you are
running Windows, the curses documentation at.
org/3/howto/curses.html recommends the UniCurses package
developed by Fredrik Lundh.
Just one more thing before we start coding. You can run into problems when trying to
import curses; the most common cause is that the libncurses are not installed in your
system. Make sure that you have libncurses and libncurses-dev installed on your
system before installing Python.
If you are using Linux, you will most likely find libncurses on the package repository of
our preferred distribution. In Debian/Ubuntu, you can install it with the following
command:
$ sudo apt-get install libncurses5 libncurses5-dev
[ 51 ]
Creating a Remote-Control Application with Spotify Chapter 2
At the time of writing, Spotify started changing its developer's site and
was currently in beta, so the address to log in and some screenshots may
be different.
If you don't have a Spotify account, you will have to create one first. You should be able to
create applications if you sign up for the free account, but I would recommend signing up
for the premium account because it is a great service with a great music catalog.
[ 52 ]
Creating a Remote-Control Application with Spotify Chapter 2
When you log in to the Spotify developer website, you will see a page similar to the
following:
At the moment, we don't have any application created (unless you have already created
one), so go ahead and click on the CREATE AN APP button. A dialog screen to create the
application will be displayed:
[ 53 ]
Creating a Remote-Control Application with Spotify Chapter 2
Here, we have three required fields: the application's name, description, and also some
checkboxes where you will have to tell Spotify what you're building. The name should be
pytify and in the description, you can put anything you want, but let's add something like
Application for controlling the Spotify client from the terminal. The
type of application we are building will be a website.
When you are done, click on the NEXT button at the bottom of the dialog screen.
[ 54 ]
Creating a Remote-Control Application with Spotify Chapter 2
The second step in the application's creation process is to inform Spotify whether you are
creating a commercial integration. For the purposes of this book, we are going to select NO;
however, if you are going to create an application that will monetize, you should definitely
select YES.
If you agree with all the conditions, just select all the checkboxes and click the
SUBMIT button.
If the application has been created successfully, you will be redirected to the application's
page, which is shown as follows:
[ 55 ]
Creating a Remote-Control Application with Spotify Chapter 2
Click on the SHOW CLIENT SECRET link and copy the values of the Client ID and the
Client Secret. We are going to need these keys to consume Spotify's REST API.
[ 56 ]
Creating a Remote-Control Application with Spotify Chapter 2
client_id and client_secret are the keys that were created for us when we created the
Spotify application. These keys will be used to get an access token that we will have to
acquire every time we need to send a new request to Spotify's REST API. Just replace the
<your client ID> and <your client secret> with your own keys.
Keep in mind that these keys have to be kept in a safe place. Don't share
the keys with anyone and if you are having your project on sites like
GitHub, make sure that you are not committing this configuration file
with your secret keys. What I usually do is add the config file to my
.gitignore file so it won't be source-controlled; otherwise, you can
always commit the file as I did by presenting it with placeholders instead
of the actual keys. That way, it will be easy to remember where you need
to add the keys.
After the client_id and client_secret keys, we have the access_token_url. This is
the URL to the API endpoint that we have to perform requests on in order to get the access
token.
auth_url is the endpoint of Spotify's Account Service; we will use it when we need to
acquire or refresh an authorization token.
The api_version, as the name says, specifies Spotify's REST API version. This is appended
to the URL when performing requests.
Lastly, we have the api_url, which is the base URL for Spotify's REST API endpoints.
[ 57 ]
Creating a Remote-Control Application with Spotify Chapter 2
class AuthMethod(Enum):
CLIENT_CREDENTIALS = auto()
AUTHORIZATION_CODE = auto()
Now, we can continue and create the functions that will read the configuration for us.
Create a file called config.py in the musicterminal/pytify/core directory, and let's
start by adding some import statements:
import os
import yaml
from collections import namedtuple
First, we import the os module so we can have access to functions that will help us in
building the path where the YAML configuration file is located. We also import the yaml
package to read the configuration file and, last but not least, we are importing
namedtuple from the collections module. We will go into more detail about what
namedtuple does later.
The last thing we import is the AuthMethod enumeration that we just created in the
pytify.auth module.
[ 58 ]
Creating a Remote-Control Application with Spotify Chapter 2
Now, we need a model representing the configuration file, so we create a named tuple
called Config, such as:
Config = namedtuple('Config', ['client_id',
'client_secret',
'access_token_url',
'auth_url',
'api_version',
'api_url',
'base_url',
'auth_method', ])
The namedtuple is not a new feature in Python and has been around since version
2.6. namedtuple's are tuple-like objects with a name and with fields accessible by attribute
lookup. It is possible to create namedtuple in two different ways; let's start Python REPL
and try it out:
>>> from collections import namedtuple
>>> User = namedtuple('User', ['firstname', 'lastname', 'email'])
>>> u = User('Daniel','Furtado', 'myemail@test.com')
User(firstname='Daniel', lastname='Furtado', email='myemail@test.com')
>>>
This construct gets two arguments; the first argument is the name of the namedtuple, and
the second is an array of str elements representing every field in the namedtuple. It is also
possible to specify the fields of the namedtuple by passing a string with every field name
separated by a space, such as:
>>> from collections import namedtuple
>>> User = namedtuple('User', 'firstname lastname email')
>>> u = User('Daniel', 'Furtado', 'myemail@test.com')
>>> print(u)
User(firstname='Daniel', lastname='Furtado', email='myemail@test.com')
Verbose, which, when set to True, displays the definition of the class that defines the
namedtuple on the terminal. Behind the scenes, namedtuple's are classes and the verbose
keyword argument lets us have a sneak peek at how the namedtuple class is constructed.
Let's see this in practice on the REPL:
>>> from collections import namedtuple
>>> User = namedtuple('User', 'firstname lastname email',
verbose=True)
from builtins import property as _property, tuple as _tuple
from operator import itemgetter as _itemgetter
[ 59 ]
Creating a Remote-Control Application with Spotify Chapter 2
class User(tuple):
'User(firstname, lastname, email)'
__slots__ = ()
@classmethod
def _make(cls, iterable, new=tuple.__new__, len=len):
'Make a new User object from a sequence or iterable'
result = new(cls, iterable)
if len(result) != 3:
raise TypeError('Expected 3 arguments, got %d' %
len(result))
return result
def __repr__(self):
'Return a nicely formatted representation string'
return self.__class__.__name__ + '(firstname=%r,
lastname=%r, email=%r)'
% self
def _asdict(self):
'Return a new OrderedDict which maps field names to their
values.'
return OrderedDict(zip(self._fields, self))
def __getnewargs__(self):
'Return self as a plain tuple. Used by copy and pickle.'
return tuple(self)
[ 60 ]
Creating a Remote-Control Application with Spotify Chapter 2
The other keyword argument is rename, which will rename every property in the
namedtuple that has an incorrect naming, for example:
As you can see, the field 23445 has been automatically renamed to _3, which is the field
position.
To access the namedtuple fields, you can use the same syntax when accessing properties in
a class, using the namedtuple —User as shown in the preceding example. If we would like
to access the lastname property, we can just write u.lastname.
Now that we have the namedtuple representing our configuration file, it is time to add the
function that will perform the work of loading the YAML file and returning the
namedtuple—Config. In the same file, let's implement the read_config function as
follows:
def read_config():
current_dir = os.path.abspath(os.curdir)
file_path = os.path.join(current_dir, 'config.yaml')
try:
with open(file_path, mode='r', encoding='UTF-8') as file:
config = yaml.load(file)
config['base_url'] =
f'{config["api_url"]}/{config["api_version"]}'
auth_method = config['auth_method']
config['auth_method'] =
AuthMethod.__members__.get(auth_method)
[ 61 ]
Creating a Remote-Control Application with Spotify Chapter 2
return Config(**config)
except IOError as e:
print(""" Error: couldn''t file the configuration file
`config.yaml`
'on your current directory.
client_id: 'your_client_id'
client_secret: 'you_client_secret'
access_token_url: ''
auth_url: ''
api_version: 'v1'
api_url: 'http//api.spotify.com'
auth_method: 'authentication method'
The read_config function starts off by using the os.path.abspath function to get the
absolute path of the current directory, and assigns it to the current_dir variable. Then, we
join the path stored on the current_dir variable with the name of the file, in this case, the
YAML configuration file.
inside the try statement, we try to open the file as read-only and set the encoding to UTF-8.
In the event this fails, it will print a help message to the user saying that it couldn't open the
file and will show help describing how the YAML configuration file is structured.
If the configuration file can be read successfully, we call the load function in the yaml
module to load and parse the file, and assign the results to the config variable. We also
include an extra item in the config called base_url, which is just a helper value that
contains the concatenated values of api_url and api_version.
The value of the base_url will look something like this:.
Lastly, we create an instance of Config. Note how we spread the values in the constructor;
this is possible because the namedtuple—Config, has the same fields as the object
returned by yaml.load(). This would be exactly the same as doing this:
return Config(
client_id=config['client_id'],
client_secret=config['client_secret'],
[ 62 ]
Creating a Remote-Control Application with Spotify Chapter 2
access_token_url=config['access_token_url'],
auth_url=config['auth_url'],
api_version=config['api_version'],
api_url=config['api_url'],
base_url=config['base_url'],
auth_method=config['auth_method'])
The final touch here is to create a __init__.py file in the pytify/core directory and
import the read_config function that we just created:
from .config import read_config
The client credentials flow has some disadvantages over the authorization code flow
because the flow does not include authorization and cannot access the user's private data as
well as control playback. We will implement and use this flow for now, but we will change
to authorization code when we start implementing the terminal player.
Authorization = namedtuple('Authorization', [
'access_token',
'token_type',
'expires_in',
'scope',
'refresh_token',
])
[ 63 ]
Creating a Remote-Control Application with Spotify Chapter 2
This is going to be the authentication model and it will contain the data we get after
requesting an access token. In the following list, you can see a description of every property:
access_token: The token that has to be sent together with every request to the
Web API
token_type: The type of the token, which is usually Bearer
expires_in: The access_token expiration time, which is 3600 seconds (1 hour)
scope: The scope is basically the permissions that Spotify's user granted to our
application
refresh_token: The token that can be used to refresh the access_token after
the expiration
1. Our application will request the access token from the Spotify accounts service;
remember that in our configuration file, we have the api_access_token. That's
the URL we need to send the request to get hold of an access token. There are
three things that we will need to send the request, the client id, the client secret,
and the grant type, which in this case is client_credentials.
2. The Spotify account service will validate that request, check if the keys match
with the keys of the app that we register to the developer's site, and return an
access token.
3. Now, our application has to use this access token in order to consume data from
the REST APIs.
4. The Spotify REST API will return the data we requested.
Before we start implementing the functions that will make the authentication and get the
access token, we can add a custom exception that we will throw if we get a bad request
(HTTP 400) from the Spotify account service.
[ 64 ]
Creating a Remote-Control Application with Spotify Chapter 2
This class doesn't do much; we simply inherit from Exception. We could have just thrown
a generic exception, but it is a good practice to create your own custom exceptions with
good names and descriptions when developing frameworks and libraries that other
developers will make use of.
Now, developers using this code can handle this kind of exception properly in their code.
Open the __init__.py file in the musicterminal/pytify/core directory and add the
following import statement:
from .exceptions import BadRequestError
I usually put all the imports from standard library modules first and
function imports in files from my applications last. It is not a requirement,
but it is just something I think makes the code cleaner and more
organized. This way, I can easily see which are standard library items and
which aren't.
[ 65 ]
Creating a Remote-Control Application with Spotify Chapter 2
Now, we can start adding the functions that will send the request the to the Spotify
account service and return the access token. The first function that we are going to add is
called get_auth_key:
def get_auth_key(client_id, client_secret):
byte_keys = bytes(f'{client_id}:{client_secret}', 'utf-8')
encoded_key = base64.b64encode(byte_keys)
return encoded_key.decode('utf-8')
The client credential flow requires us to send the client_id and the client_secret,
which has to be base 64-encoded. First, we convert the string with
the client_id:client_secret format to bytes. After that, we encode it using base 64 and
then decode it, returning the string representation of that encoded data so we can send it
with the request payload.
The other function that we are going to implement in the same file is
called _client_credentials:
def _client_credentials(conf):
options = {
'grant_type': 'client_credentials',
'json': True,
}
response = requests.post(
'',
headers=headers,
data=options
)
content = json.loads(response.content.decode('utf-8'))
if response.status_code == 400:
error_description = content.get('error_description','')
raise BadRequestError(error_description)
access_token = content.get('access_token', None)
token_type = content.get('token_type', None)
expires_in = content.get('expires_in', None)
scope = content.get('scope', None)
return Authorization(access_token, token_type, expires_in,
scope, None)
[ 66 ]
Creating a Remote-Control Application with Spotify Chapter 2
This function gets an argument as the configuration and uses the get_auth_key function
to pass the client_id and the client_secret to build a base 64-encoded auth_key. This
will be sent to Spotify's accounts service to request an access_token.
Now, it is time to prepare the request. First, we set the Authorization in the request
header, and the value will be the Basic string followed by the auth_key. The payload for
this request will be grant_type, which in this case is client_credentials, and
json will be set to True, which tells the API that we want the response in JSON format.
We use the requests package to make the request to Spotify's account service, passing the
headers and the data that we configured.
When we get a response, we first decode and load the JSON data into the variable content.
Note that we are setting None to the last parameter when creating an
Authentication, namedtuple. The reason for this is that Spotify's
account service doesn't return a refresh_token when the type of
authentication is CLIENT_CREDENTIALS.
All the functions that we have created so far are meant to be private, so the last function
that we are going to add is the authenticate function. This is the function that developers
will invoke to start the authentication process:
def authenticate(conf):
return _client_credentials(conf)
This function is pretty straightforward; the function gets an argument as an instance of the
Config, namedtuple, which will contain all the data that has been read from the
configuration file. We then pass the configuration to the _client_credentials function,
which will obtain the access_token using the client credentials flow.
[ 67 ]
Creating a Remote-Control Application with Spotify Chapter 2
Exactly what we expected! The next step is to start creating the functions that will consume
Spotify's REST API.
1. Our application will request authorization to access data, redirecting the user to a
login page on Spotify's web page. There, the user can see all the access rights that
the application requires.
2. If the user approves it, the Spotify account service will send a request to the
callback URI, sending a code and the state.
3. When we get hold of the code, we send a new request passing the client_id,
client_secret, grant_type, and code to acquire the access_token. This
time, it will be different from the client credentials flow; we are going to get
scope and a refresh_token
4. Now, we can normally send requests to the Web API and if the access token has
expired, we can do another request to refresh the access token and continue
performing requests.
[ 68 ]
Creating a Remote-Control Application with Spotify Chapter 2
With that said, open the auth.py file in the musicterminal/pytify/auth directory and
let's add a few more functions. First, we are going to add a function called
_refresh_access_token; you can add this function after the get_auth_key function:
options = {
'refresh_token': refresh_token,
'grant_type': 'refresh_token',
}
response = requests.post(
'',
headers=headers,
data=options
)
content = json.loads(response.content.decode('utf-8'))
if not response.ok:
error_description = content.get('error_description', None)
raise BadRequestError(error_description)
It basically does the same thing as the function handling the client credentials flow, but this
time we send the refresh_token and the grant_type. We get the data from the
response's object and create an Authorization, namedtuple.
The next function that we are going to implement will make use of the os module of the
standard library, so before we start with the implementation, we need to add the following
import statement at the top of the auth.py file:
import os
[ 69 ]
Creating a Remote-Control Application with Spotify Chapter 2
Now, we can go ahead and add a function called _authorization_code. You can add this
function after the get_auth_key function with the following contents:
def _authorization_code(conf):
current_dir = os.path.abspath(os.curdir)
file_path = os.path.join(current_dir, '.pytify')
try:
with open(file_path, mode='r', encoding='UTF-8') as file:
refresh_token = file.readline()
if refresh_token:
return _refresh_access_token(auth_key,
refresh_token)
except IOError:
raise IOError(('It seems you have not authorize the
application '
'yet. The file .pytify was not found.'))
Here, we try opening a file called .pytify in the musicterminal directory. This file will
contain the refresh_token that we are going to use to refresh the access_token every
time we open our application.
The last modification we need to do now is in the authenticate function in the same file.
We are going to add support for both authentication methods; it should look like this:
def authenticate(conf):
if conf.auth_method == AuthMethod.CLIENT_CREDENTIALS:
return _client_credentials(conf)
return _authorization_code(conf)
Now, we will start different authentication methods depending on what we have specified
in the configuration file.
Since the authentication function has a reference to AuthMethod, we need to import it:
from .auth_method import AuthMethod
[ 70 ]
Creating a Remote-Control Application with Spotify Chapter 2
Before we try this type of authentication out, we need to create a small web app that will
authorize our application for us. We are going to work on that in the next section.
There are a few more access rights which would be a good idea to add from the beginning if
you intend to add more functionalities to this application; for example, if you want to be
able to manipulate a user's private and public playlists, you may want to add
the playlist-modify-private and playlist-modify-public scope.
You might also want to display a list of artists that the user follows on the client application,
so you need to include user-follow-read to the scope as well.
The idea is to authorize our application using the authorization code flow. We are going to
create a simple web application using the framework Flask that will define two routes.
The / root will just render a simple page with a link that will redirect us to the Spotify
authentication page.
The second root will be /callback, which is the endpoint that Spotify will call after the
users of our application give authorization for our application to access their Spotify data.
Let's see how this is implemented, but first, we need to install Flask. Open a terminal and
type the following command:
pip install flask
After you have installed it you can even include it in the requirements.txt file such as:
$ pip freeze | grep Flask >> requirements.txt
The command pip freeze will print all the installed packages in the requirements format.
The output will return more items because it will also contain all the dependencies of the
packages that we already installed, which is why we grep Flask and append it to the
requirements.txt file.
[ 71 ]
Creating a Remote-Control Application with Spotify Chapter 2
Next time you are going to set up a virtual environment to work on this project you can just
run:
pip install -r requirements.txt
Great! Now, we can start creating the web application. Create a file called
spotify_auth.py.
import requests
import json
We are going to use the urlencode function in the urllib.parse module to encode the
parameters that are going to be appended to the authorize URL. We are also going to use
the requests to send a request to get the access_token after the user authorizes our app
and use the json package to parse the response.
Then, we will import Flask-related things, so we can create a Flask
application, render_template, so we can return a rendered HTML template to the user,
and finally the request, so we can access the data sent back to us by Spotify's authorization
service.
We will also import some functions that we included in the core and auth submodules of
the pytify module: the read_config to load and read the YAML config file and the
_authorization_code_request. The latter will be explained in more detail in a short
while.
@app.route("/")
def home():
[ 72 ]
Creating a Remote-Control Application with Spotify Chapter 2
config = read_config()
params = {
'client_id': config.client_id,
'response_type': 'code',
'redirect_uri': '',
'scope': 'user-read-private user-modify-playback-state',
}
enc_params = urlencode(params)
url = f'{config.auth_url}?{enc_params}'
Great! Starting from the top, we read the configuration file so we can get our client_id
and also the URL for Spotify's authorization service. We build the parameters dictionary
with the client_id; the response type for the authorization code flow needs to be set to
code; the redirect_uri is the callback URI which Spotify's authorization service will use
to send us the authorization code back. And finally, since we are going to send instructions
to the REST API to play a track in the user's active device, the application needs to have
user-modify-playback-state permissions.
The return value will be a rendered HTML. Here, we will use the render_template
function, passing a template as a first argument. By default, Flask will search this template
in a directory called templates. The second argument to this function is the model. We are
passing a property named link and setting the value of the variable URL. This way, we can
render the link in the HTML template such as: {{link}}.
Next, we are going to add a function to acquire the access_token and the
refresh_token for us after we get the authorization code back from Spotify's account
service. Create a function called _authorization_code_request with the following
content:
def _authorization_code_request(auth_code):
config = read_config()
options = {
'code': auth_code,
'redirect_uri': '',
[ 73 ]
Creating a Remote-Control Application with Spotify Chapter 2
'grant_type': 'authorization_code',
'json': True
}
response = requests.post(
config.access_token_url,
headers=headers,
data=options
)
content = json.loads(response.content.decode('utf-8'))
if response.status_code == 400:
error_description = content.get('error_description', '')
raise BadRequestError(error_description)
This function is pretty much the same as the _refresh_access_token function that we
previously implemented in the auth.py file. The only thing to note here is that in the
options, we are passing the authorization code, and the grant_type is set to
authorization_code:
@app.route('/callback')
def callback():
config = read_config()
code = request.args.get('code', '')
response = _authorization_code_request(config, code)
return 'All set! You can close the browser window and stop the
server.'
Here, we define the route that will be called by Spotify's authorization service to send back
the authorization code.
We start off by reading the configuration, parsing the code from the request data, and
calling the _authorization_code_request, passing the code we have just obtained.
[ 74 ]
Creating a Remote-Control Application with Spotify Chapter 2
This function will send another request using this code, and it will acquire an access token
that we can use to send requests, along with a refresh token that will be stored in a file
called .pytify in the musicterminal directory.
The access token that we obtain to make the requests to the Spotify REST API is valid for
3,600 seconds, or 1 hour, which means that within one hour, we can use the same access
token to make requests. After that, we need to refresh the access token. We can do that by
using the refresh token that is stored in the .pytify file.
Now, to finish our Flask application, we need to add the following code:
if __name__ == '__main__':
app.run(host='localhost', port=3000)
This tells Flask to run the server on the localhost and use port 3000.
The home function of our Flash application will, as a response, return a templated HTML
file called index.html. We haven't created that file yet, so let's go ahead and create a folder
called musicterminal/templates and inside the newly created directory, add a file
called index.html with the following contents:
<html>
<head>
</head>
<body>
<a href={{link}}> Click here to authorize </a>
</body>
</html>
There's not much to explain here, but note that we are referencing the link property that we
passed to the render_template function in the home function of the Flask application. We
are setting the href attribute of that anchor element to the value of the link.
Great! There is only more thing before we try this out and see if everything is working
properly. We need to change the settings of our Spotify app; more specifically, we need to
configure the callback function for the application, so we can receive the authorization code.
[ 75 ]
Creating a Remote-Control Application with Spotify Chapter 2
Scroll down until you find Redirect URIs, and in the text field, enter and click on the ADD button. Your configuration should look
as follows:
Great! Scroll down to the bottom of the dialog and click the SAVE button.
Now, we need to run the Flask application that we just created. On the terminal, in the
projects root folder, type the following command:
python spotify_auth.py
Open the browser of your choice and go to; you will see a
simple page with the link that we created:
Click on the link and you will be sent to Spotify's authorization service page.
[ 76 ]
Creating a Remote-Control Application with Spotify Chapter 2
A dialog will be displayed asking to connect the Pytify app to our account. Once you
authorize it, you will be redirected back to. If
everything goes well, you should see the All set! You can close the browser window and
stop the server message on the page.
Now, just close the browser, and you can stop the Flask application.
Note that we now have a file named .pytify in the musicterminal directory. If you look
at the contents, you will have an encrypted key similar to this one:
AQB2jJxziOvuj1VW_DOBeJh-
uYWUYaR03nWEJncKdRsgZC6ql2vaUsVpo21afco09yM4tjwgt6Kkb_XnVC50CR0SdjW
rrbMnr01zdemN0vVVHmrcr_6iMxCQSk-JM5yTjg4
Next up, we are going to add some functions that will perform requests to Spotify's Web
API to search for artists, get a list of an artist's albums and a list of tracks in an album, and
play the selected track.
class RequestType(Enum):
GET = auto()
PUT = auto()
[ 77 ]
Creating a Remote-Control Application with Spotify Chapter 2
We have gone through enumerations before, so we won't be going into so much detail. It
suffices to say that we create an enumeration with GET and PUT properties. This will be
used to notify the function that performs the requests for us that we want to do a GET
request or a PUT request.
def execute_request(
url_template,
auth,
params,
request_type=RequestType.GET,
payload=()):
url_template: This is the template that will be used to build the URL to
perform the request; it will use another argument called params to build the URL
auth: Is the Authorization object
params: It is a dict containing all the parameters that will be placed into the
URL that we are going to perform the request on
request: This is the request type; it can be GET or PUT
payload: This is the data that may be sent together with the request
params['base_url'] = conf.base_url
url = url_template.format(**params)
headers = {
'Authorization': f'Bearer {auth.access_token}'
[ 78 ]
Creating a Remote-Control Application with Spotify Chapter 2
We read the configuration and add the base URL to the params so it is replaced in the
url_template string. We add Authorization in the request headers, together with the
authentication access token:
if request_type is RequestType.GET:
response = requests.get(url, headers=headers)
else:
response = requests.put(url, headers=headers,
data=json.dumps(payload))
if not response.text:
return response.text
result = json.loads(response.text)
Here, we check if the request type is GET. If so, we execute the get function from requests;
otherwise, we execute the put function. The function calls are very similar; the only thing
that differs here is the data argument. If the response returned is empty, we just return the
empty string; otherwise, we parse the JSON data into the result variable:
if not response.ok:
error = result['error']
raise BadRequestError(
f'{error["message"]} (HTTP {error["status"]})')
return result
After parsing the JSON result, we test whether the status of the request is not 200 (OK); in
that case, we raise a BadRequestError. If it is a successful response, we return the results.
We also need some functions to help us prepare the parameters that we are going to pass to
the Web API endpoints. Let's go ahead and create a file called parameter.py in
the musicterminal/pytify/core folder with the following contents:
from urllib.parse import urlencode
if required is None:
return
[ 79 ]
Creating a Remote-Control Application with Spotify Chapter 2
if not_supplied:
msg = f'The parameter(s) `{", ".join(not_supplied)}` are
required'
raise AttributeError(msg)
query = urlencode(
'&'.join([f'{key}={value}' for key, value in
params.items()])
)
return f'?{query}'
Now, let's add an enumeration with the types of searches that can be performed. Create a
file called search_type.py in the musicterminal/pytify/core directory with the
following contents:
from enum import Enum
class SearchType(Enum):
ARTIST = 1
ALBUM = 2
PLAYLIST = 3
TRACK = 4
[ 80 ]
Creating a Remote-Control Application with Spotify Chapter 2
Now, we are ready to create the function to perform the search. Create a file called
search.py in the musicterminal/pytify/core directory:
import requests
import json
from urllib.parse import urlencode
conf = read_config()
if not criteria:
raise AttributeError('Parameter `criteria` is required.')
q_type = search_type.name.lower()
url = urlencode(f'{conf.base_url}/search?q={criteria}&type=
{q_type}')
return json.loads(response.text)
[ 81 ]
Creating a Remote-Control Application with Spotify Chapter 2
We start by explaining the _search function. This function gets three criteria parameters
(what we want to search for), the Authorization object, and lastly the search type, which
is a value in the enumeration that we just created.
The function is quite simple; we start by validating the parameters, then we build the URL
to make the request, we set the Authorization head using our access token, and lastly,
we perform the request and return the parsed response.
Now that we can search for an artist, we have to get a list of albums. Add a file called
artist.py in the musicterminal/pytify/core directory with the following contents:
url_template = '{base_url}/{area}/{artistid}/{postfix}{query}'
url_params = {
'query': prepare_params(params),
'area': 'artists',
'artistid': artist_id,
'postfix': 'albums',
}
So, given an artist_id, we just define the URL template and parameters that we want to
make the request and run the execute_request function which will take care of building
the URL, getting and parsing the results for us.
[ 82 ]
Creating a Remote-Control Application with Spotify Chapter 2
Now, we want to get a list of the tracks for a given album. Add a file called album.py in the
musicterminal/pytify/core directory with the following contents:
url_template = '{base_url}/{area}/{albumid}/{postfix}{query}'
url_params = {
'query': prepare_params(params),
'area': 'albums',
'albumid': album_id,
'postfix': 'tracks',
}
Finally, we want to be able to send an instruction to Spotify's Web API, telling it to play a
track that we selected. Add a file called player.py in the musicterminal/pytify/core
directory, and add the following contents:
from .parameter import prepare_params
from .request import execute_request
url_template = '{base_url}/{area}/{postfix}'
url_params = {
'query': prepare_params(params),
'area': 'me',
'postfix': 'player/play',
[ 83 ]
Creating a Remote-Control Application with Spotify Chapter 2
payload = {
'uris': [track_uri],
'offset': {'uri': track_uri}
}
return execute_request(url_template,
auth,
url_params,
request_type=RequestType.PUT,
payload=payload)
This function is also very similar to the previous ones (get_artist_albums and
get_album_tracks), except that it defines a payload. A payload is a dictionary containing
two items: uris, which is a list of tracks that should be added to the playback queue, and
offset, which contains another dictionary with the URIs of tracks that should be played
first. Since we are interested in only playing one song at a time, uris and offset will
contain the same track_uri.
The final touch here is to import the new function that we implemented. In the
__init__.py file at the musicterminal/pytify/core directory, add the following code:
Let's try the function to search artists in the python REPL to check whether everything is
working properly:
Python 3.6.2 (default, Dec 22 2017, 15:38:46)
[GCC 6.3.0 20170516] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from pytify.core import search_artist
>>> from pytify.core import read_config
>>> from pytify.auth import authenticate
>>> from pprint import pprint as pp
>>>
>>> config = read_config()
[ 84 ]
Creating a Remote-Control Application with Spotify Chapter 2
The rest of the output has been omitted because it was too long, but now we can see that
everything is working just as expected.
First, we need to create a new directory to keep all the client's related files in it, so go ahead
and create a directory named musicterminal/client.
Our client will only have three views. In the first view, we are going to get the user input
and search for an artist. When the artist search is complete, we are going to switch to the
second view, where a list of albums for the selected artist will be presented. In this view, the
user will be able to select an album on the list using the keyboard's Up and Down arrow
keys and select an album by hitting the Enter key.
Lastly, when an album is selected, we are going to switch to the third and final view on our
application, where the user will see a list of tracks for the selected album. Like the previous
view, the user will also be able to select a track using the keyboard's Up and Down arrow
key; hitting Enter will send a request to the Spotify API to play the selected track on the
user's available devices.
[ 85 ]
Creating a Remote-Control Application with Spotify Chapter 2
One approach is to use curses.panel. Panels are a kind of window and they are very
flexible, allowing us to stack, hide and show, and switch panels, go back to the top of the
stack of panels, and so on, which is perfect for our purposes.
So, let's create a file inside the musicterminal/client directory called panel.py with the
following contents:
import curses
import curses.panel
from uuid import uuid1
class Panel:
self._set_title()
self.hide()
All we do here is import the modules and functions we need and create a class called
Panel. We are also importing the uuid module so we can create a GUID for every new
panel.
The Panel's initializer gets two arguments: title, which is the title of the window,
and dimensions. The dimensions argument is a tuple and follows the curses convention.
It is composed of height, width, and the positions y and x, where the panel should start to
be drawn.
We unpack the values of the dimensions tuple so it is easier to work with and then we use
the newwin function to create a new window; it will have the same dimensions that we
passed in the class initializer. Next, we call the box function to draw lines on the four sides
of the terminal.
Now that we have the window created, it is time to create the panel for the window that we
just created, calling curses.panel.new_panel and passing the window. We also set the
window title and create a GUID.
[ 86 ]
Creating a Remote-Control Application with Spotify Chapter 2
Lastly, we set the state of the panel to hidden. Continuing working on this class, let's add a
new method called hide:
def hide(self):
self._panel.hide()
This method is quite simple; the only thing that it does is call the hide method in our panel.
The other method that we call in the initializer is _set_title; let's create it now:
def _set_title(self):
formatted_title = f' {self._title} '
self._win.addstr(0, 2, formatted_title, curses.A_REVERSE)
In _set_title, we format the title by adding some extra padding on both sides of the title
string, and then we call the addstr method of the window to print the title in row zero,
column two, and we use the constant A_REVERSE, which will invert the colors of the string,
like this:
We have a method to hide the panel; now, we need a method to show the panel. Let's add
the show method:
def show(self):
self._win.clear()
self._win.box()
self._set_title()
curses.curs_set(0)
self._panel.show()
The show method first clears the window and draws the borders around it with
the box method. Then, we set the title again. The cursers.curs_set(0) call will
disable the cursor; we do that here because we don't want the cursor visible when we are
selecting the items in the list. Finally, we call the show method in the panel.
It would also be nice to have a way to know whether the current panel is visible or not. So,
let's add a method called is_visible:
def is_visible(self):
return not self._panel.hidden()
[ 87 ]
Creating a Remote-Control Application with Spotify Chapter 2
Here, we can use the hidden method on the panel, which returns true if the panel is
hidden and false if the panel is visible.
The last touch in this class is to add the possibility of comparing panels. We can achieve this
by overriding some special methods; in this case, we want to override the __eq__ method,
which will be invoked every time we use the == operator. Remember that we created an id
for every panel? We can use that id now to test the equality:
def __eq__(self, other):
return self._id == other._id
Perfect! Now that we have the Panel base class, we are ready to create a special
implementation of the panel that will contain menus to select items.
We only need to import the uuid1 function from the uuid module because, like the panels,
we are going to create an id (GUID) for every menu item in the list.
def return_id():
return self.data['id'], self.data['uri']
self.action = return_id
self.selected = selected
The MenuItem initializer gets three arguments, the label item, the data which will contain
the raw data returned by the Spotify REST API, and a flag stating whether the item is
currently selected or not.
[ 88 ]
Creating a Remote-Control Application with Spotify Chapter 2
We start off by creating an id for the item, then we set the values for the data and label
properties using the argument values that are passed in the class initializer.
Every item in the list will have an action that will be executed when the item is selected on
the list, so we create a function called return_id that returns a tuple with the item id (not
the same as the id that we just created). This is the id for the item on Spotify, and the URI is
the URI for the item on Spotify. The latter will be useful when we select and play a song.
Now, we are going to implement some special methods that will be useful for us when
performing item comparisons and printing items. The first method that we are going to
implement is __eq__:
def __eq__(self, other):
return self.id == other.id
This will allow us to use the index function to find a specific MenuItem in a list of
MenuItem objects.
The other special method that we are going to implement is the __len__ method:
def __len__(self):
return len(self.label)
It returns the length of the MenuItem label and it will be used when measuring the length of
the menu item labels on the list. Later, when we are building the menu, we are going to use
the max function to get the menu item with the longest label, and based on that, we'll add
extra padding to the other items so that all the items in the list look aligned.
The last method that we are going to implement is the __str__ method:
def __str__(self):
return self.label
This is just for convenience when printing menu items; instead of doing
print(menuitem.label), we can just do print(menuitem) and it will invoke __str__,
which will return the value of the MenuItem label.
[ 89 ]
Creating a Remote-Control Application with Spotify Chapter 2
Before we start with the implementation of the menu panel, let's add an enumeration that
will represent different item alignment options, so we can have a bit more flexibility on how
to display the menu items inside the menu.
class Alignment(Enum):
LEFT = auto()
RIGHT = auto()
You should be an enumeration expert if you followed the code in the first chapter. There's
nothing as complicated here; we define a class Alignment inheriting from Enum and define
two attributes, LEFT and RIGHT, both with their values set to auto(), which means that the
values will be set automatically for us and they will be 1 and 2, respectively.
Now, we are ready to create the menu. Let's go ahead and create a final class
called menu.py in the musicterminal/client directory.
class Menu(Panel):
The Menu class inherits from the Panel base class that we just created, and the class
initializer gets a few arguments: the title, the dimensions (tuple with height, width, y
and x values) the alignment setting which is LEFT by default, and the items. The items
argument is a list of MenuItems objects. This is optional and it will be set to an empty list if
no value is specified.
[ 90 ]
Creating a Remote-Control Application with Spotify Chapter 2
The first thing we do in the class initializer is invoke the __init__ method in the base class.
We can do that by using the super function. If you remember, the __init__ method on the
Panel class gets two arguments, title and dimension, so we pass it to the base class
initializer.
Next, we assign the values for the properties align and items.
We also need a method that returns the currently selected item on the list of menu items:
def get_selected(self):
items = [x for x in self.items if x.selected]
return None if not items else items[0]
This method is very straightforward; the comprehension returns a list of selected items, and
it will return None if no items are selected; otherwise, it returns the first item on the list.
Now, we can implement the method that will handle item selection. Let's add another
method called _select:
def _select(self, expr):
current = self.get_selected()
index = self.items.index(current)
new_index = expr(index)
if new_index < 0:
return
self.items[index].selected = False
self.items[new_index].selected = True
Here, we start getting the current item selected, and right after that we get the index of the
item in the list of menu items using the index method from the array. This is possible
because we implemented the __eq__ method in the Panel class.
Then, we get to run the function passed as the argument, expr, passing the value of the
currently selected item index.
expr will determine the next current item index. If the new index is less than 0, it means
that we reached the top of the menu item's list, so we don't take any action.
[ 91 ]
Creating a Remote-Control Application with Spotify Chapter 2
If the new index is greater than the current index, and the new index is greater than or
equal to the number of menu items on the list, then we have reached the bottom of the list,
so no action is required at this point and we can continue selecting the same item.
However, if we haven't reached to top or the bottom of the list, we need to swap the
selected items. To do this, we set the selected property on the current item to False and set
the selected property of the next item to True.
The _select method is a private method, and it is not intended to be called externally, so
we define two methods—next and previous:
def next(self):
self._select(lambda index: index + 1)
def previous(self):
self._select(lambda index: index - 1)
The next method will invoke the _select method and pass a lambda expression that will
receive an index and add one to it, and the previous method will do the same thing, but
instead of increasing the index by 1, it will subtract it. So, in the _select method when we
call:
new_index = expr(index)
Great! Now, we are going to add a method that will be responsible for formatting menu
items before we render them on the screen. Create a method called _initialize_items,
which is shown as follows:
def _initialize_items(self):
longest_label_item = max(self.items, key=len)
if not self.get_selected():
self.items[0].selected = True
[ 92 ]
Creating a Remote-Control Application with Spotify Chapter 2
First, we get the menu item that has the largest label; we can do that by using the built-in
function max and passing the items, and, as the key, another built-in function called len.
This will work because we implemented the special method __len__ in the menu item.
After discovering the menu item with the largest label, we loop through the items of the list,
adding padding on the LEFT or RIGHT, depending on the alignment options. Finally, if
there's no menu item in the list with the selected flag set to True, we select the first item as
selected.
We also want to provide a method called init that will initialize the items on the list for us:
def init(self):
self._initialize_items()
We also need to handle keyboard events so we can perform a few actions when the user
specifically presses the Up and Down arrow keys, as well as Enter.
First, we need to define a few constants at the top of the file. You can add these constants
between the imports and the class definition:
NEW_LINE = 10
CARRIAGE_RETURN = 13
This method is pretty simple; it gets a key argument, and if the key is equal to
curses.KEY_UP, then we call the previous method. If the key is equal to
curses.KEY_DOWN, then we call the next method. Now, if the key is ENTER, then we get
the selected item and return its action. The action is a function that will execute another
function; in our case, we might be selecting an artist or song on a list or executing a function
that will play a music track.
[ 93 ]
Creating a Remote-Control Application with Spotify Chapter 2
We are going to implement the __iter__ method, which will make our Menu class behave
like an iterable object:
def __iter__(self):
return iter(self.items)
The last method of this class is the update method. This method will do the actual work of
rendering the menu items and refreshing the window screen:
def update(self):
pos_x = 2
pos_y = 2
self._win.refresh()
First, we set the x and y coordinates to 2, so the menu on this window will start at line 2
and column 2. We loop through the menu items and call the addstr method to print the
item on the screen.
[ 94 ]
Creating a Remote-Control Application with Spotify Chapter 2
The addstr method gets a y position, the x position, the string that will be written on the
screen, in our case item.label, and the last argument is the style. If the item is selected,
we want to show it highlighted; otherwise, it will display with normal colors. The following
screenshot illustrates what the rendered list will look like:
[ 95 ]
Creating a Remote-Control Application with Spotify Chapter 2
The first thing we are going to add is a custom exception that we can raise, and no result is
returned from the Spotify REST API. Create a new file called empty_results_error.py in
the musicterminal/client directory with the following contents:
class EmptyResultsError(Exception):
pass
To make it easier for us, let's create a DataManager class that will encapsulate all these
functionalities for us. Create a file called data_manager.py in the
musicterminal/client directory:
class DataManager():
def __init__(self):
self._conf = read_config()
self._auth = authenticate(self._conf)
First, we import the MenuItem, so we can return MenuItem objects with the request's
results. After that, we import functions from the pytify module to search artists, get
albums, list albums tracks, and play tracks. Also, in the pytify module, we import
the read_config function and authenticate it.
The initializer of the DataManager class starts reading the configuration and performs the
authentication. The authentication information will be stored in the _auth property.
[ 96 ]
Creating a Remote-Control Application with Spotify Chapter 2
if not items:
raise EmptyResultsError(f'Could not find the artist:
{criteria}')
return items[0]
The _search_artist method will get criteria as an argument and call the
search_artist function from the python.core module. If no items are returned, it will
raise an EmptyResultsError; otherwise, it will return the first match.
Before we continue creating the methods that will fetch the albums and the tracks, we need
two utility methods to format the labels of the MenuItem objects.
Here, the label will be the name of the item and the type, which can be an album, single, EP,
and so on.
time = int(item['duration_ms'])
minutes = int((time / 60000) % 60)
seconds = int((time / 1000) % 60)
track_name = item['name']
Here, we extract the duration of the track in milliseconds, convert is to minutes: seconds,
and format the label with the name of the track and its duration between square brackets.
[ 97 ]
Creating a Remote-Control Application with Spotify Chapter 2
if not albums:
raise EmptyResultsError(('Could not find any albums for'
f'the artist_id: {artist_id}'))
The get_artist_albums method gets two arguments, the artist_id and the max_item,
which is the maximum number of albums that will be returned by the method. By default, it
is set to 20.
The first thing we do here is use the get_artist_albums method from the pytify.core
module, passing the artist_id and the authentication objects, and we get the item's
attribute from the results, assigning it to the variable albums. If the albums variable is
empty, it will raise an EmptyResultsError; otherwise, it will create a list of MenuItem
objects for every album.
if not results:
raise EmptyResultsError('Could not find the tracks for this
album')
tracks = results['items']
The get_album_tracklist method gets album_id as an argument and the first thing we
do is get the tracks for that album using the get_album_tracks function in the
pytify.core module. If no result is returned, we raise an EmptyResultsError;
otherwise, we build a list of MenuItem objects.
[ 98 ]
Creating a Remote-Control Application with Spotify Chapter 2
The last method is the one that will actually send a command to the Spotify REST API to
play a track:
def play(self, track_uri):
play(track_uri, self._auth)
Very straightforward. Here, we just get track_uri as an argument and pass it down the
play function in the pytify.core module, along with the authentication object. That
will make the track start playing on the available device; it can be a mobile phone, Spotify's
client on your computer, the Spotify web player, or even your games console.
Next up, let's put together everything we have built and run the Spotify player terminal.
The pytify module also provides two different types of authentication—client credentials
and authorization code—and in the previous sections, we implemented all the
infrastructures necessary to build an application using curses. So, let's glue all the parts
together and listen to some good music.
On the musicterminal directory, create a file called app.py; this is going to be the entry
point for our application. We start by adding import statements:
import curses
import curses.panel
from curses import wrapper
from curses.textpad import Textbox
from curses.textpad import rectangle
We need to import curses and curses.panel of course, and this time, we are also
importing wrapper. This is used for debugging purposes. When developing curses
applications, they are extremely hard to debug, and when something goes wrong and some
exception is thrown, the terminal will not go back to its original state.
[ 99 ]
Creating a Remote-Control Application with Spotify Chapter 2
The wrapper takes a callable and it returns the terminal original state when the
callable function returns.
The wrapper will run the callable within a try-catch block and it will restore the terminal in
case something goes wrong. It is great for us while developing the application. Let's use the
wrapper so we can see any kind of problem that may occur.
We are going to import two new functions, Textbox and rectangle. We are going to use
those to create a search box where the users can search for their favorite artist.
Lastly, we import the Menu class and the DataManager that we implemented in the
previous sections.
Let's start implementing some helper functions; the first one is show_search_screen:
def show_search_screen(stdscr):
curses.curs_set(1)
stdscr.addstr(1, 2, "Artist name: (Ctrl-G to search)")
box = Textbox(editwin)
box.edit()
criteria = box.gather()
return criteria
It gets an instance of the window as an argument, so we can print text and add our textbox
on the screen.
The curses.curs_set function turns the cursor on and off; when set to 1, the cursor will
be visible on the screen. We want that in the search screen so the user knows where he/she
can start typing the search criteria. Then, we print help text so the user knows that the name
of the artist should be entered; then, to finish, they can press Ctrl + G or just Enter to
perform the search.
To create the textbox, we create a new small window with a height that equals 1 and a
width that equals 40, and it starts at line 3, column 3 of the terminal screen. After that, we
use the rectangle function to draw a rectangle around the new window and we refresh
the screen so the changes we made take effect.
[ 100 ]
Creating a Remote-Control Application with Spotify Chapter 2
Then, we create the Textbox object, passing the window that we just created, and call the
method edit, which will set the box to the textbox and enter edit mode. That will stop the
application and let the user enter some text in the textbox; it will exit when the user
clicks Ctrl + G or Enter.
When the user is done editing the text, we call the gather method that will collect the data
entered by the user and assign it to the criteria variable, and finally, we return
criteria.
We also need a function to clean the screen easily Let's create another function called
clean_screen:
def clear_screen(stdscr):
stdscr.clear()
stdscr.refresh()
Great! Now, we can start with the main entry point of our application, and create a function
called main with the following contents:
def main(stdscr):
curses.cbreak()
curses.noecho()
stdscr.keypad(True)
_data_manager = DataManager()
criteria = show_search_screen(stdscr)
artist = _data_manager.search_artist(criteria)
albums = _data_manager.get_artist_albums(artist['id'])
clear_screen(stdscr)
albums_panel.items = albums
albums_panel.init()
albums_panel.update()
[ 101 ]
Creating a Remote-Control Application with Spotify Chapter 2
albums_panel.show()
current_panel = albums_panel
is_running = True
while is_running:
curses.doupdate()
curses.panel.update_panels()
key = stdscr.getch()
action = current_panel.handle_events(key)
if key == curses.KEY_F2:
current_panel.hide()
criteria = show_search_screen(stdscr)
artist = _data_manager.search_artist(criteria)
albums = _data_manager.get_artist_albums(artist['id'])
clear_screen(stdscr)
current_panel = albums_panel
current_panel.items = albums
current_panel.init()
current_panel.show()
current_panel.update()
[ 102 ]
Creating a Remote-Control Application with Spotify Chapter 2
try:
wrapper(main)
except KeyboardInterrupt:
print('Thanks for using this app, bye!')
Here, we do some initialization. Usually, curses don't register the key immediately. When it
is typed, this is called buffered mode; the user has to type something and then hit Enter. In
our application, we don't want this behavior; we want the key to be registered right after
the user types it. This is what cbreak does; it turns off the curses buffered mode.
We also use the noecho function to be able the read the keys and to control when we want
to show them on the screen.
The last curses setup we do is to turn on the keypad so curses will do the job of reading and
processing the keys accordingly, and returning constant values representing the key that
has been pressed. This is much cleaner and easy to read than trying to handle it yourself
and test key code numbers.
We create an instance of the DataManager class so we can get the data we need to be
displayed on the menus and perform authentication:
_data_manager = DataManager()
We call the show_search_screen function, passing the instance of the window; it will
render the search field on the screen and return the results to us. When the user is done
typing, the user input will be stored in the criteria variable.
After we get the criteria, we call get_artist_albums, which will first search an artist and
then get a list of the artist's albums and return a list of MenuItem objects.
[ 103 ]
Creating a Remote-Control Application with Spotify Chapter 2
When the list of albums is returned, we can create the other panels with the menus:
height, width = stdscr.getmaxyx()
artist = _data_manager.search_artist(criteria)
albums = _data_manager.get_artist_albums(artist['id'])
clear_screen(stdscr)
Here, we get the height and the width of the main window so we can create panels with the
same dimensions. albums_panel will display the albums and tracks_panel will display
the tracks; as I mentioned before, it will have the same dimensions as the main window and
both panels will start at row 0, column 0.
After that, we call clear_screen to prepare the window to render the menu window with
the albums:
albums_panel.items = albums
albums_panel.init()
albums_panel.update()
albums_panel.show()
current_panel = albums_panel
is_running = True
We first set the item's properties with the results of the albums search. We also call init on
the panel, which will internally run _initialize_items, format the labels and set the
currently selected item. We also call the update method, which will do the actual work of
printing the menu items in the window; lastly, we show how to set the panel to visible.
We also define the current_panel variable, which will hold the instance of the panel that
is currently being displayed on the terminal.
The is_running flag is set to True and it will be used in the application's main loop. We
will set it to False when we want to stop the application's execution.
[ 104 ]
Creating a Remote-Control Application with Spotify Chapter 2
key = stdscr.getch()
action = current_panel.handle_events(key)
doupdate: Curses keeps two data structures representing the physical screen (the
one you see on the terminal screen) and a virtual screen (the one keeping the next
updated). doupdate updates the physical screen so it matches the virtual screen.
update_panels: Updates the virtual screen after changes in the panel stack,
changes like hiding, show panels, and so on.
After updating the screen, we wait until a key is pressed using the getch function, and
assign the key pressed value to the key variable. The key variable is then passed to the
current panel's handle_events method.
If you remember the implementation of handle_events in the Menu class, it looks like this:
def handle_events(self, key):
if key == curses.KEY_UP:
self.previous()
elif key == curses.KEY_DOWN:
self.next()
elif key == curses.KEY_ENTER or key == NEW_LINE or key ==
CARRIAGE_RETURN:
selected_item = self.get_selected()
return selected_item.action
It handles KEY_DOWN, KEY_UP, and KEY_ENTER. If the key is KEY_UP or KEY_DOWN, it will
just update the position in the menu and set a newly selected item, and that will be updated
on the screen on the next loop interaction. If the key is KEY_ENTER, we get the selected item
and return its action function.
Remember that, for both panels, it will return a function that, when executed, will return a
tuple containing the item id and the item URI.
[ 105 ]
Creating a Remote-Control Application with Spotify Chapter 2
If the handle_events method of the current panel returned a callable action, we execute
it and get the result. Then, we check if the active panel is the first panel (with the albums).
In this case, we need to get a list of tracks for the selected album, so we call
get_album_tracklist in the DataManager instance.
We hide the current_panel, switch the current panel to the second panel (the tracks
panel), set the items property with the list of tracks, call the init method so the items are
formatted properly and a first item in the list is set as selected, and finally we call show so
the track's panel is visible.
In the event the current panel is the tracks_panel, we get the action results and invoke
play on the DataManager, passing the track URI. It will request the selected track to be
played on the device you have active on Spotify.
Now, we want a way of returning to the search screen. We do that when the user hits
the F12 function key:
if key == curses.KEY_F2:
current_panel.hide()
criteria = show_search_screen(stdscr)
artist = _data_manager.search_by_artist_name(criteria)
albums = _data_manager.get_artist_albums(artist['id'])
clear_screen(stdscr)
current_panel = albums_panel
current_panel.items = albums
current_panel.init()
current_panel.show()
[ 106 ]
Creating a Remote-Control Application with Spotify Chapter 2
For the if statement above, test if the user pressed the F12 function key; in this case, we
want to return to the search screen so that the user can search for a new artist. When the F12
key is pressed, we hide the current panel. Then, we call the show_search_screen function
so the search screen is rendered and the textbox will enter in edit mode, waiting for the
user's input.
When the user is done typing and hits Ctrl+ G or Enter, we search the artist. Then, we get
the artist's albums and we show the panel with a list of albums.
The last event that we want to handle is when the user press either the q or Q key, which
sets the is_running variable to False and the application closes:
if key == ord('q') or key == ord('Q'):
is_running = False
Finally, we call update on the current panel, so we redraw the items to reflect the changes
on the screen:
current_panel.update()
Outside the main function, we have the code snippet where we actually execute the main
function:
try:
wrapper(main)
except KeyboardInterrupt:
print('Thanks for using this app, bye!')
[ 107 ]
Creating a Remote-Control Application with Spotify Chapter 2
[ 108 ]
Creating a Remote-Control Application with Spotify Chapter 2
[ 109 ]
Creating a Remote-Control Application with Spotify Chapter 2
Here, you can use the arrow keys (Up and Down) to navigate albums, and press Enter to
select an album. Then, you will see the screen showing all the tracks of the selected album:
If this screen is the same, you can use the arrow keys (Up and Down) to select the track, and
Enter will send a request to play the song on the device you have Spotify active on.
[ 110 ]
Creating a Remote-Control Application with Spotify Chapter 2
Summary
We have covered a lot of ground in this chapter; we started by creating an application on
Spotify and learning our way around its developer's website. Then, we learned how to
implement the two types of authentication flow that Spotify supports: the client credentials
flow and the authorization flow.
In this chapter, we also implemented a whole module wrapper with some of the
functionality available from Spotify's REST API.
Then, we implemented a simple terminal client where users can search for artists, browse
the artist's albums and tracks, and finally play a song in the user's active device, which can
be a computer, mobile phone, or even a video game console.
In the next chapter, we are going to create a desktop application that shows the number of
votes given through Twitter hashtags.
[ 111 ]
Casting Votes on Twitter
3
In the previous chapter, we implemented a Terminal application that serves as a remote
control for the popular music service Spotify. In this application, we could search for artists,
browse albums, and browse the tracks in each album. Lastly, we could even request the
track to be played on the user's active device.
This time, we are going to develop an application that will integrate with Twitter, making
use of its REST API. Twitter is a social network that has been around since 2006 and there
are over 300 million active users. Private users, companies, artists, soccer clubs, you can find
almost everything on Twitter. But what makes Twitter so popular, I believe, is its simplicity.
Unlike blog posts, Twitter posts or tweets have to be short and get right to the point, and it
doesn't require too much time to prepare something to post. Another point that makes
Twitter so popular is the fact that the service is a great news source. If you want to keep
updated with what's going on in the world, politics, sports, technology, you name it,
Twitter is the place to be.
Apart from all that, Twitter has a fairly decent API for us developers and, to take advantage
of that, we are going to develop an application where users can cast votes using hashtags. In
our application, we are going to configure which hashtags we are going to monitor and it
will automatically, from time to time, fetch the latest tweets matching that hashtag, count
them, and display them in a user interface.
Casting Votes on Twitter Chapter 3
[ 113 ]
Casting Votes on Twitter Chapter 3
When the virtualenv environment has been created, you can activate it with the following
command:
. twittervotes/bin/activate
Great! Now let's set up the project's directory structure. It should look like the following:
twittervotes
├── core
│ ├── models
│ └── twitter
└── templates
Next, it is time to add our project's dependencies. Go ahead and create a file called
requirements.txt in the twittervotes directory with the following content:
Flask==0.12.2
oauth2==1.9.0.post1
PyYAML==3.12
requests==2.18.4
Rx==1.6.0
[ 114 ]
Casting Votes on Twitter Chapter 3
We are going to use Flask here to create a simple web application to perform the
Flask
authentication with Twitter.
This is a great package that will abstract a lot of the complexity when performing
oauth2
OAuth authentication.
PyYAML We are going to use this package to create and read config files in YAML format.
Requests Allow us to access the Twitter API over HTTP.
Finally, we are going to use Reactive Extensions for Python so we can reactively
Rx
update our UI soon as a new tweet count arrives.
When the file has been created, run the command pip install -r requirements.txt,
and you should see an output similar to the following:
[ 115 ]
Casting Votes on Twitter Chapter 3
If you run the command pip freeze, you will get a list of dependencies
in pip format and you will notice that the output lists more dependencies
that we actually added to the requirements file. The reason for that is
that the packages that our project requires also have dependencies and
they will also be installed. So do not worry if you have more packages
installed than you specified in your requirements file.
Now that our environment is set up, we can start creating our Twitter application. As usual,
before you start coding, make sure that you have your code under a source control system
such as Git; there are plenty of online services that will host your repositories for free.
In this way, you can roll back different versions of your projects and you don't have the risk
of losing your work if you have problems with your computers. With that said, let's create
our Twitter application.
[ 116 ]
Casting Votes on Twitter Chapter 3
After you create an account, head over to, sign in with your
login credentials, and you will land on a page where you can see a list of apps that you have
already created (the first time, you will probably have an empty list of apps), and on the
same page you will have the possibility of creating new apps. Click on the Create new
app button in the top-right corner and it will open up the following page:
In this form, there are three fields that are required—name, description, and website:
Name: This is the name of your application; it is also the name that will be
presented to the users of your application when performing authorization. The
name doesn't need to follow any specific naming convention, you can have
anything you want.
Description: As the name suggests, this is the description of your application.
This field will also be presented to the users of your application, so it is good to
have nice text describing your application. In this case, here we don't need much
text. Let's add Application to cast votes on Twitter using hashtags.
[ 117 ]
Casting Votes on Twitter Chapter 3
After filling in all the fields, you just need to check the Twitter Developer Agreement and
click the Create your Twitter application button.
If everything went well, you will be directed to another page where you can see more
details of your newly created application. Just below the name of the application, you will
see an area with tabs that shows settings and different pieces of information about the
application:
On the first tab, Details, we want to copy all the URLs that we are going to use to perform
the authentication. Scroll down to Application settings, and copy Request token URL,
Authorize URL, and Access token URL:
[ 118 ]
Casting Votes on Twitter Chapter 3
Great! Now let's head over to the Keys and Access Tokens tab and copy Consumer
Key and Consumer Secret:
Now that we have copied all the necessary information, we can create a configuration file
that is going to be used by our application. It is always good practice to keep all this in a
configuration file so we don't need to hardcode those URLs in our code.
For our application, we are going to use PyYAML, which will allow us to read and write
YAML files in a very simple manner. Our configuration file is quite simple so we will not
need to use any advanced features of the library, we just want to read the content and write,
and the data that we are going to add is quite flat; we will not have any nested objects or
lists of any kind.
[ 119 ]
Casting Votes on Twitter Chapter 3
Let's get the information that we obtained from Twitter when we created our app and add it
to the configuration file. Create a file called config.yaml in the application's
twittervotes directory with the following content:
Great! Now we are going to create the first Python code in our project. If you have followed
the previous chapters, the functions to read the configuration file will be familiar to you.
The idea is simple: we are going to read the configuration file, parse it, and create a model
that we can easily use to access the data we added to the config. First, we need to create the
configuration model.
There was a more extensive introduction to namedtuple in the previous chapter, so I will
not go into as much detail about it again; if you haven't been going through the second
chapter, it will suffice to know that namedtuple is a kind of class and this code will define a
namedtuple called Config with the fields specified in the array in the second argument.
[ 120 ]
Casting Votes on Twitter Chapter 3
Now it is time to create the functions that will do the actual work of reading the YAML file
and returning it to us. Create a file called config.py in twittervotes/core/. Let's get
started by adding the import statements:
import os
import yaml
We are going to use the os package to easily obtain the user's current directory and
manipulate paths. We also import PyYAML so we can read the YAML files and, lastly, from
the models module, we import the Config model that we just created.
Then we define two functions, starting with the _read_yaml_file function. This function
gets two arguments—the filename, which is the name of the config file that we want to
read, and also cls, which can be a class or namedtuple that we will use to store the
configuration data.
In this case, we are going to pass the Config—namedtuple, which has the same properties
as the YAML configuration file that we are going to read:
def _read_yaml_file(filename, cls):
core_dir = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(core_dir, '..', filename)
with open(file_path, mode='r', encoding='UTF-8') as file:
config = yaml.load(file)
return cls(**config)
First, we use the os.path.abspath function, passing as an argument the special variable
__file__. When a module is loaded, the variable __file__ will be set to the same name
as the module. That will allow us to easily find where to load the configuration file. So the
following snippet will return the path of the core module
/projects/twittervotes/core:
That will give us the flexibility of running this code from any location in our system.
[ 121 ]
Casting Votes on Twitter Chapter 3
We open the file in the reading mode using UTF-8 encoding and pass it to the yaml.load
function, assigning the results to the config variable. The config variable will be a
dictionary with all the data we have in the config file.
The last line of this function is the interesting part: if you recall, the cls argument was a
class or a namedtuple so we spread the values of the config dictionary as an argument.
Here, we are going to use the Config—namedtuple so cls(**config) is the same as
Config, (**config) and passing the arguments with ** will be the same as passing all the
arguments one by one:
Config(
consumer_key: ''
consumer_secret: ''
app_only_auth: ''
request_token_url:
''
authorize_url: ''
access_token_url: ''
api_version: '1.1'
search_endpoint: '')
Now we are going to add the second function we are going to need, the
read_config function:
def read_config():
try:
return _read_yaml_file('config.yaml', Config)
except IOError as e:
print(""" Error: couldn\'t file the configuration file
`config.yaml`
'on your current directory.
consumer_key: 'your_consumer_key'
consumer_secret: 'your_consumer_secret'
request_token_url:
''
access_token_url:
''
authorize_url: ''
api_version: '1.1'
search_endpoint: ''
""")
raise
[ 122 ]
Casting Votes on Twitter Chapter 3
This function is pretty straightforward; it just makes use of the _read_yaml_file function
that we just created, passing the config.yaml file in the first argument and also the
Config, namedtuple in the second argument.
We catch the IOError exception that will be thrown if the file doesn't exist in the
application's directory; in that case, we throw a help message showing the users of your
application how the config file should be structured.
The final touch is to import it into the __init__.py in the twittervotes/core directory:
from .config import read_config
Great, it worked just like we wanted! In the next section, we can start creating the code that
will perform the authentication.
Performing authentication
In this section, we are going to create the program that will perform authentication for us so
we can use the Twitter API. We are going to do that using a simple Flask application that
will expose two routes. The first is the root /, which will just load and render a simple
HTML template with a button that will redirect us to the Twitter authentication dialog.
The second route that we are going to create is /callback. Remember when we specified
the callback URL in the Twitter app configuration? This is the route that will be called after
we authorize the app. It will return an authorization token that will be used to perform
requests to the Twitter API. So let's get right into it!
[ 123 ]
Casting Votes on Twitter Chapter 3
Before we start implementing the Flask app, we need to add another model to our model's
module. This model will represent the request authorization data. Open the
models.py file in twittervotes/core/models and add the following code:
This will create a namedtuple called RequestToken with the fields oauth_token,
oauth_token_secret, and outh_callback_confirmed; this data will be necessary for us
to perform the second step of the authentication.
Lastly, open the __init__.py file in the twittervotes/core/models directory and let's
import the RequestToken namedtuple that we just created, as follows:
from .models import RequestToken
Now that we have the model in place, let's start creating the Flask application. Let's add a
very simple template to show a button that will start the authentication process.
Create a new directory in the twittervotes directory called templates and create a file
called index.html with the following content:
<html>
<head>
</head>
<body>
<a href="{{link}}"> Click here to authorize </a>
</body>
</html>
import yaml
[ 124 ]
Casting Votes on Twitter Chapter 3
First, we import the parser_qls from the urllib.parse module to parse the returned
query string, and the yaml module so we can read and write YAML configuration files. Then
we import everything we need to build our Flask application. The last third-party module
that we are going to import here is the oauth2 module, which will help us to perform the
OAuth authentication.
Lastly, we import our function read_config and the RequestToken namedtuple that we
just created.
Here, we create our Flask app and a few global variables that will hold values for the client,
consumer, and the RequestToken instance:
app = Flask(__name__)
client = None
consumer = None
req_token = None
The first function that we are going to create is a function called get_req_token with the
following content:
def get_oauth_token(config):
global consumer
global client
global req_token
consumer = oauth.Consumer(config.consumer_key,
config.consumer_secret)
client = oauth.Client(consumer)
if resp['status'] != '200':
raise Exception("Invalid response
{}".format(resp['status']))
request_token = dict(parse_qsl(content.decode('utf-8')))
req_token = RequestToken(**request_token)
[ 125 ]
Casting Votes on Twitter Chapter 3
This function gets as argument an instance to the configuration and the global statements
say to the interpreter that the consumer, client, and req_token used in the function will be
referencing the global variables.
We create a consumer object using the consumer key and the consumer secret that we
obtained when the Twitter app was created. When the consumer is created, we can pass it
to the client function to create the client, then we call the function request, which, as the
name suggests, will perform the request to Twitter, passing the request token URL.
When the request is complete, the response and the content will be stored in the variables
resp and content. Right after that, we test whether the response status is not 200 or
HTTP.OK; in that case, we raise an exception, otherwise we parse the query string to get the
values that have been sent back to us and create a RequestToken instance.
get_oauth_token(config)
url = f'{config.authorize_url}?oauth_token=
{req_token.oauth_token}'
We read the configuration file and pass it the get_oauth_token function. This function
will populate the global variable req_token with the oauth_token value; we need this
token to start the authorization process. Then we build the authorization URL with the
values of authorize_url obtained from the configuration file and the OAuth request
token.
Lastly, we use the render_template to render the index.html template that we created
and we also pass to the function a second argument, which is the context. In this case, we
are creating an item called link with the value set to url. If you remember the
index.html template, there is an "{{url}}" placeholder. This placeholder will be
replaced by the value that we assigned to link in the render_template function.
[ 126 ]
Casting Votes on Twitter Chapter 3
By default, Flask uses Jinja2 as a template engine but that can be changed to the engine of
your preference; we are not going into the details of how to do this in this book because it is
beyond our scope.
The last route that we are going to add is the /callback route and that will be the route
that will be called by Twitter after the authorization:
@app.route('/callback')
def callback():
global req_token
global consumer
config = read_config()
token = oauth.Token(req_token.oauth_token,
req_token.oauth_token_secret)
token.set_verifier(oauth_verifier)
return 'All set! You can close the browser window and stop the
server.'
The implementation of the callback route starts off by using global statements so we can use
the global variables req_token and consumer.
Now we get to the interesting part. After the authorization, Twitter will return an
outh_verifier so we get it from the request arguments and set it to the variable
oauth_verifier; we create a Token instance using the oauth_token and
oauth_token_secret that we obtained in the first part of our authorization process.
And we set the oauth_verifier in the Token object and finally create a new client that we
are going to use to perform a new request with.
[ 127 ]
Casting Votes on Twitter Chapter 3
We decode the data received from the request and add it to the access token variable and, to
wrap things up, we write the content of access_token to a file .twitterauth in the
twittervotes directory. This file is also in YAML format so we are going to add another
model and one more function in the config.py file to read the new settings.
Note that this process needs to be done just once. That is the reason that we store the data in
the .twitterauth file. Further requests need only to use the data contained in this file.
If you check the contents of the .twitterauth file, you should have something similar to
the following:
oauth_token: 31******95-**************************rt*****io
oauth_token_secret: NZH***************************************ze8v
screen_name: the8bitcoder
user_id: '31******95'
x_auth_expires: '0'
To finish the Flask application, we need to add the following code at the end of the file:
if __name__ == '__main__':
app.run(host='localhost', port=3000)
Let's add a new model to the models.py file in twittervotes/core/models/ with the
following content:
RequestAuth = namedtuple('RequestAuth', ['oauth_token',
'oauth_token_secret',
'user_id',
'screen_name',
'x_auth_expires', ])
Great! One more thing—we need to import the new model in the __init__.py file in the
twittervotes/core/models directory:
[ 128 ]
Casting Votes on Twitter Chapter 3
Now we can try the authentication. In the twittervotes directory, execute the script
twitter_auth.py. You should see the following output:
[ 129 ]
Casting Votes on Twitter Chapter 3
If you inspect the link with the browser development tools, you will see that the link is
pointing to the authorize endpoint and it is passing the oauth_token that we created:
Go ahead and click on the link and you will be sent to the authorization page:
[ 130 ]
Casting Votes on Twitter Chapter 3
If you click on the Authorize app button, you will be redirected back to localhost and a
success message will be displayed:
If you pay attention to the URL Twitter has sent back to us, you will find some information.
The important point here is the oauth_verifier that we will set to the request token and
we perform one last request to get the access token. Now you can close the browser, stop
the Flask app, and see the results in the file .twitterauth in the twittervotes directory:
oauth_token: 31*******5-KNAbN***********************K40
oauth_token_secret: d**************************************Y3
screen_name: the8bitcoder
user_id: '31******95'
x_auth_expires: '0'
Now, all the functionality that we implemented here is very useful if other users are going
to use our application; however, there's an easier way to obtain the access token if you are
authorizing your own Twitter app. Let's have a look at how that is done.
[ 131 ]
Casting Votes on Twitter Chapter 3
If you click on Create my access token, Twitter will generate the access token for you:
After the access token is created, you can just copy the data into the .twitterauth file.
[ 132 ]
Casting Votes on Twitter Chapter 3
We start off by creating a model class that will represent a hashtag. Create a file called
hashtag.py in the twittervotes/core/twitter directory with the following content:
class Hashtag:
def __init__(self, name):
self.name = name
self.total = 0
self.refresh_url = None
This is a very simple class. We can pass a name as an argument to the initializer; the name is
the hashtag without the hash sign (#). In the initializer, we define a few properties: the
name, which will be set to the argument that we pass to the initializer, then a property
called total that will keep the hashtag usage count for us.
Finally, we set the refresh_url. The refresh_url is going to be used to perform queries
to the Twitter API, and the interesting part here is that the refresh_url already contains
the id of the latest tweet that has been returned, so we can use that to fetch only tweets that
we haven't already fetched, to avoid counting the same tweet multiple times.
Perfect! Now go ahead and create a file called request.py in the twittervotes/core/
directory.
import requests
[ 133 ]
Casting Votes on Twitter Chapter 3
First, we import the oauth2 package that we are going to use to perform authentication; we
prepare the request, signing it with the SHA1 key. We also import time to set the OAuth
timestamp setting. We import the function parse_qsl, which we are going to use to parse
a query string so we can prepare a new request to search for the latest tweets, and the json
module so we can deserialize the JSON data that the Twitter API sends back to us.
Then, we import our own functions, read_config and read_req_auth, so we can read
both configuration files. Lastly, we import the json package to parse the results and the
requests package to perform the actual request to the Twitter search endpoint:
token = oauth.Token(
key=reqconfig.oauth_token,
secret=reqconfig.oauth_token_secret)
consumer = oauth.Consumer(
key=config.consumer_key,
secret=config.consumer_secret)
params = {
'oauth_version': "1.0",
'oauth_nonce': oauth.generate_nonce(),
'oauth_timestamp': str(int(time.time()))
}
params['oauth_token'] = token.key
params['oauth_consumer_key'] = consumer.key
params.update(url_params)
signature_method = oauth.SignatureMethod_HMAC_SHA1()
req.sign_request(signature_method, consumer, token)
return req.to_url()
This function will read both configuration files—the config.org configuration file
contains all the endpoint URLs that we need, and also the consumer keys. The
.twitterauth file contains the oauth_token and oauth_token_secret that we will use
to create a Token object that we will pass along with our request.
[ 134 ]
Casting Votes on Twitter Chapter 3
After that, we define some parameters. oauth_version should, according to the Twitter
API documentation, always be set to 1.0. We also send oauth_nonce, which is a unique
token that we must generate for every request, and lastly, oauth_timestamp, which is the
time at which the request was created. Twitter will reject a request that was created too long
before sending the request.
The last thing that we attach to the parameters is oauth_token, which is the token that is
stored in the .twitterath file, and the consumer key, which is the key that was stored in
the config.yaml file.
We perform a request to get an authorization and if everything goes right, we sign the
request with an SHA1 key and return the URL of the request.
Now we are going to add the function that will perform a request to search for a specific
hashtag and return the results to us. Let's go ahead and add another function called
execute_request:
def execute_request(hashtag):
config = read_config()
if hashtag.refresh_url:
refresh_url = hashtag.refresh_url[1:]
url_params = dict(parse_qsl(refresh_url))
else:
url_params = {
'q': f'#{hashtag.name}',
'result_type': 'mixed'
}
data = requests.get(url)
results = json.loads(data.text)
This function will get a Hashtag object as an argument and the first thing we do in this
function is to read the configuration file. Then we check whether the Hashtag object has a
value in the refresh_url property; in that case, we are going remove the ? sign in the
front of the refresh_url string.
[ 135 ]
Casting Votes on Twitter Chapter 3
After that, we use the function parse_qsl to parse the query string and return a list of
tuples where the first item in the tuple is the name of the parameter and the second is its
value. For example, let's say we have a query string that looks like this:
'param1=1¶m2=2¶m3=3'
If we use the parse_qsl, passing as an argument this query string, we will get the
following list:
[('param1', '1'), ('param2', '2'), ('param3', '3')]
And then if we pass this result to the dict function, we will get a dictionary like this:
{'param1': '1', 'param2': '2', 'param3': '3'}
And after parsing and transforming it into a dictionary, we can use it to get refreshed data
for the underlying hashtag.
If the Hashtag object does not have the property refresh_url set, then we simply define a
dictionary where the q is the hashtag name and the result type is set to mixed to tell the
Twitter API that it should return popular, recent, and real-time tweets.
After defining the search parameters, we use the prepare_request function that we
created above to authorize the request and sign it; when we get the URL back, we perform
the request using the URL we get back from the prepare_request function.
We make use of the json.loads function to parse the JSON data and return a tuple
containing the first item, the hashtag itself; the second item will be the results we get back
from the request.
The final touch, as usual, is to import the execute_request function in the __init__.py
file in the core module:
from .request import execute_request
[ 136 ]
Casting Votes on Twitter Chapter 3
The output above is much bigger than this but a lot of it has been omitted; I just wanted to
demonstrate how the function works.
With that said, we are going to define some rules for these arguments. First, we will limit
the maximum number of hashtags that we are going to monitor, so we are going to add a
rule that no more than four hashtags can be used.
If the user specifies more than four hashtags, we will simply display a warning on the
Terminal and pick the first four hashtags. We also want to remove the duplicated hashtags.
[ 137 ]
Casting Votes on Twitter Chapter 3
When showing these warning messages that we talked about, we could simply print them
on the Terminal and it would definitely work; however, we want to make things more
interesting, so we are going to use the logging package to do it. Apart from that,
implementing a proper logging will give us much more control over what kind of log we
want to have and also how we want to present it to the users.
Before we start implementing the command-line parser, let's add the logger. Create a file
called app_logger.py in the twittervotes/core directory with the following content:
import os
import logging
from logging.config import fileConfig
def get_logger():
core_dir = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(core_dir, '..', 'logconfig.ini')
fileConfig(file_path)
return logging.getLogger('twitterVotesLogger')
This function doesn't do much but first we import the os module, then we import the
logging package, and lastly, we import the function fileConfig, which reads the logging
configuration from a config file. This configuration file has to be in
the configparser format and you can get more information about this format at https://
docs.python.org/3.6/library/logging.config.html#logging-config-fileformat.
After we read the configuration file, we just return a logger called twitterVotesLogger.
Let's see what the configuration file for our application looks like. Create a file called
logconfig.ini in the twittervotes directory with the following content:
[loggers]
keys=root,twitterVotesLogger
[handlers]
keys=consoleHandler
[formatters]
keys=simpleFormatter
[logger_root]
level=INFO
handlers=consoleHandler
[logger_twitterVotesLogger]
level=INFO
[ 138 ]
Casting Votes on Twitter Chapter 3
handlers=consoleHandler
qualname=twitterVotesLogger
[handler_consoleHandler]
class=StreamHandler
level=INFO
formatter=simpleFormatter
args=(sys.stdout,)
[formatter_simpleFormatter]
format=[%(levelname)s] %(asctime)s - %(message)s
datefmt=%Y-%m-%d %H:%M:%S
So here we define two loggers, root and twitterVotesLogger; the loggers are
responsible for exposing methods that we can use at runtime to log messages. It is also
through the loggers that we can set the level of severity, for example, INFO, DEBUG and so
on. Lastly, the logger passes the log messages along to the appropriated handler.
In the definition of our twitterVotesLogger, we set the level of severity to INFO, we set
the handler to consoleHandler (we are going to describe this very soon), and we also set a
qualified name that will be used when we want to get hold of the twitterVotesLogger.
The next component in the logging configuration is the handler. Handlers are the
component that sends the log messages of a specific logger to a destination. We defined a
handler called consoleHandler of type StreamHandler, which is a built-in handler of the
logging module. The StreamHandler sends out log messages to streams such
as sys.stdout, sys.stderr, or a file. This is perfect for us because we want to send
messages to the Terminal.
In the consoleHandler, we also set the severity level to INFO and also we set the formatter
which is set to the customFormatter; then we set the value for args to (sys.stdout, ).
Args specify where the log messages will be sent to; in this case, we set only sys.stdout
but you can add multiple output streams if you need.
[ 139 ]
Casting Votes on Twitter Chapter 3
Now that we have the logging in place, let's add the functions that will parse the command
line. Create a file cmdline_parser.py in twittervotes/core and add some imports:
from argparse import ArgumentParser
Then we will need to add a function that will validate the command-line arguments:
def validated_args(args):
logger = get_logger()
unique_hashtags = list(set(args.hashtags))
args.hashtags = unique_hashtags
if len(args.hashtags) > 4:
logger.error('Voting app accepts only 4 hashtags at the
time')
args.hashtags = args.hashtags[:4]
return args
validate_args functions have only one parameter and it is the arguments that have been
parsed by the ArgumentParser. The first thing we do in this function is to get hold of the
logger that we just created, so we can send log messages to inform the user about possible
problems in the command-line arguments that have been passed to the application.
Next, we transform the list of hashtags into a set so all the duplicated hashtags are removed
and then we transform it back to a list. After that, we check whether the number of unique
hashtags is less than the original number of hashtags that have been passed on the
command line. That means that we had duplication and we log a message to inform the
user about that.
[ 140 ]
Casting Votes on Twitter Chapter 3
The last verification we do is to make sure that a maximum of four hashtags will be
monitored by our application. If the number of items in the hashtag list is greater than four,
then we slice the array, getting only the first four items, and we also log a message to
inform the user that only four hashtags will be displayed.
required.add_argument(
'-ht', '--hashtags',
nargs='+',
required=True,
dest='hashtags',
help=('Space separated list specifying the '
'hashtags that will be used for the voting.\n'
'Type the hashtags without the hash symbol.'))
args = argparser.parse_args()
return validated_args(args)
We saw how the ArgumentParser works when we were developing the application in the
first chapter, the weather application. However, we can still go through what this function
does.
Note that we don't really need to create this extra group; however, I find
that it helps to keep the code more organized and easier to maintain in
case it is necessary to add new options in the future.
We define only one argument, hashtags. In the definition of the hashtags argument,
there is an argument called nargs and we have set it to +; this means that I can pass an
unlimited number of items separated by spaces, as follows:
--hashtags item1 item2 item3
[ 141 ]
Casting Votes on Twitter Chapter 3
The last thing we do in this function is to parse the arguments with the parse_args
function and run the arguments through the validate_args function that has been shown
previously.
Now we need to create a class that will help us to manage hashtags and perform tasks such
as keeping the score count of hashtags, updating its value after every request. So let's go
ahead and create a class called HashtagStatsManager. Create a file called
hashtagstats_manager.py in twittervotes/core/twitter with the following
content:
from .hashtag import Hashtag
class HashtagStatsManager:
if not hashtags:
raise AttributeError('hashtags must be provided')
total = len(statuses)
if total > 0:
self._hashtags.get(hashtag.name).total += total
self._hashtags.get(hashtag.name).refresh_url =
refresh_url
@property
def hashtags(self):
return self._hashtags
[ 142 ]
Casting Votes on Twitter Chapter 3
This class is also very simple: in the constructor, we get a list of hashtags and initialize a
property, _hashtags, which will be a dictionary where the key is the name of the hashtag
and the value is an instance of the Hashtag class.
The update method gets a tuple containing a Hashtag object and the results are returned by
the Twitter API. First, we unpack the tuple values and set it to the hashtag and results
variables. The results dictionary has two items that are interesting to us. The first is the
search_metadata; in this item, we will find the refresh_url and the statuses contain a
list of all tweets that used the hashtag that we were searching for.
So we get the values for the search_metadata, the refresh_url, and lastly the
statuses. Then we count how many items there are in the statuses list. If the number of
items on the statuses list is greater than 0, we update the total count for the underlying
hashtag as well as its refresh_url.
Then we import the HashtagStatsManager class that we just created in the __init__.py
file in the twittervotes/core/twitter directory:
from .hashtagstats_manager import HashtagStatsManager
The heart of this application is the class Runner. This class will perform the execution of a
function and queue it in the process pool. Every function will be executed in parallel in a
different process, which will make the program much faster than if I executed these
functions one by one.
class Runner:
observables = []
[ 143 ]
Casting Votes on Twitter Chapter 3
The class Runner has an initializer taking three arguments; they are all functions that will
be called in different statuses of the execution. on_success will be called when the
execution of the item has been successful, on_error when the execution of one function has
failed for some reason, and finally on_complete will be called when all the functions in the
queue have been executed.
There is also a method called exec that takes a function as the first argument, which is the
function that will be executed, and the second argument is a list of Hashtag instances.
There are a few interesting things in the Runner class. First, we are using the
concurrent.futures module, which is a really nice addition to Python and has been
around since Python 3.2; this module provides ways of executing callables asynchronously.
If you want to read more about the GIL, you can check out the following wiki page: https:/
/wiki.python.org/moin/GlobalInterpreterLock.
Since we are not doing any I/O-bound operations, we use ProcessPoolExecutor. Then,
we loop through the values of the items, which is a dictionary containing all the hashtags
that our application is monitoring. And for every hashtag, we pass it to the submit function
of the ProcessPollExecutor along with the function that we want to execute; in our case,
it will be the execute_request function defined in the core module of our application.
[ 144 ]
Casting Votes on Twitter Chapter 3
The submit function, instead of returning the value returned by the execute_request
function, will return a future object, which encapsulates the asynchronous execution of the
execute_request function. The future object provides methods to cancel an execution,
check the status of the execution, get the results of the execution, and so on.
Now, we want a way to be notified when the executions change state or when they finish.
That is where reactive programming comes in handy.
Here, we get the future object and create an Observable. Observables are the core of
reactive programming. An Observable is an object that can be observed and emit events at
any given time. When an Observable emits an event, all observers that subscribed to that
Observable will be notified and react to those changes.
This is exactly what we are trying to achieve here: we have an array of future executions
and we want to be notified when those executions change state. These states will be
handled by the functions that we passed as an argument to the Runner
initializer—_on_sucess, _on_error, and _on_complete.
Perfect! Let's import the Runner class into __init__.py in the twittervotes/core
directory:
from .runner import Runner
The last piece of our project is to add the entry point of our application. We are going to add
the user interface using the Tkinter package from the standard library. So let's start
implementing it. Create a file called app.py in the twittervotes directory, and let's start
by adding some imports:
from core import parse_commandline_args
from core import execute_request
from core import Runner
[ 145 ]
Casting Votes on Twitter Chapter 3
We also import the HashtagStatsManager to manage the hashtag voting results for us.
self._manager = HashtagStatsManager(hashtags)
self._runner = Runner(self._on_success,
self._on_error,
self._on_complete)
So here, we create a class, Application, that inherits from Frame. The initializer takes two
arguments: hashtags, which are the hashtags that we are going to monitor, and the master
argument, which is an object of type Tk.
Then we have a dictionary comprehension that will create a dictionary where the keys are
the hashtags and the values are a Tkinter variable of type string, which in the Tkinter
world is called StringVar. We do that so it will be easier to update the labels with the
results later on.
[ 146 ]
Casting Votes on Twitter Chapter 3
We call the methods set_header and create_labels that we are going to implement
shortly and finally we call pack. The pack function will organize widgets such as buttons
and labels and place them in the parent widget, in this case, the Application.
Then we define a button that will execute the function _fetch_data when clicked and
we use pack to place the button at the bottom of the frame:
def set_header(self):
title = Label(self,
text='Voting for hasthags',
font=("Helvetica", 24),
height=4)
title.pack()
Here's the set_header method that I mentioned earlier; it simply creates Label objects
and places them at the top of the frame.
First, we create a Label, and the interesting part is the textvariable argument; we set it
to value, which is a Tkinter variable related to a specific hashtag. Then we place the
Label in the frame and, lastly, we set the value of the label using the function set.
[ 147 ]
Casting Votes on Twitter Chapter 3
Then we need to add a method that will update the Labels for us:
def _update_label(self, data):
hashtag, result = data
total = self._manager.hashtags.get(hashtag.name).total
self._items[hashtag.name].set(
f'#{hashtag.name}\nNumber of votes: {total}')
The _update_label, as the name suggests, updates the label of a specific hashtag. The data
argument is the results returned by the Twitter API and we get the total number of the
hashtags from the manager. Finally, we use the set function again to update the label.
Let's add another function that will actually do the work of sending the requests to the
Twitter API:
def _fetch_data(self):
self._runner.exec(execute_request,
self._manager.hashtags)
This method will call the method exec of the Runner to execute the function that performs
the requests to the Twitter API.
Then we need to define the methods that will handle the events emitted by the
Observables created in the Runner class; we start by adding the method that will handle
execution errors:
def _on_error(self, error_message):
raise Exception(error_message)
This is a helper method just to raise an exception in case something goes wrong with the
execution of the requests.
Then we add another method that handles when the execution of an Observable has been
successful:
def _on_success(self, data):
hashtag, _ = data
self._manager.update(data)
self._update_label(data)
[ 148 ]
Casting Votes on Twitter Chapter 3
The _on_success method is going to be called when one execution from the Runner
finished successfully, and it will just update the manager with the new data and also update
the label in the UI.
Lastly, we define a method that will handle when all the executions have been completed:
def _on_complete(self):
pass
The _on_complete will be called when all the executions of the Runner finish. We are not
going to be using it so we just use the pass statement.
Now it is time to implement the function that will set up the application and initialize the
UI—the function start_app:
def start_app(args):
root = Tk()
This function creates the root application, sets the title, defines its dimensions, and also calls
the mainloop function so the application keeps running.
if __name__ == '__main__':
main()
[ 149 ]
Casting Votes on Twitter Chapter 3
The main function is pretty simple. First, we parse the command-line arguments, then we
start the application, passing the command-line arguments to it.
Let's say we want the voting process to run for 3 minutes and it will monitor the hashtags
#debian, #ubuntu, and #arch:
[ 150 ]
Casting Votes on Twitter Chapter 3
And if you click the Update button, the count for every hashtag will be updated.
[ 151 ]
Casting Votes on Twitter Chapter 3
Summary
In this chapter, we developed an application to cast votes on Twitter and we learned the
different concepts and paradigms of the Python programming language.
By creating the hashtag voting application, you have learned how to create and configure a
Twitter app and also how to implement a three-legged OAuth authentication to consume
data from the Twitter API.
We also learned how to use the logging module to show informational messages to the
users of our application. Like the previous modules, we also created a command-line parser
using the ArgumentParser module in the standard library.
We also had an introduction to reactive programming using the Rx (Reactive Extensions for
Python) module. Then we used the concurrent.futures module to enhance the
performance of our application, running multiple requests to the Twitter API in parallel.
In the next chapter, we are going to build an application that will fetch exchange rate data
from the site to perform currency conversion.
[ 152 ]
Exchange Rates and the
4
Currency Conversion Tool
In the previous chapter, we built a really cool application to count votes on Twitter and
learned how to authenticate and consume the Twitter API using Python. We also had a
good introduction to how to use Reactive Extensions for Python. In this chapter, we are
going to create a terminal tool that will fetch exchange rates for the current day from
fixer.io and use this information to convert the value between different currencies.
Our project starts out by creating a framework around the API; when that is in place, we are
going to create a terminal application where we can perform currency conversion. All the
data that we fetch from the fixer.io is going to be stored in a MongoDB database, so we
can perform conversions without doing requests to fixer.io all the time. This will
increase the performance of our application.
In the previous chapters, we used virtualenv to create our virtual environment; however,
Kenneth Reitz (the creator of the popular package requests) created pipenv.
pipenv is for Python what NPM is for Node.js. However, pipenv is used for much more
than package management, and it also creates and manages a virtual environment for you.
In my opinion, there are a lot of advantages of the old development workflows, but for me,
there are two things that stand out: the first is that you no longer need two different tools
(pip, virtualenv), and the second is that it is much simpler to have all these great features
in just one place.
Another thing that I really like about pipenv is the use of Pipfile. Sometimes, it is really
hard to work with requirement files. Our production environment and development
environment have the same dependencies, and you end up having to maintain two
different files; plus, every time you need to remove one dependency, you will need to edit
the requirement file manually.
With pipenv, you don't need to worry about having multiple requirement files.
Development and production dependencies are placed in the same file, and pipenv also
takes care of updating the Pipfile.
[ 154 ]
Exchange Rates and the Currency Conversion Tool Chapter 4
We are not going to go through all the different options because that is beyond the scope of
this book, but while we are creating our environment, you will acquire a good knowledge
of the basics.
The first step is to create a directory for our project. Let's create a directory called
currency_converter:
Now that you are inside the currency_converter directory, we are going to use pipenv
to create our virtual environment. Run the following command:
pipenv --python python3.6
[ 155 ]
Exchange Rates and the Currency Conversion Tool Chapter 4
This will create a virtual environment for the project living in the current directory and will
use Python 3.6. The --python option also accepts a path to where you installed Python. In
my case, I always download the Python source code, build it, and install it in a different
location, so this is very useful for me.
You could also use the --three option, which would use the default Python3 installation
on your system. After running the command, you should see the following output:
If you have a look at the contents of the Pipfile, you should have something similar to the
following:
[[source]]
url = ""
verify_ssl = true
name = "pypi"
[dev-packages]
[packages]
[requires]
python_version = "3.6"
[ 156 ]
Exchange Rates and the Currency Conversion Tool Chapter 4
This file starts defining where to get the packages from, and in this case, it will download
packages from pypi. Then, we have a place for the development dependencies of our
project, and in packages, the production dependencies. Lastly, it says that this project
requires Python version 3.6.
Great! Now you can use some commands. For example, if you want to know which virtual
environment the project uses, you can run pipenv --venv; you will see the following
output:
If you want to activate the virtual environment for the project, you can use the
shell command, as follows:
Perfect! With the virtual environment in place, we can start adding our project's
dependencies.
[ 157 ]
Exchange Rates and the Currency Conversion Tool Chapter 4
As you can see, pipenv installs requests as well as all its dependencies.
The author of pipenv is the same developer who created the popular
requests library. In the installation output, you can see an easter egg,
saying PS: You have excellent taste!.
The other dependency that we need to add to our project is pymongo so that we can connect
and manipulate data in a MongoDB database.
[ 158 ]
Exchange Rates and the Currency Conversion Tool Chapter 4
Let's have a look at the Pipfile and see how it looks now:
[[source]]
url = ""
verify_ssl = true
name = "pypi"
[dev-packages]
[packages]
requests = "*"
pymongo = "*"
[requires]
python_version = "3.6"
As you can see, under the packages folder, we have now our two dependencies.
Not much has changed in comparison with installing packages with pip. The exception is
that now installing and removing dependencies will automatically update the Pipfile.
[ 159 ]
Exchange Rates and the Currency Conversion Tool Chapter 4
Another command that is very useful is the graph command. Run the following command:
pipenv graph
As you can see, the graph command is very helpful when you want to know what the
dependencies of the packages you have installed are. In our project, we can see that
pymongo doesn't have any extra dependencies. However, requests has four
dependencies: certifi, chardet, idna, and urllib3.
Now that you have had a great introduction to pipenv, let's have a look at what this
project's structure will look like:
currency_converter
└── currency_converter
├── config
├── core
The top currency_converter is the application's root directory. Then, one level down
we have another currency_converter and that is the currency_converter module that
we are going to create.
Inside the currency_converter module directory, we have a core which contains the
application core functionality, for example, a command line argument parser, helper
functions to handle data, and so on.
[ 160 ]
Exchange Rates and the Currency Conversion Tool Chapter 4
We have also configured, as with the other projects, which project will contain functions to
read YAML configuration files; finally, we have HTTP, which have all the functions that
will perform HTTP requests to the fixer.io REST API.
Now that we have learned how to use pipenv and how it will help us to be more
productive, we can install the initial dependencies to our project. We created the project's
directory structure, too. The only missing piece of the puzzle is installing MongoDB.
I'm using Linux Debian 9 and I can easily just install this using Debian's package manager
tool:
sudo apt install mongodb
You will find MongoDB in the package repositories of the most popular Linux distributions,
and if you are using Windows or macOS, you can see the instructions in the following
links:
After installation, you can verify that everything is working properly using the MongoDB
client. Open a terminal and just run the mongo command.
[ 161 ]
Exchange Rates and the Currency Conversion Tool Chapter 4
We obviously need requests so that we can perform requests to the fixer.io endpoints,
and we are also importing HTTPStatus from the HTTP module so we can return the correct
HTTP status code; also be a bit more verbose in our code. It's much nicer and easier to read
the HTTPStatus.OK return than only 200.
Lastly, we import the json package so that we can parse the JSON content that we get from
fixer.io into Python objects.
Next, we are going to add our first function. This function will return the current exchange
rates given a specific currency:
def fetch_exchange_rates_by_currency(currency):
response = requests.get(f'
{currency}')
if response.status_code == HTTPStatus.OK:
return json.loads(response.text)
elif response.status_code == HTTPStatus.NOT_FOUND:
raise ValueError(f'Could not find the exchange rates for:
{currency}.')
elif response.status_code == HTTPStatus.BAD_REQUEST:
raise ValueError(f'Invalid base currency value:
{currency}')
else:
raise Exception((f'Something went wrong and we were unable
to fetch'
f' the exchange rates for: {currency}'))
This function gets a currency as an argument and starts off by sending a request to
the fixer.io API to get the latest exchange rates using the currency as a base, which was
given as an argument.
If the response was HTTPStatus.OK (200), we use the load function from the JSON module
to parse the JSON response; otherwise, we raise exceptions depending on the error that
occurs.
[ 162 ]
Exchange Rates and the Currency Conversion Tool Chapter 4
[ 163 ]
Exchange Rates and the Currency Conversion Tool Chapter 4
'ZAR': 4.1853}}
The only thing we need to import is the MongoClient. The MongoClient will be
responsible for opening a connection with our database instance.
Now, we need to add the DbClient class. The idea of this class is to serve as a wrapper
around the pymongo package functions and provide a simpler set of functions, abstracting
some of the repetitive boilerplate code when working with pymongo:
class DbClient:
a class called DbClient and its constructor gets two arguments, db_name and
default_collection. Note that, in MongoDB, we don't need to create the database and
the collection before using it. When we try to insert data for the first time, the database and
the collection will be created for us.
This might seem strange if you are used to working with SQL databases such as MySQL or
MSSQL where you have to connect to the server instance, create a database, and create all
the tables before using it.
[ 164 ]
Exchange Rates and the Currency Conversion Tool Chapter 4
Then, we are going to add two methods, connect and disconnect, to the database:
def connect(self):
self._client = MongoClient('mongodb://127.0.0.1:27017/')
self._db = self._client.get_database(self._db_name)
def disconnect(self):
self._client.close()
The connect method will use the MongoClient connecting to the database instance at our
localhost, using the port 27017 which is the default port that MongoDB runs right after the
installation. These two values might be different for your environment. The disconnect
method simply calls the method close to the client and, as the name says, it closes the
connection.
Now, we are going to add two special functions, __enter__ and __exit__:
def __enter__(self):
self.connect()
return self
if exec_type:
raise exec_type(exec_value)
return self
We want the DbClient class to be used within its own context, and this is achieved by
using a context manager and with the with statement. The basic implementation of a
context manager is done by implementing these two functions, __enter__ and __exit__.
__enter__ will be called when we enter the context that the DbClient is running. In this
case, we are going to call the connect method to connect to our MongoDB instance.
[ 165 ]
Exchange Rates and the Currency Conversion Tool Chapter 4
The __exit__ method, on the other hand, is called when the current context is terminated.
The context can be terminated by normal causes or by some exception that has been thrown.
In our case, we disconnect from the database and, if exec_type is not equal to None, which
means that if some exception has occurred, we raise that exception. This is necessary,
otherwise, exceptions occurring within the context of the DbClient would be suppressed.
return self._db[self._default_collection]
This method will simply check if we have defined a default_collection. If not, it will
throw an exception; otherwise, we return the collection.
We need just two methods to finish this class, one to find items in the database and another
to insert or update data:
def find_one(self, filter=None):
collection = self._get_collection()
return collection.find_one(filter)
collection.find_one_and_update(
filter,
{'$set': document},
upsert=upsert)
The find_one method gets one optional argument called filter, which is a dictionary with
criteria that will be used to perform the search. If omitted, it will just return the first item in
the collection.
There are a few more things going on in the update method. It gets three
arguments: filter, document, and the optional argument, upsert.
The filter argument is exactly the same as the find_one method; it is a criterion that will
be used to search the collection's item that we want to update.
The document argument is a dictionary with the fields that we want to update in the
collection's item or insert.
[ 166 ]
Exchange Rates and the Currency Conversion Tool Chapter 4
Lastly, the optional argument upsert, when set to True, means that if the item that we are
trying to update doesn't exist in the database's collection, then we are going to perform an
insert operation and add the item to the collection.
The method starts off by getting the default collection and then uses the
collection's find_on_and_update method, passing the filter to the dictionary with the
fields that we want to update and also the upsert option.
There are some things we need to implement in order to start creating the command line
parser. One functionality that we are going to add is the possibility of setting a default
currency, which will avoid user of our application always having to specify the base
currency to perform currency conversions.
To do that, we are going to create an action, We have seen how actions work in Chapter 1,
Implementing the Weather Application, but just to refresh our minds, actions are classes that
can be bound to command line arguments to execute a certain task. These actions are called
automatically when the argument is used in the command line.
[ 167 ]
Exchange Rates and the Currency Conversion Tool Chapter 4
Before going into the development of custom actions, we need to create a function that will
fetch the configuration of our application from the database. First, we are going to create a
custom exception that will be used to raise errors when we cannot retrieve the configuration
from the database. Create a file named config_error.py in
the currency_converter/currency_converter/config directory with the following
contents:
class ConfigError(Exception):
pass
Perfect! This is all we need to create our custom exception. We could have used a built-in
exception, but that would have been too specific to our application. It is always a good
practice to create custom exceptions for your application; it will make your life and the life
of your colleagues much easier when troubleshooting bugs.
def get_config():
config = None
if config is None:
error_message = ('It was not possible to get your base
currency, that '
'probably happened because it have not been
'
'set yet.\n Please, use the option '
'--setbasecurrency')
raise ConfigError(error_message)
return config
Here, we start off by adding from the import statements. We start importing the
ConfigError custom exception that we just created and we also import the DbClient class
so we can access the database to retrieve the configuration for our application.
[ 168 ]
Exchange Rates and the Currency Conversion Tool Chapter 4
Then, we define the get_config function. This function will not take any argument, and
the function starts by defining a variable config with a None value. Then, we use the
DbClient to connect to the exchange_rate database and use the collection named
config. inside the DbClient context, we use the find_one method without any argument,
which means that the first item in that config collection will be returned.
If the config variable is still None, we raise an exception saying to the user that there's no
configuration in the database yet and that it is necessary to run the application again with
the --setbasecurrency argument. We are going to implement the command line
arguments in a short while. If we have the value of the config, we just return it.
Now, let's start adding our first action, which will set the default currency. Add a file called
actions.py in the currency_converter/currency_converter/core directory:
import sys
from argparse import Action
from datetime import datetime
First, we import sys so we can terminate the program's execution if something goes wrong.
Then, we import the Action from the argparse module. We need to create a class
inheriting from Action when creating custom actions. We also import datetime because
we are going to add functionality to check if the exchange rates that we are going to use are
outdated.
Then, we import some of the classes and functions that we created. We start with the
DbClient so we can fetch and store data in the MongoDB,
then fetch_exchange_rates_by_currency to fetch fresh data from fixer.io when
necessary. Finally, we import a helper function called get_config so we can get the
default currency from the config collection in the database.
[ 169 ]
Exchange Rates and the Currency Conversion Tool Chapter 4
Here, we define the SetBaseCurrency class, inheriting from Action, and we also add a
constructor. It doesn't do much; it just all the constructor of the base class.
Now, we need to implement a special method called __call__. It will be called when the
argument that the action is bound to is parsed:
def __call__(self, parser, namespace, value, option_string=None):
self.dest = value
try:
with DbClient('exchange_rates', 'config') as db:
db.update(
{'base_currency': {'$ne': None}},
{'base_currency': value})
This method gets four arguments, and the parser is an instance of the ArgumentParser
that we are going to create shortly. namespace is an object which is the result of the
argument parser; we went through namespace objects in detail in Chapter 1, Implementing
the Weather Application. The value is the value that has been passed to the underlying
argument and lastly, the option_string is the argument that the action is bound to.
We start the method by setting the value, the destination variable for the argument, and
then create an instance of the DbClient. Note that we are using the with statement here, so
we run the update within the DbClient context.
Then, we call the update method. Here, we are passing two arguments to the update
method, the first being filter. When we have {'base_currrency': {'$ne': None}},
it means that we are going to update an item in the collection where the base currency is not
equal to None; otherwise, we are going to insert a new item. This is the default behavior of
the update method in the DbClient class because we have the upsert option set to True
by default.
[ 170 ]
Exchange Rates and the Currency Conversion Tool Chapter 4
When we finish updating, we print the message to the user saying that the default currency
has been set and we exit the execution of the code when we hit the finally clause. If
something goes wrong, and for some reason, we cannot update the config collection, an
error will be displayed and we exit the program.
As with the class before, we define the class and inherit from Action. The constructor only
calls the constructor in the base class:
def __call__(self, parser, namespace, value, option_string=None):
try:
config = get_config()
base_currency = config['base_currency']
print(('Fetching exchange rates from fixer.io'
f' [base currency: {base_currency}]'))
response =
fetch_exchange_rates_by_currency(base_currency)
response['date'] = datetime.utcnow()
We also need to implement the __call__ method, which will be called when using the
argument that this action will be bound to. We are not going through the method
arguments again because it is exactly the same as the previous one.
The method starts by setting the value to True for the destination property. The argument
that we are going to use to run this action will not require arguments and it will default to
False, so if we use the argument, we set it to True. It is just a way of stating that we have
used that argument.
[ 171 ]
Exchange Rates and the Currency Conversion Tool Chapter 4
Then, we get the configuration from the database and get the base_currency. We show a
message to the user saying that we are fetching the data from fixer.io and then we use
our fetch_exchange_rates_by_currency function, passing the base_currency to it.
When we get a response, we change the date to UTC time so it will be easier for us to
calculate if the exchange rate for a given currency needs to be updated.
Then, we create another instance of the DbClient and use the update method with two
arguments. The first one is filter, so it will change any item in the collection that matches
the criteria, and the second argument is the response that we get from fixer.io API.
After everything is done, we hit the finally clause and terminate the program's execution.
If something goes wrong, we show a message to the user in the terminal and terminate the
program's execution.
class Currency(Enum):
AUD = 'Australia Dollar'
BGN = 'Bulgaria Lev'
BRL = 'Brazil Real'
CAD = 'Canada Dollar'
CHF = 'Switzerland Franc'
CNY = 'China Yuan/Renminbi'
CZK = 'Czech Koruna'
DKK = 'Denmark Krone'
GBP = 'Great Britain Pound'
HKD = 'Hong Kong Dollar'
HRK = 'Croatia Kuna'
HUF = 'Hungary Forint'
[ 172 ]
Exchange Rates and the Currency Conversion Tool Chapter 4
[ 173 ]
Exchange Rates and the Currency Conversion Tool Chapter 4
From the top, we import sys, so that can we exit the program if something is not right. We
also include the ArgumentParser so we can create the parser; we also import
the UpdateforeignerExchangeRates and SetBaseCurrency actions that we just
created. The last thing in the Currency enumeration is that we are going to use it to set
valid choices in some arguments in our parser.
argparser = ArgumentParser(
prog='currency_converter',
description=('Tool that shows exchange rated and perform '
'currency convertion, using
data.'))
The first thing we do here is get only the names of the Currency enumeration's keys; this
will return a list like this:
Here, we finally create an instance of the ArgumentParser and we pass two arguments:
prog, which is the name of the program, we can call it currency_converter, and the
second is description(the description that will be displayed to the user when the help
argument is passed in the command line).
[ 174 ]
Exchange Rates and the Currency Conversion Tool Chapter 4
The first argument that we define is --setbasecurrency. It will store the currency in the
database, so we don't need to specify the base currency all the time in the command line.
We specify that this argument will be stored as a string and the value that the user enters
will be stored in an attribute called base_currency.
We also set the argument choices to the currency_options that we defined in the
preceding code. This will ensure that we can only pass currencies matching the Currency
enumeration.
action specifies which action is going to be executed when this argument is used, and we
are setting it to the SetBaseCurrency custom action that we defined in the actions.py
file. The last option, help, is the text that is displayed when the application's help is
displayed.
The --update argument, as the name says, will update the exchange rates for the default
currency. It is meant to be used after the --setbasecurrency argument.
[ 175 ]
Exchange Rates and the Currency Conversion Tool Chapter 4
Here, we define the argument with the name --update, then we set
the metavar argument. The metavar keyword --update will be referenced when the help
is generated. By default, it's the same as the name of the argument but in uppercase. Since
we don't have any value that we need to pass to this argument, we set metavar to nothing.
The next argument is nargs, which tells the argparser that this argument does not require
a value to be passed. Finally, we have the action that we set to the other custom action that
we created previously, the UpdateForeignExchangeRates action. The last argument
is help, which specifies the help text for the argument.
The idea with this argument is that we want to allow users to override the default currency
that they set using the --setbasecurrency argument when asking for a currency
conversion.
Here, we define the argument with the name --basecurrency. With the string type, we
are going to store the value passed to the argument in an attribute called from_currency;
we also set the choices to currency_option here so we can make sure that only currencies
that exist in the Currency enumeration are allowed. Lastly, we set the help text.
The next argument that we are going to add is called --value. This argument will receive
the value that the users of our application want to convert to another currency.
[ 176 ]
Exchange Rates and the Currency Conversion Tool Chapter 4
Here, we set the name of the argument as --value. Note that the type is different from the
previous arguments that we defined. Now, we will receive a float value, and the argument
parser will store the value passed to the --value argument to the attribute called value.
The last argument is the help text.
Finally, the last argument that we are going to add in the argument that specifies which
currency the value will be converted to is going to be called --to:
argparser.add_argument('--to',
type=str,
dest='dest_currency',
choices=currency_options,
help=('Specify the currency that the value
will '
'be converted to.'))
This argument is very similar to the --basecurrency argument that we defined in the
preceding code. Here, we set the argument's name to --to and it is going to be of type
string. The value passed to this argument will be stored in the attribute called
dest_currency. Here, we also set a choice of arguments to the list of valid currencies that
we extracted from the Currency enumeration; last but not the least, we set the help text.
Basic validation
Note that many of these arguments that we defined are required. However, there are some
arguments that are dependent on each other, for example, the arguments --value and --
to. You cannot try to convert a value without specifying the currency that you want to
convert to and vice versa.
Another problem here is that, since many arguments are required, if we run the application
without passing any argument at all, it will just accept it and crash; the right thing to do
here is that, if the user doesn't use any argument, we should display the Help menu. With
that said, we need to add a function to perform this kind of validation for us, so let's go
ahead and add a function called validate_args. You can add this function right at the
top, after the import statements:
def validate_args(args):
if not fields:
return False
[ 177 ]
Exchange Rates and the Currency Conversion Tool Chapter 4
return True
We use a comprehension to get all the fields that are not set to None. In this comprehension,
we use the built-in function vars, which will return the value of the property __dict__ of
args, which is an instance of the Namespace object. Then, we use the .items() function so
we can iterate through the dictionary items and one by one test if its value is None.
If any argument is passed in the command line, the result of this comprehension will be an
empty list, and in that case, we return False.
Then, we test the arguments that need to be used in pairs: --value (value) and --to
(dest_currency). It will return False if we have a value, but dest_currency is equal to
None and vice versa.
Now, we can complete parse_commandline_args. Let's go to the end of this function and
add the code as follows:
args = argparser.parse_args()
if not validate_args(args):
argparser.print_help()
sys.exit()
return args
Here, we parse the arguments and set them to the variable args, and remember that args
will be of the namespace type. Then, we pass args to the function that we just created, the
validate_args function. If the validate_args returns False, it will print the help and
terminate the program's execution; otherwise, it will return args.
[ 178 ]
Exchange Rates and the Currency Conversion Tool Chapter 4
Next, we are going to develop the application's entry point that will glue together all the
pieces that we have developed so far.
Great! So, let's start adding content to this file. First, add some import statements:
import sys
We import the sys package as usual in case we need to call exit to terminate the execution
of the code, then we import all the classes and utility functions that we developed so far.
We start by importing the parse_commandline_args function for command line parsing,
the get_config so that we can get hold of the default currency set by the user, the
DbClient class so we can access the database and fetch the exchange rates; lastly, we also
import the fetch_exchange_rates_by_currency function, which will be used when
we choose a currency that is not in our database yet. We will fetch this from the fixer.io
API.
[ 179 ]
Exchange Rates and the Currency Conversion Tool Chapter 4
config = get_config()
base_currency = (from_currency
if from_currency
else config['base_currency'])
The main function starts off by parsing the command line arguments. If everything is
entered by the user correctly, we should receive a namespace object containing all the
arguments with its values. In this stage, we only care about three arguments: value,
dest_currency, and from_currency. If you recall from earlier, value is the value that
the user wants to convert to another currency, dest_currency is the currency that the user
wants to convert to, and from_currency is only passed if the user wishes to override the
default currency that is set on the database.
After getting all these values, we call get_config to get the base_currency from the
database, and right after that we check if there is a from_currency where we can use the
value; otherwise, we use the base_currency from the database. This will ensure that if the
user specifies a from_currency value, then that value will override the default currency
stored in the database.
Next, we implement the code that will actually fetch the exchange rates from the database
or from the fixer.io API, like so:
with DbClient('exchange_rates', 'rates') as db:
exchange_rates = db.find_one({'base': base_currency})
if exchange_rates is None:
print(('Fetching exchange rates from fixer.io'
f' [base currency: {base_currency}]'))
try:
response =
fetch_exchange_rates_by_currency(base_currency)
except Exception as e:
sys.exit(f'Error: {e}')
dest_rate = response['rates'][dest_currency]
db.update({'base': base_currency}, response)
[ 180 ]
Exchange Rates and the Currency Conversion Tool Chapter 4
else:
dest_rate = exchange_rates['rates'][dest_currency]
We create a connection with the database using the DbClient class and also specify that we
are going to access the rates collection. inside the context, we first try to find the exchange
rated for the base currency. if it is not in the database, we try to fetch it from fixer.io.
After that, we extract the exchange rate value for the currency that we are converting to and
insert the result in the database so that, the next time that we run the program and want to
use this currency as the base, we don't need to send a request to fixer.io again.
If we find the exchange rate for the base currency, we simply get that value and assign it to
the dest_rate variable.
The last thing we have to do is perform the conversion and use the built-in round function
to limit the number of digits after the decimal point to two digits, and we print the value in
the terminal.
At the end of the file, after the main() function, add the following code:
if __name__ == '__main__':
main()
[ 181 ]
Exchange Rates and the Currency Conversion Tool Chapter 4
Nice! Just as expected. Now, we can use the --setbasecurrency argument to set the base
currency:
[ 182 ]
Exchange Rates and the Currency Conversion Tool Chapter 4
Here, I have set the base currency to SEK (Swedish Kronor) and, every time I need to
perform a currency conversion, I don't need to specify that my base currency is SEK. Let's
convert 100 SEK to USD (United States Dollars):
As you can see, we didn't have the exchange rate in the database yet, so the first thing the
application does is to fetch it from fixer.io and save it into the database.
Since I am a Brazilian developer based in Sweden, I want to convert SEK to BRL (Brazil
Real) so that I know how much Swedish Crowns I will have to take to Brazil next time I go
to visit my parents:
Note that, since this is the second time that we are running the application, we already have
exchange rates with SEK as the base currency, so the application does not fetch the data
from fixer.io again.
[ 183 ]
Exchange Rates and the Currency Conversion Tool Chapter 4
Now, the last thing that we want to try is overriding the base currency. At the moment, it is
set to SEK. We use MXN (Mexico Peso) and convert from MXN to SEK:
Summary
In this chapter, we have covered a lot of interesting topics. In the first section, while setting
up the environment for our application, you learned how to use the super new and popular
tool pipenv, which has become the recommend tool at python.org for creating virtual
environments and also managing project dependencies.
You also learned the basic concepts of object-oriented programming, how to create custom
actions for your command line tools, the basics about context managers which is a really
powerful feature in the Python language, how to create enumerations in Python, and how
to perform HTTP requests using Requests, which is one of the most popular packages in
the Python ecosystem.
Last but not the least, you learned how to use the pymongo package to insert, update, and
In the next chapter, we are going to switch gears and develop a complete, very functional
web application using the excellent and very popular Django web framework!
[ 184 ]
Building a Web Messenger with
5
Microservices
In today's application development world, Microservices have become the standard in
designing and architecting distributed systems. Companies like Netflix have pioneered this
shift and revolutionized the way in which software companies operate, from having small
autonomous teams to designing systems that scale with ease.
In this chapter, I will guide you through the process of creating two microservices that will
work together to make a messaging web application that uses Redis as a datastore.
Messages will automatically expire after a configurable amount of time, so for the purpose
of this chapter, let's call it TempMessenger.
What is Nameko?
Creating your first Nameko microservice
Storing messages
Nameko Dependency Providers
Saving messages
Retrieving all messages
Displaying messages in the web browser
Sending messages via POST requests
Browser polling for messages
Building a Web Messenger with Microservices Chapter 5
TempMessenger Goals
Before starting, let's define some goals for our application:
If at any point during this chapter you would like to refer to all of the code
in this chapter in its entirety, feel free to see it, with tests, at:.
marcuspen.com/github-ppb.
Requirements
In order to partake in this chapter, your local machine will need the following:
An internet connection
Docker - If you haven't installed Docker already, see the official
documentation:
All instructions in this chapter are tailored towards macOS or Debian/Ubuntu systems. I
have, however, taken care to only use cross-platform dependencies.
[ 186 ]
Building a Web Messenger with Microservices Chapter 5
What is Nameko?
Nameko is an open-source framework used for building microservices in Python. Using
Nameko, you can create microservices that communicate with each other using RPC
(Remote Procedure Calls) via AMQP (Advanced Message Queueing Protocol).
RPCs
RPC stands for Remote Procedure Call, and I'll briefly explain this with a short example
based on a cinema booking system. Within this cinema booking system, there are many
microservices, but we will focus on the booking service, which is responsible for managing
bookings, and the email service, which is responsible for sending emails. The booking
service and email service both exist on different machines and both are unaware of where
the other one is. When making a new booking, the booking service needs to send an email
confirmation to the user, so it makes a Remote Procedure Call to the email service, which
could look something like this:
def new_booking(self, user_id, film, time):
...
self.email_service.send_confirmation(user_id, film, time)
...
Notice in the preceding code how the booking service makes the call as if it were executing
code that was local to it? It does not care about the network or the protocol and it doesn't
even give details on which email address it needs to send it to. For the booking service,
email addresses and any other email related concepts are irrelevant! This allows the
booking service to adhere to the Single Responsibility Principle, a term introduced by
Robert C. Martin in his article Principles of Object Orientated Design (.
com/bob-ood), which states that:
The scope of this quote can also be extended to microservices, and is something we should
keep in mind when developing them. This will allow us to keep our microservices self-
contained and cohesive. If the cinema decided to change its email provider, then the only
service that should need to change is the email service, keeping the work required minimal,
which in turn reduces the risk of bugs and possible downtime.
[ 187 ]
Building a Web Messenger with Microservices Chapter 5
However, RPCs do have their downsides when compared to other techniques such as REST,
the main one being that it can be hard to see when a call is remote. One could make
unnecessary remote calls without realizing it, which can be expensive since they go over the
network and use external resources. So when using RPCs, it's important to make them
visibly different.
You can also scale Nameko horizontally by increasing the amount of instances running
your service. This is known as clustering, which is also where the name Nameko originates,
since Nameko mushrooms grow in clusters.
Nameko can also respond to requests from other protocols such as HTTP and websockets.
RabbitMQ
RabbitMQ is used as the message broker for Nameko and allows it to utilize AMQP. Before
we start, you will need to install it on your machine; to do so, we will use Docker, which is
available on all major operating systems.
For those new to Docker, it allows us to run our code in a standalone, self-contained
environment called a container. Within a container is everything that is required for that
code to run independently from anything else. You can also download and run pre-built
containers, which is how we are going to run RabbitMQ. This saves us from installing it on
our local machine and minimizes the amount of issues that can arise from running
RabbitMQ on different platforms such as macOS or Windows.
[ 188 ]
Building a Web Messenger with Microservices Chapter 5
You can check that your new RabbitMQ container is running by executing:
$ docker ps
I also strongly recommend using virtualenv to create an isolated environment to install our
Python requirements. Installing Python requirements without a virtual environment can
cause unexpected side-effects with other Python applications, or worse, your operating
system!
[ 189 ]
Building a Web Messenger with Microservices Chapter 5
Normally, when dealing with Python packages, you would create a requirements.txt
file, populate it with your requirements and then install it. I'd like to show you a different
way that will allow you to easily keep track of Python package versions.
Now create a new folder called requirements and create two new files:
base.in
test.in
The base.in file will contain the requirements needed in order for the core of our service
to run, whereas the test.in file will contain the requirements needed in order to run our
tests. It's important to keep these requirements separate, especially when deploying code in
a microservice architecture. It's okay for our local machines to have test packages installed,
but a deployed version of our code should be as minimal and lightweight as possible.
Provided you are in the directory containing your requirements folder, run the following:
pip-compile requirements/base.in
pip-compile requirements/test.in
This will generate two files, base.txt, and test.txt. Here's a small sample of the
base.txt:
...
nameko==2.8.3
path.py==10.5 # via nameko
pbr==3.1.1 # via mock
pyyaml==3.12 # via nameko
redis==2.10.6
[ 190 ]
Building a Web Messenger with Microservices Chapter 5
Notice how we now have a file that contains all of the latest dependencies and sub-
dependencies of Nameko. It specifies which versions are required and also what caused
each sub-dependency to be installed. For example, six is required by nameko and mock.
This makes it extremely easy to troubleshoot upgrade issues in the future by being able to
easily track version changes between each release of your code.
At the time of writing, Nameko is currently version 2.8.3 and Pytest is 3.4.0. Feel free to use
newer versions of these packages if available, but if you have any issues throughout the
book then revert back to these by appending the version number in your base.in or
test.in file as follows:
nameko==2.8.3
The pip-sync command installs all requirements specified in the files while also removing
any packages that are in your environment that aren't specified. It's a nice way to keep your
virtualenv clean. Alternatively, you can also use:
$ pip install -r requirements/base.txt -r requirements/test.txt
class KonnichiwaService:
name = 'konnichiwa_service'
@rpc
def konnichiwa(self):
return 'Konnichiwa!'
[ 191 ]
Building a Web Messenger with Microservices Chapter 5
We first start by importing rpc from nameko.rpc. This will allow us to decorate our
methods with the rpc decorator and expose them as entrypoints into our service. An
entrypoint is any method in a Nameko service that acts as a gateway into our service.
We've written a method on our service which simply returns the word Konnichiwa!.
Notice how this method is decorated with rpc. The konnichiwa method is now going to be
exposed via RPC.
Before we test this code out we need to create a small config file which will tell Nameko
where to access RabbitMQ and what RPC exchange to use. Create a new file, config.yaml:
AMQP_URI: 'pyamqp://guest:guest@localhost'
rpc_exchange: 'nameko-rpc'
The AMQP_URI configuration here is correct for users who have started the
RabbitMQ container using the instructions given earlier. If you have
adjusted the username, password or location, ensure that your changes are
reflected here.
You should now have a directory structure that resembles the following:
.
├── config.yaml
├── requirements
│ ├── base.in
│ ├── base.txt
│ ├── test.in
│ └── test.txt
├── temp_messenger
└── service.py
Now in your terminal, within the root of your project directory, execute the following:
$ nameko run temp_messenger.service --config config.yaml
[ 192 ]
Building a Web Messenger with Microservices Chapter 5
This should give you access to a Python shell with the ability to make Remote Procedure
Calls. Let's try that out:
>>> n.rpc.konnichiwa_service.konnichiwa()
'Konnichiwa!'
It worked! We have successfully made a call to our Konnichiwa Service and received some
output back. When we executed this code in our Nameko shell, we put a message on the
queue, which was then received by our KonnichiwaService. It then spawned a new
worker to carry out the work of the konnichiwa RPC.
"A microservices framework for Python that lets service developers concentrate on
application logic and encourages testability."
We will now focus on the testability part of Nameko; it provides some very useful tools for
isolating and testing its services.
Create a new folder, tests, and place two new files inside, __init__.py (which can be left
blank) and test_service.py:
from nameko.testing.services import worker_factory
from temp_messenger.service import KonnichiwaService
def test_konnichiwa():
service = worker_factory(KonnichiwaService)
result = service.konnichiwa()
assert result == 'Konnichiwa!'
[ 193 ]
Building a Web Messenger with Microservices Chapter 5
When running outside of the test environment, Nameko spawns a new worker for each
entrypoint that is called. Earlier, when we tested our konnichiwa RPC, the Konnichiwa
Service would have been listening for new messages on the Rabbit queue. Once it received a
new message for the konnichiwa entrypoint, it would spawn a new worker that would
carry out that method and then die.
For our tests, Nameko provides a way to emulate that via a woker_factory. As you can
see, our test uses worker_factory, which we pass our service class, KonnichiwaService.
This will then allow us to call any entrypoint on that service and access the result.
To run the test, from the root of your code directory, simply execute:
pytest
That's it. The test suite should now pass. Have a play around and try to make it break.
name = 'web_server'
konnichiwa_service = RpcProxy('konnichiwa_service')
@http('GET', '/')
def home(self, request):
return self.konnichiwa_service.konnichiwa()
[ 194 ]
Building a Web Messenger with Microservices Chapter 5
Notice how the follows a similar pattern to the KonnichiwaService. It has a name
attribute and a method decorated in order to expose it as an entrypoint. In this case, it is
decorated with the http entrypoint. We specify inside the http decorator that it is a GET
request and the location of that request - in this case, the root of our website.
There is also one more crucial difference: This service holds a reference to the Konnichiwa
Service via an RpcProxy object. RpcProxy allows us to make calls to another Nameko
service via RPC. We instantiate it with the name attribute, which we specified earlier in
KonnichiwaService.
Let's try this out - simply restart the Nameko using the command from earlier (this is
needed to take into account any changes to the code) and go to
in your browser of choice:
It worked! We've now successfully made two microservices—one responsible for showing a
message and one responsible for serving web requests.
[ 195 ]
Building a Web Messenger with Microservices Chapter 5
Nameko gives us the ability to test multiple services working in tandem in a single test.
Look at the following:
def test_root_http(web_session, web_config, container_factory):
web_config['AMQP_URI'] = 'pyamqp://guest:guest@localhost'
result = web_session.get('/')
As you can see in the preceding code, Nameko also gives us access to the following test
fixtures:
Since this is running the actual services, we need to specify the location of the AMQP broker
by injecting it into the web_config. Using container_factory, we create two containers:
web_server and konnichiwa. We then start both containers.
It's then a simple case of using web_session to make a GET request to the root of our site
and checking that the result is what we expect.
As we go through the rest of the chapter, I encourage you to write your own tests for the
code, as it will not only prevents bugs but also help to solidify your knowledge on this
topic. It's also a good way to experiment with your own ideas and modifications to the code
as they can tell you quickly if you have broken anything.
[ 196 ]
Building a Web Messenger with Microservices Chapter 5
Storing messages
The messages we want our application to display need to be temporary. We could use a
relational database for this, such as PostgreSQL, but that would mean having to design and
maintain a database for something as simple as text.
An introduction to Redis
Redis is an in-memory data store. The entire dataset can be stored in memory making reads
and writes much faster than relational databases, which is useful for data that is not going
to need persistence. In addition, we can store data without making a schema, which is fine
if we are not going to need complex queries. In our case, we simply need a data store that
will allow us to store messages, get messages, and expire messages. Redis fits our use case
perfectly!
You can check that your new Redis container is running by executing:
$ docker ps
[ 197 ]
Building a Web Messenger with Microservices Chapter 5
Using Redis
Let's briefly look at the types of Redis commands that could be useful to us for
TempMessenger:
SET: Sets a given key to hold a given string. It also allows us to set an expiration
in seconds or milliseconds.
GET: Gets the value of the data stored with the given key.
TTL: Gets the time-to-live for a given key in seconds.
PTTL: Gets the time-to-live for a given key in milliseconds.
KEYS: Returns a list of all keys in the data store.
To try them out, we can use redis-cli which is a program that ships with our Redis
container. To access it, first log in to the container by executing the following in your
terminal:
docker exec -it redis /bin/bash
There are some examples given as follows on how to use redis-cli; if you're not familiar
with Redis then I encourage you to experiment with the commands yourself.
[ 198 ]
Building a Web Messenger with Microservices Chapter 5
Set some more data, hi there, at key msg2 and retrieve it:
127.0.0.1:6379> SET msg2 "hi there"
OK
127.0.0.1:6379> GET msg2
"hi there"
[ 199 ]
Building a Web Messenger with Microservices Chapter 5
By structuring our microservices like this, we have the ability to easily swap out or re-use
dependency providers in other services.
class RedisClient:
We start off our code by implementing the __init__ method, which creates our Redis
client and assigns it to self.redis. StrictRedis that can take a number of optional
arguments, however, we have only specified the following:
url: Rather than specifying the host, port and database number separately, we
can use StrictRedis' from_url, which will allow us to specify all three with a
single string, like so—redis://localhost:6379/0. This is a lot more
convenient when it comes to storing it in our config.yaml later.
decode_responses: This will automatically convert the data we get from Redis
into a Unicode string. By default, data is retrieved in bytes.
[ 200 ]
Building a Web Messenger with Microservices Chapter 5
if message is None:
raise RedisError(
'Message not found: {}'.format(message_id)
)
return message
Outside of our new class, let's also implement a new error class:
class RedisError(Exception):
pass
Here we have a method, get_message, that takes a message_id that will be used as our
Redis key. We use the get method on our Redis client to retrieve the message with our
given key. When retrieving values from Redis, if the key does not exist, it will simply return
None. Since this method expects there to be a message, we should handle raising an error
ourselves. In this case, we've made a simple exception, RedisError.
def setup(self):
redis_url = self.container.config['REDIS_URL']
self.client = RedisClient(redis_url)
def stop(self):
del self.client
[ 201 ]
Building a Web Messenger with Microservices Chapter 5
In the preceding code, you can see that our new MessageStore class inherits from the
DependencyProvider class. The methods we have specified in our new MessageStore class
will be called at certain moments of our microservice lifecycle:
setup: This will be called before our Nameko services starts. Here we get the
Redis URL from config.yaml and create a new RedisClient using the code
we made earlier.
stop: When our Nameko services begin to shut down, this will be called.
get_dependency: All dependency providers need to implement this method.
When an entrypoint fires, Nameko creates a worker and injects the result of
get_dependency for each dependency specified in the service into the worker.
In our case, this means that our workers will all have access to an instance of
RedisClient.
name = 'message_service'
message_store = MessageStore()
@rpc
def get_message(self, message_id):
return self.message_store.get_message(message_id)
This is similar to our earlier services; however, this time we are specifying a new class
attribute, message_store. Our RPC entrypoint, get_message, can now make use of this
and call get_message in our RedisClient and simply return the result.
[ 202 ]
Building a Web Messenger with Microservices Chapter 5
We could have done all of this by creating a new Redis client within our RPC entrypoint
and implementing a Redis GET. However, by creating a dependency provider, we promote
reusability and hide away the unwanted behavior of Redis returning None when a key does
not exist. This is just a small example of why Dependency Providers are extremely good at
decoupling our services from external dependencies.
We can now use nameko shell to make remote calls to our new MessageService:
>>> n.rpc.message_service.get_message('msg1')
'this is a test'
As expected, we were able to retrieve a message that we set earlier using redis-cli via
our MessageService entrypoint.
[ 203 ]
Building a Web Messenger with Microservices Chapter 5
This isn't the prettiest of errors and there are certain things we can do to reduce the
traceback with this, but the final line states the exception we defined earlier and clearly
shows us why that request failed.
Saving messages
Earlier, I introduced the Redis SET method. This will allow us to save a message to Redis,
but first, we need to create a new method in our dependency provider that will handle this.
We'll solve this by having the dependency create a random string to be used as the message
ID.
uuid4 generates us a unique random string that we can use for our message.
return message_id
First off, we generate a new message ID using uuid4().hex. The hex attribute gives us the
UUID as a 32-character hexadecimal string. We then use it as a key to save the message and
return it.
[ 204 ]
Building a Web Messenger with Microservices Chapter 5
@rpc
def save_message(self, message):
message_id = self.message_store.save_message(message)
return message_id
Nothing fancy here, but notice how easy it is becoming to add new functionality to our
service. We are separating logic that belongs in the dependency from our entrypoints, and
at the same time making our code reusable. If another RPC method we create in the future
needs to save a message to Redis, we can easily do so without having to recreate the same
code again.
Let's test this out by only using the nameko shell - remember to restart your Nameko
service for changes to take effect!
>>> n.rpc.message_service.save_message('Nameko is awesome!')
'd18e3d8226cd458db2731af8b3b000d9'
The ID returned here is random and will differ from the one you get from
your session.
>>>n.rpc.message_service.get_message
('d18e3d8226cd458db2731af8b3b000d9')
'Nameko is awesome!'
As you can see, we have successfully saved a message and used the UUID that is returned
to retrieve our message.
This is all well and good, but for the purposes of our app we don't expect the user to have to
supply a message UUID in order to read messages. Let's make this a bit more practical and
look at how we can get all of the messages in our Redis store.
[ 205 ]
Building a Web Messenger with Microservices Chapter 5
We start off by using self.redis.keys() to gather all keys that are stored in Redis,
which, in our case, are the message IDs. We then have a list comprehension that will iterate
through all of the message IDs and create a dictionary for each one, containing the message
ID itself and the message that is stored in Redis, using self.redis.get(message_id).
Personally, I prefer to use a list comprehension here to build the list of messages, but if you
are struggling to understand this method, I recommend writing it as a standard for loop.
For the sake of this example, see the following code for the same method built as a for loop:
def get_all_messages(self):
message_ids = self.redis.keys()
messages = []
[ 206 ]
Building a Web Messenger with Microservices Chapter 5
)
return messages
Both of these methods do exactly the same thing. Which do you prefer? I'll leave that choice
to you...
Whenever I write a list or dictionary comprehension, I always start by having a test that
checks the output of my function or method. I then write my code with a comprehension
and test it to ensure the output is correct. I'll then change my code to a for loop and ensure
the test still passes. After that, I look at both versions of my code and decide which one
looks the most readable and clean. Unless the code needs to be super efficient, I always opt
for code that reads well, even if that means a few more lines. This approach pays off in the
long run when it comes to reading back and maintaining that code later!
We now have a way to obtain all messages in Redis. In the preceding code, I could have
simply returned a list of messages with no dictionaries involved, just the string value of the
message. But what if we wanted to add more data to each message later? For example,
some metadata to say when the message was created or how long the message has until it
expires... we'll get to that part later! Using a dictionary here for each message will allow us
to easily evolve our data structures later on.
We can now look at adding a new RPC to our MessageService that will allow us to get all
of the messages.
I'm sure that by now, I probably do not need to explain what is going on here! We are
simply calling the method we made earlier in our Redis dependency and returning the
result.
[ 207 ]
Building a Web Messenger with Microservices Chapter 5
There we have it! We can now retrieve all of the messages in our data store. (For the sake of
space and readability, I've truncated the message IDs.)
There is one issue with the messages that are returned here - can you spot what it is? The
order in which we put the messages into Redis is not the same order that we have received
when we get them out again. We'll come back to this later, but for now, let's move on to
displaying these messages in our web browser.
Before we start, you should amend your base.in file to include jinja2, re-compile your
requirements and install them. Alternatively, simply run pip install jinja2.
[ 208 ]
Building a Web Messenger with Microservices Chapter 5
With these three steps, it's important to identify which parts are never subject (or at least
extremely unlikely) to change while our application is running... and which are. Keep this
in mind as I explain through the following code.
In your dependencies directory, add a new file, jinja2.py and start with the following
code:
from jinja2 import Environment, PackageLoader, select_autoescape
class TemplateRenderer:
In our __init__ method, we require a package name and a template directory. With these,
we can then create the template environment. The environment requires a loader, which is
simply a way of being able to load our template files from a given package and directory.
We've also specified that we want to enable auto-escaping on our HTML files for security.
We've then made a render_home method that will allow us to render our home.html
template once we've made it. Notice how we render our template with messages... you'll
see why later!
Can you see why I've structured the code this way? Since the __init__ method is always
executed, I've put the creation of our template environment there, since this is unlikely to
ever change while our application is running.
[ 209 ]
Building a Web Messenger with Microservices Chapter 5
However, which template we want to render and the variables we give to that template are
always going to change, depending on what page the user is trying to access and what data
is available at that given moment in time. With the preceding structure, it becomes trivial to
add a new method for each webpage of our application.
<body>
{% if messages %}
{% for message in messages %}
<p>{{ message['message'] }}</p>
{% endfor %}
{% else %}
<p>No messages!</p>
{% endif %}
</body>
This HTML is nothing fancy, and neither is the templating logic! If you are unfamiliar to
Jinja2 or Django templating then you're probably thinking that this HTML looks weird with
the curly braces everywhere. Jinja2 uses these to allow us to input Python-like syntax into
our template.
In the preceding example, we start off with an if statement to see if we have any messages
(the format and structure of messages will be the same as the messages that are returned
by the get_all_messages RPC we made earlier). If we do, then we have some more logic,
including a for loop that will iterate and display the value of 'message' for each dictionary
in our messages list.
If there are no messages, then we will just show the No messages! text.
[ 210 ]
Building a Web Messenger with Microservices Chapter 5
def setup(self):
self.template_renderer = TemplateRenderer(
'temp_messenger', 'templates'
)
This is extremely similar to our previous Redis dependency. We specify a setup method
that creates an instance of our TemplateRenderer and a get_dependency method that
will inject it into the worker.
name = 'web_server'
message_service = RpcProxy('message_service')
templates = Jinja2()
@http('GET', '/')
def home(self, request):
messages = self.message_service.get_all_messages()
rendered_template = self.templates.render_home(messages)
[ 211 ]
Building a Web Messenger with Microservices Chapter 5
return rendered_template
Notice how we have assigned a new attribute, templates, like we did earlier in our
MessageService with message_store. Our HTTP entrypoint now talks to our
MessageService, retrieves all of the messages in Redis, and uses them to create a rendered
template using our new Jinja2 dependency. We then return the result.
[ 212 ]
Building a Web Messenger with Microservices Chapter 5
It's worked... sort of! The messages we stored in Redis earlier are present, which means the
logic in our template is functioning properly, but we also have all of the HTML tags and
indentation from our home.html.
The reason for this is because we haven't yet specified any headers for our HTTP response
to indicate that it is HTML. To do this, let's create a small helper function outside of our
WebServer class, which will convert our rendered template into a response with proper
headers and a status code.
This function creates a headers dictionary, which contains the correct content type, HTML.
We then create and return a Response object with an HTTP status code of 200, our headers,
and the content, which in our case will be the rendered template.
We can now amend our HTTP entrypoint to use our new helper function:
@http('GET', '/')
def home(self, request):
messages = self.message_service.get_all_messages()
rendered_template = self.templates.render_home(messages)
html_response = create_html_response(rendered_template)
return html_response
[ 213 ]
Building a Web Messenger with Microservices Chapter 5
Our home HTTP entrypoint now makes use of the create_html_reponse, giving it the
rendered template, and then returns the response that is made. Let's try this out again in
our browser:
As you can now see, our messages now display as we expect them with no HTML tags to be
found! Have a try at deleting all data in Redis with the flushall command using the
redis-cli and reload the webpage. What happens?
[ 214 ]
Building a Web Messenger with Microservices Chapter 5
try:
data = json.loads(data_as_text)
except json.JSONDecodeError:
return 400, 'JSON payload expected'
try:
message = data['message']
except KeyError:
return 400, 'No message given'
self.message_service.save_message(message)
With our new POST entrypoint, we start off by extracting the data from the request. We
specify the parameter as_text=True, because we would otherwise get the data back as
bytes.
Once we have that data, we can then attempt to load it from JSON into a Python dictionary.
If the data is not valid JSON then this can cause a JSONDecodeError in our service, so it's
best to handle that nicely and return a bad request status code of 400. Without this
exception handling, our service would return an internal server error, which has a status
code of 500.
Now that the data is in a dictionary format, we can obtain the message inside it. Again, we
have some defensive code which will handle any occurrences of an absent 'message' key
and return another 400.
We then proceed to save the message using the save_message RPC we made earlier in our
MessageService.
[ 215 ]
Building a Web Messenger with Microservices Chapter 5
With this, TempMessenger now has the ability to save new messages via an HTTP POST
request! If you wanted to, you can test this out using curl or another API client, like so:
$ curl -d '{"message": "foo"}' -H "Content-Type: application/json" -X POST
We will now update our home.html template to include the ability to use this new POST
request.
The code you are about to read is something that I learned just by reading the jQuery
documentation, so it's extremely simple. If you are comfortable with front-end code then
I'm sure there are probably a million different and probably better ways to do this in
JavaScript, so please amend as you see fit.
You will first need to add the following after the <!DOCTYPE html>:
<head>
<script src=""></script>
</head>
This will download and run the latest version of jQuery in the browser.
In our home.html, before the closing </body> tag, add the following:
<form action="/messages" id="postMessage">
<input type="text" name="message" placeholder="Post message">
<input type="submit" value="Post">
</form>
We start off here with some simple HTML to add a basic form. This only has a text input
and a submit button. On its own, it will render a text box and a submit button, but it will
not do anything.
[ 216 ]
Building a Web Messenger with Microservices Chapter 5
$( "#postMessage" ).submit(function(event) { # ①
event.preventDefault(); # ②
$.ajax({ # ④
type: 'POST',
url: url,
data: JSON.stringify({message: message}), # ⑤
contentType: "application/json", # ⑥
dataType: 'json', # ⑦
success: function() {location.reload();} # ⑧
});
});
</script>
This will now add some functionality to our submit button. Let's briefly cover what is
happening here:
1. This will create an event listener for our page that listens for the postMessage
event.
2. We also prevent the default behavior of our submit button using
event.preventDefault();. In this case, it would submit our form and attempt
to perform a GET on /messages?message=I%27m+a+new+message.
3. Once that is triggered, we then find the message and URL in our form.
4. With these, we then construct our AJAX request, which is a POST request.
5. We use JSON.stringify to convert our payload into valid JSON data.
6. Remember earlier, when we had to construct a response and supply header
information to say that our content type was text/html? Well, we are doing the
same thing here in our AJAX request, but this time, our content type is
application/json.
7. We set the datatype to json. This tells the browser the type of data we are
expecting back from the server.
8. We also register a callback that reloads the webpage if the request is successful.
This will allow us to see our new message on the page (and any other new ones)
since it will get all of the messages again. This forced page reload is not the most
elegant way of handling this, but it will do for now.
[ 217 ]
Building a Web Messenger with Microservices Chapter 5
Provided you haven't cleared the data from Redis (this can be done by manually deleting
them or by simply restarting your machine), you should still see the old messages from
earlier.
[ 218 ]
Building a Web Messenger with Microservices Chapter 5
Once you've typed your message, click the Post button to submit your new message:
Looks like it worked! Our application now has the ability to send new messages. We will
now move onto the last requirement for our application, which is to expire messages after a
given period of time.
Let's look back at our save_message method in our Redis dependency. Redis' SET has
some optional parameters; the two we are most interested in here are ex and px. Both allow
us to set the expiry of the data we are about to save, with one difference: ex is in seconds
and px is in milliseconds:
def save_message(self, message):
message_id = uuid4().hex
self.redis.set(message_id, message, ex=10)
return message_id
[ 219 ]
Building a Web Messenger with Microservices Chapter 5
In the preceding code, you can see that the only amendment to the code I've made is to add
ex=10 to the redis.set method; this will cause all of our messages to expire in 10 seconds.
Restart your Nameko services now and try this out. When you send a new message, wait 10
seconds and refresh the page, and it should be gone.
Please note that if there were any messages in Redis before you made this
change, they will still be present, since they were saved without an expiry.
To remove them, delete all data in Redis with the flushall command
using the redis-cli.
Feel free to play around with the expiry time, setting it to whatever you wish with either
the ex or px parameters. One way you could make this better is to move the expiry time
constant to the configuration file, which is then loaded whenever you start Nameko, but for
now, this will suffice.
Sorting messages
One thing you will quickly notice with the current state of our app is that the messages are
not in any order at all. When you send a new message it could be inserted anywhere in the
thread of messages, making our app pretty inconvenient, to say the least!
To remedy this, we will sort the messages by the amount of time left before they expire.
First, we will have to amend our get_all_messages method in our Redis dependency to
also get the time-to-live for each message:
def get_all_messages(self):
return [
{
'id': message_id,
'message': self.redis.get(message_id),
'expires_in': self.redis.pttl(message_id),
}
for message_id in self.redis.keys()
]
[ 220 ]
Building a Web Messenger with Microservices Chapter 5
As you can see in the preceding code, we have added a new expires_in value to each
message. This uses the Redis PTTL command, which returns the time to live in milliseconds
for a given key. Alternatively, we could also use the Redis TTL command, which returns the
time to live in seconds, but we want this to be as precise as possible to make our sorting
more accurate.
Now, when our MessageService calls get_all_messages, it will also know how long
each message has to live. With this, we can create a new helper function to sort the
messages.
This uses Python's built-in sorted function, which has the ability to return a sorted list
from a given iterable; in our case the iterable is messages. We use key to specify what we
want messages to be sorted by. Since we want the messages to be sorted by expires_in,
we use an itemgetter to extract it to be used as the comparison. We've given the
sort_messages_by_expiry function an optional parameter, reverse, which, if set to
True, will make sorted return the sorted list in a reverse order.
With this new helper function, we can now amend our get_all_messages RPC in our
MessageService:
@rpc
def get_all_messages(self):
messages = self.message_store.get_all_messages()
sorted_messages = sort_messages_by_expiry(messages)
return sorted_messages
Our app will now return our messages, sorted with the newest messages at the bottom. If
you'd like to have the newest messages at the top, then simply change sorted_messages
to be:
sorted_messages = sort_messages_by_expiry(messages, reverse=True)
[ 221 ]
Building a Web Messenger with Microservices Chapter 5
Our app now fits all the acceptance criteria we specified earlier. We have the ability to send
messages and get existing messages, and they all expire after a configurable amount of time.
One thing that is less than ideal is that we rely on a browser refresh to fetch the latest state
of the messages. We can fix this in a number of ways, but I will demonstrate one of the
simplest ways to solve this; via polling.
By using polling, the browser can constantly make a request to the server to get the latest
messages without forcing a page refresh. We will have to introduce some more JavaScript to
achieve this, but so would any other method.
This is similar to our create_html_response from earlier, but here it sets the Content-
Type to 'application/json' and converts our data into a valid JSON object.
This will call our get_all_messages RPC and return the result as a JSON response to the
browser. Notice how we are using the same URL, /messages, as we do in our endpoint,
here to send a new message. This is a good example of being RESTful. We use a POST
request to /messages to create a new message and we use a GET request to /messages to
get all messages.
[ 222 ]
Building a Web Messenger with Microservices Chapter 5
Start by replacing the Jinja2 if block in our home.html, which iterates through our list of
messages, with the following line:
<div id="messageContainer"></div>
This will be used later to hold our new list of messages generated by our jQuery function.
Inside the <script> tags in our home.html, write the following code:
function messagePoll() {
$.ajax({
type: "GET", # ①
url: "/messages",
dataType: "json",
success: function(data) { # ②
updateMessages(data);
},
timeout: 500, # ③
complete: setTimeout(messagePoll, 1000), # ④
})
}
This is another AJAX request, similar to the one we made earlier to send a new message,
with a few differences:
1. Here, we are performing a GET request to the new endpoint we made in our
WebServer instead of a POST request.
2. If successful, we use the success callback to call the updateMessages function
that we will create later.
3. Set timeout to 500 milliseconds - this is the amount of time in which we should
expect a response from our server before giving up.
4. Use complete, which allows us to define what happens once the success or
error callback has completed - in this case, we set it to call poll again after 1000
milliseconds using the setTimeout function.
[ 223 ]
Building a Web Messenger with Microservices Chapter 5
if (messages.length === 0) { # ④
$messageContainer.html(emptyMessages); #
} else {
$.each(messages, function(index, value) {
var message = $(value.message).text() || value.message;
messageList.push('<p>' + message + '</p>'); #
});
$messageContainer.html(messageList); # ⑤
}
}
By using this function, we can replace all of the code in our HTML template that generates
the list of messages in the Jinja2 template. Let's go through this step-by-step:
1. First, we get the messageContainer within the HTML so that we can update it.
2. We generate an empty messageList array.
3. We generate the emptyMessages text.
4. We check if the amount of messages is equal to 0:
a. If so, we use .html() to replace messageContainer HTML with "No
messages!".
b. Otherwise, for each message in messages, we first strip any HTML
tags that could be present using jQuery's built-in .text() function.
Then we wrap the message in <p> tags and append them to the
messageList using .push().
5. Finally, we use .html() to replace the messageContainer HTML with the
messagesList.
In point 4b, it's important to escape any HTML tags that could be present
in the message, as a malicious user could send a nasty script as a message,
which would be executed by everyone using the app!
[ 224 ]
Building a Web Messenger with Microservices Chapter 5
This is by no means the best way to solve the issue of having to force refresh the browser to
update the messages, but it is one of the simplest ways for me to demonstrate in this book.
There are probably more elegant ways to achieve the polling, and if you really wanted to do
this properly then WebSockets is by far your best option here.
Summary
This now brings us to a close with the guide to writing the TempMessenger application. If
you have never used Nameko before or written a microservice, I hope I have given you a
good base to build on when it comes to keeping services small and to the point.
We started by creating a service with a single RPC method and then used that within
another service via HTTP. We then looked at ways in which we can test Nameko services
with fixtures that allow us to spawn workers and even the services themselves.
We introduced dependency providers and created a Redis client with the ability to get a
single message. With that, we expanded the Redis dependency with methods that allowed
us to save new messages, expire messages, and return them all in a list.
We looked at how we can return HTML to the browser using Jinja2, and at creating a
dependency provider. We even looked at some JavaScript and JQuery to enable us to make
requests from the browser.
One of the main themes you will have probably noticed is the need to keep dependency
logic away from your service code. By doing this we keep our services agnostic to the
workings that are specific to only that dependency. What if we decided to switch Redis for a
MySQL database? In our code, it would just be a case of creating a new dependency
provider for MySQL and new client methods that mapped to the ones our
MessageService expects. We'd then make the minimal change of swapping Redis for
MySQL in our MessageService. If we did not write our code in this way then we would
have to invest more time and effort to make changes to our service. We'd also introduce
more scope for bugs to arise.
If you are familiar with other Python frameworks, you should now see how Nameko allows
us to easily create scalable microservices while still giving us a more batteries not
included approach when compared to something like Django. When it comes to writing
small services that serve a single purpose that are focused on backend tasks, Nameko can be
a perfect choice.
In the next chapter, we will look at extending TempMessenger with a User Authentication
microservice using a PostgreSQL database.
[ 225 ]
Extending TempMessenger
6
with a User Authentication
Microservice
In the last chapter, we created a web-based messenger, TempMessenger, which consists of
two microservices—one that is responsible for storing and retrieving messages and another
that is responsible for serving web requests.
In this chapter, we will look to extend our existing TempMessenger platform with a User
Authentication microservice. This will consist of a Nameko service with a PostgreSQL
database dependency that has the ability to create new users and authenticate existing
users.
We will also replace our Nameko Web Server microservice with a more suitable Flask app
that will allow us to keep track of web sessions for our users.
It is necessary to have read the last chapter in order to follow this chapter.
TempMessenger goals
Let's add some new goals for our new and improved TempMessenger:
If at any point you would like to refer to all of the code in this chapter in
its entirety, feel free to view it with tests at:.
Requirements
In order to function in this chapter, your local machine will need the following:
An internet connection
Docker: If you haven't installed Docker already, please see the official
documentation:
A virtualenv running Python 3.6 or later; you can reuse your virtualenv from the
last chapter.
pgAdmin: see the official documentation for installation instructions:
A RabbitMQ container running on the default ports: this should be present from
the last chapter, Chapter 5, Building a Web Messenger with Microservices.
A Redis container running on the default ports: this should be present from the
last chapter, Chapter 5, Building a Web Messenger with Microservices.
All instructions in this chapter are tailored towards macOS or Debian/Ubuntu systems;
however, I have made an effort to only use multi-platform dependencies.
[ 227 ]
Extending TempMessenger with a User Authentication Microservice Chapter 6
However, user accounts are a totally different kettle of fish altogether. They must be stored
for as long as the user wishes and they must be stored securely. We also need a proper
schema for these accounts to keep the data consistent. We also need to be able to query and
update the data with ease.
For these reasons, Redis probably isn't the best solution. One of the many benefits of
building microservices is that we aren't tied to a specific technology; just because our
Message Service uses Redis for storage doesn't mean that our User Service has to follow
suit...
[ 228 ]
Extending TempMessenger with a User Authentication Microservice Chapter 6
You can check if the container is up and running by executing the following and ensuring
that your postgres container is present:
$ docker ps
We will first need to install two new Python packages: SQLAlchemy and Psycopg.
SQLAlchemy is a toolkit and object-relational mapper that will serve as our gateway into
the world of SQL. Psycopg is a PostgreSQL database adapter for Python.
Start by adding sqlalchemy (version 1.2.1 at the time of writing) and psycopg2 (version 2.7.4
at the time of writing) to your base.in file. From the root of your project folder, within your
virtualenv, run:
$ pip-compile requirements/base.in
$ pip-sync requirements/base.txt requirements/test.txt
This will add sqlalchemy and psycopg2 to our requirements and will ensure that our
virtualenv packages match them exactly. Alternatively, you can pip install them if you
are choosing not to use pip-tools.
In our dependencies folder, create a new file, users.py. Usually, you would have a
different file for your database models, but for the purpose of simplicity we will embed it
within our dependency. To start, let's define our imports and the base class to be used by
our model:
from sqlalchemy import Column, Integer, Unicode
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
We start by importing Column, which will be used to declare our database columns, and
some basic field types: Integer and Unicode. As for declarative_base, we use that to
create our Base class, from which our User model will inherit. This will create the mapping
between our model and a database table.
[ 229 ]
Extending TempMessenger with a User Authentication Microservice Chapter 6
id = Column(Integer, primary_key=True)
first_name = Column(Unicode(length=128))
last_name = Column(Unicode(length=128))
password = Column(Unicode(length=512))
As you can see, our User class inherits from the Base class we defined earlier.
__tablename__ sets the name of the table. Let's briefly go over some of the database
columns we have defined:
id: A unique identifier and primary key for each user in our database. It's
common practice for database models to have their IDs as integers for simplicity.
first_name and last_name: a maximum length of 128 characters should be
enough for any name. We've also used Unicode as our type to cater for names
that include symbols such as Chinese.
email: Again, a large field length and Unicode to cater for symbols. We've also
made this field unique, which will prevent multiple users with the same email
address from being created.
password: We won't be storing passwords in plain text here; we'll come back to
this later!
[ 230 ]
Extending TempMessenger with a User Authentication Microservice Chapter 6
We will now create a wrapper class that will be used to encapsulate all of the logic around
managing users. In users.py, add the following code:
class UserWrapper:
This will be the basis of our wrapper and will require a database session object in the form
of session. Later, we will add more methods to this class, such as create and
authenticate. In order to create our user dependency, first let's add the following to our
imports:
from nameko_sqlalchemy import DatabaseSession
Now let's create a new class, User Store, which will serve as our dependency:
class UserStore(DatabaseSession):
def __init__(self):
super().__init__(Base)
To explain this code, first, let's talk about DatabaseSession. This pre-made dependency
provider for Nameko, given to us by nameko-sqlalchemy, already includes methods such
as setup and get_dependency, as covered in the previous chapter. Therefore, our
UserStore class is simply inheriting from it to use this existing functionality.
The DatabaseSession class' __init__ method takes the declarative base for our models
as its only argument. In our UserStore class, we override this with our own __init__
method, which amends it to use our Base and carry out the same functionality as it would
have originally done by using Python's in-built super function.
[ 231 ]
Extending TempMessenger with a User Authentication Microservice Chapter 6
Creating users
Now that we have our Nameko dependency in place, we can start to add functionality to
our UserWrapper. We will start by creating users. Add the following to the UserWrapper
class:
def create(self, **kwargs):
user = User(**kwargs)
self.session.add(user)
self.session.commit()
This create method will create a new User object, add it to our database session, commit
that change to the database, and return the user. Nothing fancy here! But let's talk about the
process of self.session.add and self.session.commit. When we first add the user to
the session, this adds the user to our local database session in memory, rather than adding
them to our actual database. The new user has been staged but no changes have actually
taken place in our database. This is rather useful. Say we wanted to do multiple updates to
the database, making a number of calls to the database can be expensive, so we first make
all the changes we want in memory, then commit them all with a single database
transaction.
Another thing you'll notice in the preceding code is that we use **kwargs instead of
defining the actual arguments to create a new User. If we were to change the user model,
this minimizes the changes needed since the keyword arguments directly map to the fields.
[ 232 ]
Extending TempMessenger with a User Authentication Microservice Chapter 6
class UserService:
name = 'user_service'
user_store = UserStore()
@rpc
def create_user(self, first_name, last_name, email, password):
self.user_store.create(
first_name=first_name,
last_name=last_name,
password=password,
)
If you read the last chapter, then there is nothing new here. We've created a new
UserService, given it the UserStore dependency and made an RPC, which is simply a
pass-through to the create method on the dependency. However, here we have opted to
define the arguments to create a user rather than use **kwargs like we did in the
dependency method. This is because we want the RPC to define the contract it has with
other services that will interface with it. If another service makes an invalid call, then we
want the RPC to reject it as soon as possible without wasting time making a call to the
dependency or, worse, making a database query.
We are close to the point where we can test this out, but first we need to update our
config.yaml with our database settings. Provided you used the command supplied earlier
to create a Docker Postgres container, append the following:
DB_URIS:
user_service:Base:
"postgresql+psycopg2://postgres:secret@localhost/
users?client_encoding=utf8"
[ 233 ]
Extending TempMessenger with a User Authentication Microservice Chapter 6
We will also have to create the tables in our Postgres database. Usually, you would do this
with a database migration tool, such as Alembic. However, for the purposes of this book,
we will use a small one-off Python script to do this for us. In the root of your project
directory, create a new file, setup_db.py, with the following code:
from sqlalchemy import create_engine
from temp_messenger.dependencies.users import User
engine = create_engine(
'postgresql+psycopg2://postgres:secret@localhost/'
'users?client_encoding=utf8'
)
User.metadata.create_all(engine)
This code takes our user model in our dependency module and creates the required table in
our database for us. create_engine is the starting point as it establishes a connection with
the database. We then use our user model metadata (which in our case consists of the table
name and columns) and call create_all, which issues the CREATE SQL statements to the
database using the engine.
If you are going to want to make changes to the User model while retaining your existing
user data, then learning how to use a database migration tool, such as Alembic, is a must
and I strongly recommend it.
Now let's take a look at our new table using a Database Admin tool. There are many
Database Admin tools out there, my personal favorite being Postico for Mac, but for the
purposes of this book, we will use pgAdmin, which works on all platforms.
[ 234 ]
Extending TempMessenger with a User Authentication Microservice Chapter 6
Simply give it a name of your choice in the General tab, then in the Connection tab, you
can fill out the details of our database with the configuration we set when we created our
Postgres Docker screenshot earlier. However, if you did not make any changes to this, you
can simply copy the details in the preceding image. Remember that the password was set to
secret. Once you've filled this out, hit Save and it should connect to our database.
Once connected, we can start to look at the details of our database. To see our table, you'll
need to expand out and action the menus like so:
[ 235 ]
Extending TempMessenger with a User Authentication Microservice Chapter 6
[ 236 ]
Extending TempMessenger with a User Authentication Microservice Chapter 6
You should now be able to see our table, which represents our user model:
We can now try out creating a user with the Nameko shell. Start our new User Service in the
terminal by executing the following, within a virtualenv, in the root of our project folder:
$ nameko run temp_messenger.user_service --config config.yaml
Once in your Nameko shell, execute the following to create a new user:
>>> n.rpc.user_service.create_user('John', 'Doe', 'john@example.com',
'super-secret')
[ 237 ]
Extending TempMessenger with a User Authentication Microservice Chapter 6
Now let's check pgAdmin to see if the user was successfully created. To refresh the data,
simply follow the earlier steps to show the user table or click the Refresh button:
It worked! We now have a functioning User Service that can create new users. However,
there is one major issue here... We have just committed one of the worst offenses a software
developer can commit—storing passwords in plain text!
[ 238 ]
Extending TempMessenger with a User Authentication Microservice Chapter 6
Either way, this negligence has led to the leak of millions of users' email and password
combinations. This would not be such an issue if we used different passwords for every
online account we made... but unfortunately, we are lazy and password reuse is quite
common practice. Therefore, the responsibility for mitigating some of the damage done by
hackers infiltrating our servers falls to us, the developers.
In October 2016, the popular video sharing platform Dailymotion suffered a data breach in
which 85 million accounts were stolen. Of those 85 million accounts, 18 million had
passwords attached to them, but luckily they were hashed using Bcrypt. This meant that it
would take hackers decades, maybe even centuries, of brute-force computing to crack them
with today's hardware (source:).
So despite hackers successfully breaching Dailymotion's servers, some of the damage was
mitigated by using a hashing algorithm, such as Bcrypt, to store the passwords. With this in
mind, we will now look at how to implement bcrypt hashing for our user passwords,
rather than storing them insecurely in plain text.
Using Bcrypt
Start by adding bcrypt to your base.in file and installing it (version 3.1.4 at the time of
writing) using the same process as earlier.
In order for bcrypt to create a hash of a password, it requires two things—your password
and a salt. A salt is simply a string of random characters. Let's look at how you can
create a salt in Python:
>>> from bcrypt import gensalt
>>> gensalt()
b'$2b$12$fiDoHXkWx6WMOuIfOG4Gku'
[ 239 ]
Extending TempMessenger with a User Authentication Microservice Chapter 6
This is the simplest way to create a salt compatible with Bcrypt. The $ symbols represent
different parts of the salt, and I'd like to point out the second section: $12. This part
represents how many rounds of work are required to hash the password, which by default,
is 12. We can configure this like so:
>>> gensalt(rounds=14)
b'$2b$14$kOUKDC.05iq1ANZPgBXxYO'
Notice how in this salt, it has changed to $14. By increasing this, we are also increasing
the amount of time it would take to create a hash of the password. This will also increase
the amount of time it takes to check the password attempt against the hash later on. This is
useful since we are trying to prevent hackers from brute-forcing password attempts if they
do manage to get hold of our database. However, the default number of rounds, 12, is
plenty enough already! Let's now create a hash of a password:
>>> from bcrypt import hashpw, gensalt
>>> my_password = b'super-secret'
>>> salt = gensalt()
>>> salt
b'$2b$12$YCnmXxOcs/GJVTHinSoVs.'
>>> hashpw(my_password, salt)
b'$2b$12$YCnmXxOcs/GJVTHinSoVs.43v/.RVKXQSdOhHffiGNk2nMgKweR4u'
Here, we have simply generated a new salt using the default amount of rounds and used
hashpw to generate the hash. Notice how the salt is also in the first part of the hash for our
password? This is quite convenient as it means we don't also have to store the salt
separately, which we'll need when it comes to authenticating users later.
Since we used the default number of rounds to generate the salt, why not try setting your
own amount of rounds? Notice how the amount of time taken by hashpw increases the
higher you set this. My machine took almost 2 minutes to create a hash when the amount of
rounds was set to 20!
[ 240 ]
Extending TempMessenger with a User Authentication Microservice Chapter 6
As you can see, checkpw takes the password attempt that we are checking and the hashed
password as arguments. When we implement this in our dependency, the password
attempt will be the part coming from the web request and the hashed password will be
stored in the database. Since it was a successful attempt, checkpw returns True. Let's
attempt the same operation with an invalid password:
>>> password_attempt = b'invalid-password'
>>> checkpw(password_attempt, hashed_password)
False
If you'd like to learn more about storing passwords and the pitfalls of
certain methods, I'd suggest you read this short article from Dustin
Boswell:. It explains
nicely how hackers can attempt to crack passwords using brute force and
rainbow tables. It also goes into a Bcrypt in bit more detail.
import bcrypt
HASH_WORK_FACTOR = 15
Our new constant, HASH_WORK_FACTOR will be used for the rounds argument that gensalt
uses. I've set it to 15, which will cause it to take slightly longer to create password hashes
and check passwords, but it will be more secure. Please feel free to set this as you wish; just
bare in mind that the more you increase this, the longer it will take for our application to
create and authenticate users later on.
Now, outside any classes, we will define a new helper function for hashing passwords:
def hash_password(plain_text_password):
salt = bcrypt.gensalt(rounds=HASH_WORK_FACTOR)
encoded_password = plain_text_password.encode()
[ 241 ]
Extending TempMessenger with a User Authentication Microservice Chapter 6
This helper function simply takes our plain text password, generates a salt, and returns a
hashed password. Now, you may have noticed that when using Bcrypt, we always have to
ensure that the passwords we give it are bytestrings. As you'll notice from the preceding
code, we had to .encode() the password (which by default is UTF-8) before giving it to
hashpw. Bcrypt also will return the hashed password in the bytestring format. The problem
this will bring is that our field for passwords in our database is currently set to Unicode,
making it incompatible with our passwords. We have two options here: either call
.decode() on the password before we store it or amend our password field to something
that will accept bytestrings, such as LargeBinary. Let's go with the latter, as it is cleaner
and saves us from having to convert our data every time we wish to access it.
First, let's amend the line where we import our field types to include LargeBinary:
from sqlalchemy import Column, Integer, LargeBinary, Unicode
Now we can update our User model to use our new field type:
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
first_name = Column(Unicode(length=128))
last_name = Column(Unicode(length=128))
password = Column(LargeBinary())
The only problem we have now is that our existing database is not compatible with our new
schema. To solve this, we can either delete the database table or perform a migration. In
real-world environments, deleting a whole table is not an option, ever! If you have already
taken my advice earlier to study Alembic, then I'd encourage you to put your knowledge to
the test and perform a database migration. But for the purposes of this book, I will take
advantage of throwaway Docker containers and start from scratch. To do this, in the root of
your project, and inside your virtualenv, execute:
$ docker rm -f postgres
$ docker run --name postgres -e POSTGRES_PASSWORD=secret -e
POSTGRES_DB=users -p 5432:5432 -d postgres
$ python setup_db.py
This will delete your existing Postgres container, create a new one and run the
setup_db.py script we made earlier. If you check pgAdmin, you'll now see that the field
type in the column headers for password has changed from character varying (512)
to bytea.
[ 242 ]
Extending TempMessenger with a User Authentication Microservice Chapter 6
At last, we are now ready to update our create method to use our new hash_password
function:
def create(self, **kwargs):
plain_text_password = kwargs['password']
hashed_password = hash_password(plain_text_password)
kwargs.update(password=hashed_password)
user = User(**kwargs)
self.session.add(user)
self.session.commit()
As you can see, in the first three lines of the method we:
Let's try this out. In your terminal within your virtualenv, start (or restart) the User Service:
$ nameko run temp_messenger.user_service --config config.yaml
In another terminal window within your virtualenv, start your Nameko shell:
$ nameko shell
Inside your Nameko shell, execute the following to add a new user again:
>>> n.rpc.user_service.create_user('John', 'Doe', 'john@example.com',
'super-secret')
You should notice (depending on how large you set HASH_WORK_FACTOR) that there is now
a slight delay compared to last time when creating a new user.
[ 243 ]
Extending TempMessenger with a User Authentication Microservice Chapter 6
Another problem with this is that, if there were any other errors when creating a new user,
there is no nice way for our external services to react to these different types of errors
without knowing the type of database we are using, which we want to avoid at all costs.
To solve this, let's start by creating two new exception classes in our users.py:
class CreateUserError(Exception):
pass
class UserAlreadyExists(CreateUserError):
pass
[ 244 ]
Extending TempMessenger with a User Authentication Microservice Chapter 6
We also need to update our imports to include IntegrityError, which is the type of error
SQLAlchemy raises when there is a unique key violation:
from sqlalchemy.exc import IntegrityError
Again, we will amend our create method, this time to use our two new exceptions:
def create(self, **kwargs):
plain_text_password = kwargs['password']
hashed_password = hash_password(plain_text_password)
kwargs.update(password=hashed_password)
user = User(**kwargs)
self.session.add(user)
try:
self.session.commit() # ①
except IntegrityError as err:
self.session.rollback() # ②
error_message = err.args[0] # ③
[ 245 ]
Extending TempMessenger with a User Authentication Microservice Chapter 6
By doing this, our external services will now be able to differentiate between a user error
and an unexpected error.
To test this out, restart the User Service and attempt to add the same user again in the
Nameko shell.
Authenticating users
We can now look at how to authenticate users. This is a very simple process:
This is what we will raise in the event of the user not being found. Now we will update our
imports to include the following:
from sqlalchemy.orm.exc import NoResultFound
try:
user = query.filter_by(email=email).one() # ②
except NoResultFound:
message = 'User not found - {}'.format(email)
[ 246 ]
Extending TempMessenger with a User Authentication Microservice Chapter 6
raise UserNotFound(message) # ③
return user
1. In order to query our database, we first must make a query object using our user
model as an argument.
2. Once we have this, we can use filter_by and specify some parameters; in this
case, we just want to filter by email. filter_by always returns an iterable, since
you could have multiple results, but since we have a unique constraint on the
email field, it's safe to assume that we are only ever going to have one match if it
exists. Therefore, we call .one(), which returns the single object or raises
NoResultFound if the filter is empty.
3. We handle NoResultFound and raise our own exception, UserNotFound, with
an error message, which better suits our User Service.
First, let's create a new exception class that will be raised if there is a password mismatch:
class AuthenticationError(Exception):
pass
We can now create another method for our UserWrapper to authenticate users:
def authenticate(self, email, password):
user = self.get(email) # ①
1. We start by using our recently created get method to retrieve the user we want
to authenticate from our database.
[ 247 ]
Extending TempMessenger with a User Authentication Microservice Chapter 6
2. We then use bcrypt.checkpw to check that the attempted password matches the
password stored on the user object retrieved from the database. We call
.encode() on the password attempt because our external services aren't going to
do this for us. Nor should they; this is something specific to Bcrypt and such logic
should stay in the dependency.
3. If the password is incorrect, we raise our AuthenticationError error with an
appropriate message.
@rpc
def authenticate_user(self, email, password):
self.user_store.authenticate(email, password)
Nothing special here, just a simple pass-through to the user_store dependency method
we just made.
Let's test this out. Restart the user_service and execute the following in your Nameko
shell:
>>> n.rpc.user_service.authenticate_user('john@example.com', 'super-
secret')
>>>
That's it! That concludes our work on our User Service. We will now look at integrating it
with our existing services.
If you'd like to see how to write some tests for the User Service, you'll find
them, plus all the code, in the Github repository mentioned at the start of
this chapter.
[ 248 ]
Extending TempMessenger with a User Authentication Microservice Chapter 6
[ 249 ]
Extending TempMessenger with a User Authentication Microservice Chapter 6
The preceding diagram demonstrates how our services will integrate with each other. Take
note of how the Message Service and User Service are totally unaware of each other. A
change to the User Service should not require a change to the Message Service and vice
versa. By splitting these services, we also gain the advantage of being able to deploy new
code to a single service without affecting the others. A bonus from Nameko using
RabbitMQ is that, if a service does go down for a short period of time, any work will simply
be queued until the service comes back online. We will now begin to reap some of the
benefits of a microservice architecture.
To start this refactoring, let's create a new file within our temp_messenger folder,
message_service.py:
class MessageService:
name = 'message_service'
message_store = MessageStore()
@rpc
def get_message(self, message_id):
return self.message_store.get_message(message_id)
@rpc
def save_message(self, message):
message_id = self.message_store.save_message(message)
return message_id
@rpc
def get_all_messages(self):
messages = self.message_store.get_all_messages()
sorted_messages = sort_messages_by_expiry(messages)
return sorted_messages
[ 250 ]
Extending TempMessenger with a User Authentication Microservice Chapter 6
All we have done here is take the MessageService and all related code from our old
service.py and place it into our new message_service.py module.
Start by adding flask to our base.in file, then pip-compile and install (version 0.12.2 at
the time of writing) using the same process as earlier.
Getting started with Flask is quite straightforward; we will start by creating our new home
page endpoint. Within your temp_messenger directory, create a new file,
web_server.py , with the following:
app = Flask(__name__) # ②
@app.route('/') # ③
def home():
return render_template('home.html') # ④
With this, we will be able to get our new Flask web server up and running, albeit with no
functionality. To test this, first export some environment variables:
$ export FLASK_DEBUG=1
$ export FLASK_APP=temp_messenger/web_server.py
[ 251 ]
Extending TempMessenger with a User Authentication Microservice Chapter 6
The first will set the app to debug mode, one of the features I like about this as it will hot-
reload when we update our code, unlike a Nameko service. The second simply tells Flask
where our app lives.
Before we start the Flask app, please ensure that you are not currently
running your old Nameko web server as this will cause a port clash.
Within your virtualenv, execute the following in the root of our project to start the server:
$ flask run -h 0.0.0.0 -p 8000
This will start the Flask server on port 8000, the same port we had our old Nameko web
server running on. Provided your local network allows, you can even have other devices on
the same network navigate to your machine's IP and use TempMessenger! Now go to on your browser and you should see the following (albeit with
no functionality):
Looks similar to what we had before right? That's because Flask already uses Jinja2 as its
default templating engine, so if we want we can delete our old jinja2.py dependency as
it's no longer needed. Flask also looks for a folder called templates in the same directory
as the app, which is how it automatically knew where to find home.html.
[ 252 ]
Extending TempMessenger with a User Authentication Microservice Chapter 6
Let's now add the functionality of retrieving messages from our Message Service. This is
slightly different from when we were communicating between two Nameko services since
Flask does not know how to perform RPC's. First, let's add the following to our imports:
from flask.views import MethodView
from nameko.standalone.rpc import ClusterRpcProxy
from flask.json import jsonify
We will also need to add some config so that Flask knows where to find our RabbitMQ
server. We could just add this in our module as a constant, but since we already have
AMQP_URI in our config.yaml, it makes no sense to duplicate it! In our web_server.py
module, before app = Flask(__name__), add the following:
import yaml
with open('config.yaml', 'r') as config_file:
config = yaml.load(config_file)
This will load all of our config variables from config.yaml. Now add the following class
to web_server.py:
class MessageAPI(MethodView):
def get(self):
with ClusterRpcProxy(config) as rpc:
messages = rpc.message_service.get_all_messages()
return jsonify(messages)
Whereas our home page endpoint has a function-based view, here we have a class-based
view. We've defined a get method, which will be used for any GET requests to this
MessageAPI. Take note that the names of the methods are important here since they map to
their respective request types. If we were to add a post method (and we will later), then
that would map to all POST requests on the MessageAPI.
ClusterRpcProxy allows us to make RPCs outside a Nameko service. It's used as a context
manager and allows us to easily call our Message Service. Flask comes with a handy helper
function, jsonify, which converts our list of messages into JSON. It's then a simple task of
returning that payload, whereby Flask handles the response headers and status code for us.
Let's now add the functionality of sending new messages. First, amend your flask import to
include request:
from flask import Flask, render_template, request
[ 253 ]
Extending TempMessenger with a User Authentication Microservice Chapter 6
try:
message = data['message'] # ③
except KeyError:
return 'No message given', 400
1. You may notice that, rather than obtaining the request object from the post
parameters like we did with our Nameko web server, we are importing it from
Flask. In this context, it is a global object that parses all incoming request data for
us.
2. We use get_json, which is an inbuilt JSON parser that will replace our
get_request_data function from the last chapter. We specify that force=True,
which will enforce that the request has valid JSON data; otherwise it will return a
400 Bad Request error code.
3. Like our old post_message HTTP endpoint, we try to get data['message']
or return a 400.
4. We then again use ClusterRpcProxy to make an RPC to save the message.
5. Return a 204 if all went well. We use 204 rather than a 200 here to indicate that,
while the request was still successful, there is no content to be returned.
There's one more thing we need to do before this will work, and that is to register our
MessageAPI with an API endpoint. At the bottom of our web_server.py, outside the
MessageAPI class, add the following:
app.add_url_rule(
'/messages', view_func=MessageAPI.as_view('messages')
)
[ 254 ]
Extending TempMessenger with a User Authentication Microservice Chapter 6
It's now time to bring our Message Service back online. In a new terminal window and
inside your virtualenv, execute:
$ nameko run temp_messenger.message_service --config config.yaml
Provided that you still have your Flask server running, you should now be able to visit our
app in all its former glory at!
[ 255 ]
Extending TempMessenger with a User Authentication Microservice Chapter 6
Web sessions
Now that we have our old functionality back using our new Flask server, we can start to
add some new features such as logging users in and out, creating new users , and allowing
only logged in users to send messages. All of these depend heavily on web sessions.
Web sessions allow us to keep track of users between different requests via cookies. In these
cookies, we store information that can be passed on from one request to the next. For
example, we could store whether a user is authenticated, what their email address is, and so
on. The cookies are signed cryptographically using a secret key, which we will need to
define before we can use Flask's Sessions. In config.yaml, add the following:
FLASK_SECRET_KEY: 'my-super-secret-flask-key'
Feel free to set your own secret key, this is just an example. In a production-like
environment, this would have to be kept safe and secure, otherwise a user could forge their
own session cookies.
We will now need to tell our app to use this secret key. After app = Flask(__name__),
add the following:
app.secret_key = config['FLASK_SECRET_KEY']
With this done, Flask will now use our FLASK_SECRET_KEY from our config.yaml to sign
cookies.
class SignUpView(MethodView):
def get(self):
return render_template('sign_up.html')
This new SignUpView class will be responsible for dealing with the sign-up process. We've
added a get method, which will simply render the sign_up.html template that we will
create later.
[ 256 ]
Extending TempMessenger with a User Authentication Microservice Chapter 6
At the end of the web_server.py module, create the following URL rule:
app.add_url_rule(
'/sign_up', view_func=SignUpView.as_view('sign_up')
)
As you probably already know, this will direct all requests to /sign_up to our new
Now let's create our new template. In the templates folder, create a new file,
<!DOCTYPE html>
<body>
<h1>Sign up</h1>
<form action="/sign_up" method="post">
<input type="text" name="first_name" placeholder="First Name">
<input type="text" name="last_name" placeholder="Last Name">
<input type="text" name="email" placeholder="Email">
<input type="password" name="password" placeholder="Password">
<input type="submit" value="Submit">
</form>
{% if error_message %}
<p>{{ error_message }}</p>
{% endif %}
</body>
This is a basic HTML form, consisting of the fields needed to create a new user in our
database. The action and method forms tell it to make a post request to the /sign_up
endpoint. All fields are text fields with the exception of password, which is of type
password, which will cause the user input to be masked. We also have a Jinja if statement
that will check to see if the template was rendered with an error_message. If so, then it
will be displayed in a paragraph block. We will use this later to display messages such
as User already exists to the user.
With these changes made, provided you still have the Flask server running, navigate to and you should see the new sign-up page:
[ 257 ]
Extending TempMessenger with a User Authentication Microservice Chapter 6
This form will not yet do anything, as we have not defined a post method for our
SignUpView. Let's go ahead and create that. First, update our imports in web_server.py
to include RemoteError from Nameko and session, redirect, and url_for from Flask:
from nameko.exceptions import RemoteError
from flask import (
Flask,
Redirect,
render_template,
request,
session,
url_for,
)
[ 258 ]
Extending TempMessenger with a User Authentication Microservice Chapter 6
try:
cluster_rpc.user_service.create_user( # ②
first_name=first_name,
last_name=last_name,
password=password,
)
except RemoteError as err: # ③
message = 'Unable to create user {} - {}'.format(
err.value
)
app.logger.error(message)
return render_template(
'sign_up.html', error_message=message
)
session['authenticated'] = True # ④
session['email'] = email # ⑤
return redirect(url_for('home')) # ⑥
This is quite a long method, but it's fairly simple. Let's go through it step-by-step:
[ 259 ]
Extending TempMessenger with a User Authentication Microservice Chapter 6
Before we test this out, if you don't already have the User Service running, in a new
terminal within your virtualenv execute:
nameko run temp_messenger.user_service --config config.yaml
With this, you should now have your User Service, Message Service and Flask web server
running simultaneously in different terminal windows. If not, then start them using the
nameko and flask commands from earlier.
Once you hit Submit, it should redirect you to the home page and you should have a new
user in your database. Check pgAdmin to ensure that they have been created.
[ 260 ]
Extending TempMessenger with a User Authentication Microservice Chapter 6
It's all well and good having a sign-up page, but our users need to be able to navigate to it
without knowing the URL! Let's make some adjustments to our home.html to add a simple
Sign up link. While we are at it, we can also hide the ability to send new messages unless
they are logged in! In our home.html, amend our existing postMessage form to the
following:
{% if authenticated %}
<form action="/messages" id="postMessage">
<input type="text" name="message" placeholder="Post message">
<input type="submit" value="Post">
</form>
{% else %}
<p><a href="/sign_up">Sign up</a></p>
{% endif %}
What we have done here is to wrap our form in a Jinja if block. If the user is
authenticated, then we will show the postMessage form; otherwise, we will display a
link directing the user to the sign-up page.
[ 261 ]
Extending TempMessenger with a User Authentication Microservice Chapter 6
We will now also have to update our home endpoint to pass the authenticated Boolean
from the session object to the template renderer. First, let's add a new helper function that
gets the authenticated state of a user. This should sit outside any classes inside your
web_server.py module:
def user_authenticated():
return session.get('authenticated', False)
This will attempt to get the authenticated Boolean from the session object. If it's a
brand new session then we can't guarantee that the authenticated will be there, so we
default it to False and return it.
This will make a call to user_authenticated to get the authenticated Boolean of our user.
We then render the template by passing it authenticated.
Another nice adjustment we can make is to only allow the user to go to the sign up page if
they are not authenticated. To do this, we will need to update our get method in our
def get(self):
if user_authenticated():
return redirect(url_for('home'))
else:
return render_template(sign_up.html')
If we are authenticated, then we redirect the user to the home endpoint; otherwise, we
render the sign_up.html template.
If you still have the browser open that you used to create your first user, then if you try to
navigate to it should redirect you to the home page of
our site since you are already authenticated.
If you open a different browser, on the home page, you should see the new Sign up link we
made and the ability to send new messages should have disappeared, since you have a new
session.
[ 262 ]
Extending TempMessenger with a User Authentication Microservice Chapter 6
We now have a new issue. We have prevented users from sending new messages from the
app, but they can still send them if they were to use Curl or a REST client. To stop this from
happening, we need to make a small tweak to our MessageAPI. At the start of the
MessageAPI post method, add the following:
def post(self):
if not user_authenticated()
return 'Please log in', 401
...
Be sure not to adjust any of the other code; the ... denotes the rest of the code from our
post method. This will simply reject the user's request with a 401 response that tells the
user to log in.
If a user hits this endpoint, Flask will clear their session object and redirect them to the
home endpoint. Since the session is cleared, the authenticated Boolean will be deleted.
In home.html, let's update our page to include the link for users to log out. To do this, we
will add a new link just after our postMessage form:
{% if authenticated %}
<form action="/messages" id="postMessage">
<input type="text" name="message" placeholder="Post message">
<input type="submit" value="Post">
</form>
<p><a href="/logout">Logout</a></p>
...
[ 263 ]
Extending TempMessenger with a User Authentication Microservice Chapter 6
Once saved, and provided we are logged in, we should now have a Logout link underneath
our message form:
After clicking the Logout link, you should be redirected back to the home page, where you
will no longer be able to send messages.
Logging users in
Our app can't be complete without the ability to log a user in! In our web_server.py,
create a new class, LoginView:
class LoginView(MethodView):
def get(self):
if user_authenticated():
return redirect(url_for('home'))
else:
return render_template('login.html')
[ 264 ]
Extending TempMessenger with a User Authentication Microservice Chapter 6
Like the get in our SignUpView, this one will check to see if the user is already
authenticated. If so, then we will redirect them to the home endpoint, otherwise, we will
render the login.html template.
At the end of our web_server.py module, add the following URL rule for the LoginView:
app.add_url_rule(
'/login', view_func=LoginView.as_view('login')
)
As you can see, this is quite similar to our sign_up.html template. We create a form, but
this time we only have the email and password fields. We also have a Jinja if block for
error messages. However, this one has a hardcoded error message rather than one returned
from the LoginView. This is because it is bad practice to tell a user why they failed to log in.
If it was a malicious user and we were telling them things such as This user does not exist or
Password incorrect then this alone would tell them which users exist in our database and
they could possibly attempt to brute-force passwords.
In our home.html template, let's also add a link for users to log in. To do this, we will add a
new link in the else statement of our if authenticated block:
{% if authenticated %}
...
{% else %}
<p><a href="/login">Login</a></p>
<p><a href="/sign_up">Sign up</a></p>
{% endif %}
[ 265 ]
Extending TempMessenger with a User Authentication Microservice Chapter 6
We should now be able to navigate to the Login page from the home page:
In order for our Login page to work, we will need to create a post method in our
LoginView. Add the following to LoginView:
def post(self):
password = request.form['password']
[ 266 ]
Extending TempMessenger with a User Authentication Microservice Chapter 6
session['authenticated'] = True # ④
session['email'] = email # ⑤
return redirect(url_for('home')) # ⑥
You'll notice that this is quite similar to our SignUpView post method. Let's briefly go over
what is happening:
With the preceding code, rather than return the error message to the user, we choose to log
the error message to the console where only we can see it. This allows us to see if there are
any issues with our authentication system or if a malicious user is up to no good, while still
letting the user know that they supplied invalid information.
Provided our services are all still running, you should now be able to test this out! We now
have a fully functioning authentication system for TempMessenger and our goals are
complete.
[ 267 ]
Extending TempMessenger with a User Authentication Microservice Chapter 6
return message_id
The first thing you'll notice is that, in order to call save_message, we now require the
user's email.
What we have also done here is to change the format of the data we are storing in Redis
from a string to a hash. Redis hashes allow us to store dictionary-like objects as the value.
They also have the added benefit of being able to pick which key from the dictionary we
want to get back out later, as opposed to getting the whole object out.
So here we create a dictionary of the user's email and password and use hmset to store it in
Redis. hmset does not have a px or ex argument, so instead we make a call to pexpire,
which expires the given key for the given number of milliseconds. There is also an expire
equivalent of this for seconds.
To learn more about Redis hashes and other data types, see:.
We will now update our get_all_messages method in the RedisClient to the following:
def get_all_messages(self):
return [
{
'id': message_id,
'email': self.redis.hget(message_id, 'email'),
'message': self.redis.hget(message_id, 'message'),
'expires_in': self.redis.pttl(message_id),
}
for message_id in self.redis.keys()
]
[ 268 ]
Extending TempMessenger with a User Authentication Microservice Chapter 6
Since the data has changed to a hash, we also have to retrieve it from Redis differently,
using the hget method. We also get the email corresponding to each message.
@rpc
def save_message(self, email, message):
message_id = self.message_store.save_message(
)
return message_id
All we have done here is update the arguments for the RPC to include email and pass that
to the updated message_store.save_message.
Back in our web_server.py, we will need to update the MessageAPI post method to send
the user's email when it makes the RPC to the MessageService:
def post(self):
if not user_authenticated():
return 'Please log in', 401
data = request.get_json(force=True)
try:
message = data['message']
except KeyError:
return 'No message given', 400
[ 269 ]
Extending TempMessenger with a User Authentication Microservice Chapter 6
In order to see these changes on our page, we will also need to update the home.html
template. For our JavaScript function, updateMessages, update it to the following:
function updateMessages(messages) {
var $messageContainer = $('#messageContainer');
var messageList = [];
var emptyMessages = '<p>No messages!</p>';
if (messages.length === 0) {
$messageContainer.html(emptyMessages);
} else {
$.each(messages, function(index, value) {
var message = $(value.message).text() || value.message;
messageList.push(
'<p>' + value.email + ': ' + message + '</p>'
);
});
$messageContainer.html(messageList);
}
}
This is a minor tweak. If you can't spot it, we've updated the messageList.push to include
the email.
Before you test this, ensure that your Redis store is empty, as old messages will be in the old
format and will break our app. You can do this by using redis-cli inside of our Redis
container:
$ docker exec -it redis /bin/bash
$ redis-cli -h redis
redis:6379> flushall
OK
redis:6379>
[ 270 ]
Extending TempMessenger with a User Authentication Microservice Chapter 6
Also, be sure to restart our Message Service so that it takes the new changes into effect.
Once you have done that, we can test this new functionality:
Summary
This now concludes our work on the TempMessenger User Authentication system. We
started this chapter by using a Postgres database with Python and created a Nameko
Dependency to encapsulate it. This was different from our Redis dependency from the last
chapter since the data is permanent and required a lot more planning. Despite this, we
tucked this logic away and simply exposed two RPC's: create_user and
authenticate_user.
We then looked at how to securely store user passwords in a database. We explored some of
the ways you can do this incorrectly, such as by storing passwords in plain text. We used
Bcrypt to cryptographically hash our passwords to prevent them from being read if our
database was compromised.
[ 271 ]
Extending TempMessenger with a User Authentication Microservice Chapter 6
When it came to linking the new User Service to the rest of our application, we first split out
each service into its own module to allow us to deploy, update, and manage them
independently. We reaped some of the benefits of a microservice architecture by showing
how easy it was to replace one framework (Nameko) with another (Flask) in the Web Server
without affecting the rest of the platform.
We explored the Flask framework and how to create function-based and class-based views.
We also looked at Flask session objects and how we could store user data from one request
to the next.
As a bonus, we amended our message list to also include the email address of the user who
sent it.
I'd encourage you to think of new enhancements to make for TempMessenger and plan
accordingly how you would add them, ensuring that logic from our dependencies does not
leak outside the service it belongs to—a mistake made by many! Keeping our service
boundaries well defined is a hard task and sometimes it helps to start off with a more
monolithic approach and separate them out later once they are clear. This is similar to the
approach we took with MessageService and WebServer from the last chapter. Building
Microservices (O'Reilly) by Sam Newman explains this very well and also covers in more
detail the benefits, drawbacks, and challenges associated with building distributed systems.
With this chapter complete, I hope I have given you a deeper insight into how you can
benefit from a Microservice architecture in practice. The journey we took creating this
application was purposely modular, not only to reflect the modularity of microservices but
to demonstrate how we should go about adding new features with minimal impact to the
rest of the platform.
[ 272 ]
Online Video Game Store with
7
Django
I was born in the late seventies, which means that I grew up during the birth of the video
game industry. My first video game console was the Atari 2600, and it was because of that
specific video game console that I decided that I wanted to be a programmer and make
video games. I never got a job within the gaming industry, however, but I still love playing
video games, and in, my spare time, I try to develop my own games.
To this day, I still go around the internet—especially eBay—buying old video games to
bring back my nice childhood memories when all the family, my parents, and my sister,
used to play Atari 2600 games together.
Because of my interest in vintage video games, we are going to develop a vintage video
game online store; this will be a great way to develop something fun and also learn a lot
about web development with the popular Django web framework.
Also, as an extra, we will be using the npm (Node Package Manager) to download the
client-side dependencies. We will also cover how to create simple tasks using the task
runner Gulp.
Online Video Game Store with Django Chapter 7
To make our application prettier without a lot of effort, we are going to use Bootstrap.
First, we want to create the directory where we are going to keep our project. In your
working directory, create a directory called django-project as follows:
mkdir django-project && cd django-project
If you have Python 3 installed in another location, you can use the argument --python and
specify the path where the Python executable is located. If everything went fine, you should
see an output such as the following:
[ 274 ]
Online Video Game Store with Django Chapter 7
Now we can activate our virtual environment using the pipenv command shell:
pipenv shell
Great! The only dependency that we are going to add for now is Django.
At the time of writing this book, Django 2.0 had been released. It has really
nice features compared to its predecessor. You can see the list of new
features at.
Django 2.0 has dropped support for Python 2.0, so if you are planning to develop an
application using Python 2, you should install Django 1.11.x or lower. I strongly
recommend that you start a new project using Python 3. Python 2 will stop being
maintained after a couple of years, and new packages will be created for Python 3. Popular
packages of Python 2 will migrate to Python 3.
In my opinion, the best new feature of Django 2 is the new routing syntax, because now it is
not necessary to write regular expressions. It is much cleaner and more readable to write
something like the following:
path('user/<int:id>/', views.get_user_by_id)
It is much simpler this way. Another feature that I really like in Django 2.0 is that they have
improved the admin UI a little bit and made it responsive; this is a great feature, because I
have experienced that creating a new user (while you are on the go with no access to a
desktop) on a non-responsive site on a small mobile phone screen can be painful.
[ 275 ]
Online Video Game Store with Django Chapter 7
Installing Node.js
When it comes to web development, it is almost impossible to stay away from Node.js.
Node.js is a project that was released back in 2009. It is a JavaScript runtime that allows us
to run JavaScript on the server-side. Why do we care about Node.js if we are developing a
website using Django and Python? The reason is that the Node.js ecosystem has several
tools that will help us to manage the client-side dependencies in a simple manner. One of
these tools that we are going to use is the npm.
Think about npm as the pip of the JavaScript world. npm, however, has many more
features. One of the features that we are going to use is npm scripts.
So, let's go ahead and install Node.js. Usually, developers need to go over to the Node.js
website and download it from there, but I find it much simpler to use a tool called NVM,
which allows us to install and switch easily between different versions of Node.js.
To install NVM in our environment, you can follow the instructions at.
com/creationix/nvm.
When NVM is installed, you are ready to install the latest version of Node.js with the
following command:
nvm install node
You can also type npm on the terminal, where you should see an output similar to the
output that follows:
[ 276 ]
Online Video Game Store with Django Chapter 7
Note that django-admin created a directory called gamestore that contains some
boilerplate code for us. We will go through the files that Django created in a little while, but,
first, we are going to create our first Django application. In the Django world, you have the
project and the application, and according to the Django documentation, the project
describes the web application itself, and the application is a Python package that provides
some kind of feature; these applications contain their own set of routes, views, static files
and can be reused across different Django projects.
[ 277 ]
Online Video Game Store with Django Chapter 7
Don't worry if you don't understand it completely; you will learn more as we progress.
With that said, let's create the project's initial application. Run cd gamestore, and once
you are inside the gamestore directory, execute the following command:
python-admin startapp main
If you list the contents of the gamestore directory, you should see a new directory named
main; that's the directory of the Django application that we are going to create.
Without writing any code at all, you already have a totally functional web application. To
run the application and see the results, run the following command:
python manage.py runserver
You have 14 unapplied migration(s). Your project may not work properly
until you apply the migrations for app(s): admin, auth, contenttypes,
sessions.
Run 'python manage.py migrate' to apply them.
Open your favorite web browser, and go to, where you will see
the following page:
[ 278 ]
Online Video Game Store with Django Chapter 7
One thing to note when we start the application for the first time is the following warning:
You have 14 unapplied migration(s). Your project may not work properly
until you apply the migrations for app(s): admin, auth, contenttypes,
sessions.
Run 'python manage.py migrate' to apply them.
This means that the apps that are registered by default on a Django project, admin, auth,
contenttypes, and sessions have migrations (database changes) that haven't been
applied to this project. We can run these migrations with the following command:
➜ python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
[ 279 ]
Online Video Game Store with Django Chapter
Here Django created all the tables in a SQLite database, you will find the SQLite database
file in the application's root directory.
The db.sqlite3 file is the database file that contains the tables for our application. The
choice of SQLite is just to make the application simpler for this chapter. Django supports a
large set of databases; the most popular databases, such as, Postgres, Oracle, and even
MSSQL are supported.
If you run the runserver command again, there should not be any migration warnings:
→ python manage.py runserver
Performing system checks...
Now there's only one thing that we need to do to wrap this section up; we need to create an
administrator user so we can log in to the Django admin UI and administrate our web
application.
As with everything else in Django, this is very simple. Just run the following command:
python manage.py createsuperuser
[ 280 ]
Online Video Game Store with Django Chapter 7
You will be asked to enter a username and email and to set the password, that is all you
have to do to set an administrator account.
In the next section, we are going to have a closer look at the files that the Django created for
us.
We can set up a new database and create a superuser, and, on the top of that, Django comes
with a very nice and useful admin UI, where you can visualize our data, , and users.
In this section, we are going to explore the code that Django created for us when starting a
new project so that we can get familiar with the structure. Let's go ahead and start adding
the other components of our project.
If you have a look inside of the project's root directory, you will find a file called
db.sqlite3, another file called manage.py, and, lastly, a directory with the same name as
the project, in our case gamestore. The db.sqlite3 file, as the name suggests, is the
database file; this file is created here on the project's root folder because we are working
with SQLite. You can explore this file directly from the command line; we are going to
demonstrate how to do that shortly.
The second file is manage.py. This file is created automatically by the django-admin in
every Django project. It basically does the same things as django-admin, plus two extra
things; it will set the DJANGO_SETTINGS_MODULE to point to the project's setting file and
also put the project's package on the sys.path. If you execute manage.py without any
arguments, you can see the help with all the commands available.
As you can see with manage.py, you have many options, such as manage passwords,
create a superuser, manage the database, create and execute database migrations, start new
apps and projects, and a very important option in runserver, which, as the name says, will
start the Django development server for you.
[ 281 ]
Online Video Game Store with Django Chapter 7
Now that we have learned about manage.py and how to execute its commands, we are
going to take a step back and learn how to inspect the database that we just created. The
command to do that is dbshell; let's give it a go:
python manage.py dbshell
If you want to get a list of all the database's tables, you can use the command .tables:
sqlite> .tables
auth_group auth_user_user_permissions
auth_group_permissions django_admin_log
auth_permission django_content_type
auth_user django_migrations
auth_user_groups django_session
Here you can see that we have all the tables that we created through the migrate
command.
To look at every table structure, you can use the command .schema, and we can use the
option --indent, so the output will be displayed in a more readable manner:
sqlite> .schema --indent auth_group
CREATE TABLE IF NOT EXISTS "auth_group"(
"id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
"name" varchar(80) NOT NULL UNIQUE
);
These are the commands that I use the most when working with SQLite3 databases, but the
command-line interface offers a variety of commands. You can use the .help command to
get a list of all available commands.
[ 282 ]
Online Video Game Store with Django Chapter 7
Then you have the urls.py; this file is where you specify the URLs that will be available on
your application. You can setup URLs on the project level but also for every Django app. If
you examine the contents of this urls.py file, you won't find much detail. Basically, you
will see text explaining how to add new URLs, but Django has defined (out of the box) a
URL to the Django admin site:
from django.contrib import admin
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
]
We are going to go through the process of adding new URLs to the project, but we can
explain this file anyway; remember when I mentioned that in Django you can have diverse
apps? So django.contrib.admin is also an app, and an app has its own set of URLs,
views, templates. So what it is doing here? When we import the admin app and then define
a list called urlpatterns, in this list we use a function path where the first argument is the
URL, and the second argument here can be a view that is going to be executed. But in this
case, it is passing the URLs of the admin.site app, which means that admin/ will be the
base URL, and all the URLs defined in admin.site.urls will be created under it.
[ 283 ]
Online Video Game Store with Django Chapter 7
For example, if in admin.site.url, I have defined two URLs, users/ and groups/, when
I have path('admin/', admin.site.urls), I will be actually creating two URLs:
admin/users/
admin/groups/
Lastly, we have the wsgi.py, which is a simple WSGI configuration that Django creates for
us when creating a new project.
Now that we are a bit more familiar with the Django's project structure, it is time to create
our project's first app.
Let's go ahead and run the command startapp, and, as shown before, you can either use
the django-admin command or use manager.py. As we created the project using the
django-admin command, it is a good opportunity to test the manager.py command. To
create a new Django app, run the following command:
python manager.py startapp main
Here, we are going to create an app named main. Don't worry that no output is displayed,
Django creates the project and the app silently. If you get a list of the directory contents
now, you will see that there is a directory named main, and inside the main directory you
will find some files; we are going to explain every file while we are adding changes to it.
So, the first thing we want to do is to add a landing page to our application. To do that, we
have to do three things:
First, we add a new URL to tell Django that when a user of our site browses to the
root, it should go the site / and display some content
The second step is to add a view that will be executed when the user browses to
the site's root /
[ 284 ]
Online Video Game Store with Django Chapter 7
The last step is to add an HTML template with the content that we want to
display to the users
With that said, we need to include a new file called urls.py inside of the main app
directory. First, we add some imports:
from django.urls import path
from . import views
In the preceding code, we imported the function path from django.urls. The path
function will return an element to be included in the urlpatterns list, and we also import
the views file in the same directory; we want to import this view because it is there that we
are going to define functions that will be executed when a specific route is accessed:
urlpatterns = [
path(r'', views.index, name='index'),
]
Then we use the path function to define a new route. The first argument of the function
path is a string that contains the URL pattern that we wish to make available in our
application. This pattern may contain angle brackets (for example, <int:user_id>) to
capture parameters passed on the URL, but, at this point, we are not going use it; we just
want to add a URL for the application's root, so we add an empty string ''. The second
argument is the function that is going to be executed, and, optionally, you can add the
keyword argument name, which sets the URL's name. We will see why this is useful in a
short while.
The second part is to define the function called index in the views.py file, as follows:
from django.shortcuts import render
def index(request):
return render(request, 'main/index.html', {})
As there are not too many things going on at this point, we first import the render function
from django.shortcuts. Django has its own template engine that is built into the
framework, and it is possible to change the default template engine to other template
engines you like (such as Jinja2, which is one of the most popular template engines in the
Python ecosystem), but, for simplicity, we are going to use the default engine. The render
function gets the request object, the template, and a context object; the latter is an object that
contains data to be displayed in the template.
[ 285 ]
Online Video Game Store with Django Chapter 7
The next thing we need to do is to add a template that will contain the content that we want
to display when the user browses to our application. Now, most of the web application's
pages contain parts that never change, such as a top menu bar or a page's footer, and these
parts can be put into a separate template that can be reused by other templates. Luckily, the
Django template engine has this feature. In fact, we can not only inject sub-templates inside
a template, but also we can have a base template that will contain the HTML that will be
shared between all of the pages. With that said, we are going to create a file called
base.html inside the gamestore/templates directory that has the following contents:
<">
{% load staticfiles %}
<link href="{% static 'styles/site.css' %}" rel='stylesheet'>
<link href="{% static 'styles/bootstrap.min.css' %}"
rel='stylesheet'>
<link href="{% static 'styles/font-awesome.min.css' %}"
rel='stylesheet'>
</head>
<body>
[ 286 ]
Online Video Game Store with Django Chapter 7
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li>
<a href="/">
<i class="fa fa-home" aria-</i> HOME
</a>
</li>
{% if user.is_authenticated%}
<li>
<a href="/cart/">
<i class="fa fa-shopping-cart"
aria-</i> CART
</a>
</li>
{% endif %}
</ul>
</div><!--/.nav-collapse -->
</div>
</nav>
<div class="container">
<div class="starter-template">
{% if messages %}
{% for message in messages %}
<div class="alert alert-info" role="alert">
</div>
{% endfor %}
{% endif %}
{% block 'content' %}
{% endblock %}
</div>
</div>
</body>
</html>
We are not going to go through all the HTML parts, just the parts that are the specific
syntax of Django's template engine:
{% load static %}
<link href="{% static 'styles/site.css' %}" rel='stylesheet'>
<link href="{% static 'styles/bootstrap.min.css' %}"
rel='stylesheet'>
<link href="{% static 'styles/font-awesome.min.css' %}"
rel='stylesheet'>
[ 287 ]
Online Video Game Store with Django Chapter 7
The first thing to note here is {% load static %}, which will tell Django's template
engine that we want to load the static template tag. The static template tag is used to link
static files. These files can be images, JavaScript, or Stylesheet files. How does Django
find those files, you may ask, and the answer is simple: by magic! No, just kidding; the
static template tag will look for the files in the directory specified in the STATIC_ROOT
variable in the settings.py file; in our case we defined STATIC_ROOT = '/static/', so
when using the tag {% static 'styles/site.css' %} the link
/static/styles/site.css will be returned.
You may be wondering, why not just write /static/styles/site.css instead of using
the tag? The reason for this is that the tag gives us much more flexibility for change in case
we need to update the path where we serve our static files. Imagine a situation where you
have a large application with hundreds of templates, and in all of them, you
hardcode /static/ and then decide to change that path (and you don't have a team). You
would need to change every single file to perform this change. If you use the static tag, you
can simply move the files to a different location, and the tag changes the value of the
STATIC_ROOT variable in the settings files.
Another tag that we are using in this template is the block tag:
{% block 'content' %}
{% endblock %}
The block tag is very simple; it defines an area in the base template that can be used by
children templates to inject content in that area. We are going to see exactly how this works
when we create the next template file.
The third part is to add the template. The index function is going to render a
template stored at main/index.html, which means that it will leave it in the directory
main/templates/main/. Let's go ahead and create the folder main/templates and
then main/templates/main:
mkdir main/templates && mkdir main/templates/main
{% block 'content' %}
<h1>Welcome to the gamestore!</h1>
{% endblock %}
[ 288 ]
Online Video Game Store with Django Chapter 7
As you can see, here, we start off by extending the base template, which means that all the
content of the base.html file will be used by the Django template engine to build the
HTML that will be provided back to the browser when the user browses to /. Now, we also
use the block tag; in this context, it means that the engine will search for a block tag named
'content' in the base.html file, and, if it finds it, the engine will insert the h1 html tab
inside the 'content' block.
This is all about reusability and maintainability of code, because you don't need to insert the
menu markup and tags to load JavaScript and CSS files in every single template of our
application; you just need to insert them in the base template and use the block tag here.
The content will change. A second reason to use base templates is that, again, imagine a
situation where you need to change something—let's say the top menu that we defined in
the base.html file, as the menu is only defined in the base.html file. All you need to do
to perform changes is to change the markup in the base.html, and all the other templates
will inherit the changes.
We are almost ready to run our code and see how the application is looking so far, but, first,
we need to install some client-side dependencies.
Bootstrap is a very well-known toolkit that has been around for many years. It has a very
nice set of components, a grid system, and plugins that will help us make our application
look great for our users when they are browsing the application on a desktop, or even a
mobile device.
Font Awesome is another project that has been around for a while, and it is a font and icons
framework.
To install these dependencies, we could just run the npm's install command. However, we
are going to do better. Similar to pipenv, which creates a file for our Python dependencies,
npm has something similar. This file is called package.json, and it contains not only the
project's dependencies but also scripts and meta information about the package.
[ 289 ]
Online Video Game Store with Django Chapter 7
So let's go ahead and add the package.json file to the gamestore/ directory, with the
following content:
{
"name": "gamestore",
"version": "1.0.0",
"description": "Retro game store website",
"dependencies": {
"bootstrap": "^3.3.7",
"font-awesome": "^4.7.0"
}
}
Great! Save the file, and run this command on the terminal:
npm install
If everything goes well, you should see a message saying that two packages have been
installed.
If you list the contents of the gamestore directory, you will see that npm created a new
directory called node_modules, and it is there that npm installed Bootstrap and Font
Awesome.
For simplicity, we are going to just copy the CSS files and fonts that we need to the static
folder. However, when building an application, I would recommend using tools such
as webpack, which will bundle all our client-side dependencies and set up a webpack dev
server to serve the files for your Django application. Since we want to focus on Python and
Django we can just go ahead and copy the files manually.
Then we need to copy the bootstrap files. First, the minified CSS file:
cp node_modules/bootstrap/dist/css/bootstrap.min.css static/styles/
Next, we need to copy the Font Awesome files, starting with the minified CSS:
cp node_modules/font-awesome/css/font-awesome.min.css static/styles/
[ 290 ]
Online Video Game Store with Django Chapter 7
We are going to add another CSS file that will contain some custom CSS that we may add to
the application to give a personal touch to the application. Add a file called site.css in
the gamestore/static/styles directory with the following contents:
.nav.navbar-nav .fa-home,
.nav.navbar-nav .fa-shopping-cart {
font-size: 1.5em;
}
.starter-template {
padding: 70px 15px;
}
h2.panel-title {
font-size: 25px;
}
There are a few things we need to do to run our application for the first time; first, we need
to add the main app that we created to the INSTALLED_APPS list in the settings.py file in
the gamestore/gamestore directory. It should look like this:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'main',
]
In the same settings file you will find the list TEMPLATES:
TEMPLATES = [
{
'BACKEND':
'django.templates.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.templates.context_processors.debug',
'django.templates.context_processors.request',
'django.contrib.auth.context_processors.auth',
[ 291 ]
Online Video Game Store with Django Chapter 7
'django.contrib.messages.context_processors.messages',
],
},
},
]
That will tell Django to search for templates in the templates directory.
Then, at the end of the settings.py file, add the following line:
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), ]
This will tell Django to search for static files in the gamestore/static directory.
Now we need to tell Django to register the URLs that we have defined in the main app. So,
let's go ahead and open the file urls.py in the gamestore/gamestore directory. We need
to include "main.urls" in the urlpatterns list. After the changes, the urls.py file
should look like this:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('main.urls'))
]
Note that we also need to import the include function of the django.urls module.
Great! Now we have all the client-site dependencies in place and ready to be used by our
application, and we can start the application for the first time to see the changes that we
have implemented so far. Open the terminal, and use the command runserver to start
Django's development server, like so:
python manage.py runserver
[ 292 ]
Online Video Game Store with Django Chapter 7
Browse to; you should see a page like the one shown in the
following screenshot:
We are going to start adding the login and logout functionality. The good news is that it is
super easy to implement in Django.
First, we need to add a Django form to our login page. Django has a built-in form of
authentication; however, we want to customize it, so we are going to create another class
that inherits from the Django built-in AuthenticationForm and add our changes.
class AuthenticationForm(AuthenticationForm):
username = forms.CharField(
max_length=50,
widget=forms.TextInput({
'class': 'form-control',
[ 293 ]
Online Video Game Store with Django Chapter 7
password = forms.CharField(
label="Password",
widget=forms.PasswordInput({
'class': 'form-control',
'placeholder': 'Password'
})
)
This class is quite simple. First, we import forms from the django module and
the AuthenticationForm from django.contrib.auth.forms, and then we create
another class, also called AuthenticationForm, which inherits from Django's
AuthenticationForm. Then we define two properties, the username and the password.
We define the username as an instance of CharField , and there are some keyword
arguments that we pass in its constructor. They are:
max_length, which, as the name suggests limits the size of the string to 50
characters.
We also use the widget argument, which specifies how this property will be
rendered on the page. In this case, we want to render it as an input text element,
so we pass an instance to TextInput. It is possible to pass some options to the
widget; in our case, here we pass 'class', which is the CSS class and the
placeholder.
All these options will be used when the template engine renders this property on the page.
The second property that we define here is the password. We also define it as a CharField,
and, instead of passing max_length, this time we set the label to 'Password'. The widget
we set to PasswordInput so the template engine will render the field on the page as input
with a type equal to the password, and, lastly, we define the same settings for this field class
and placeholder.
Now we can start registering the new URLs for logging in and out. Open the file
gamestore/main/urls.py. To start, we are going to add some import statements:
[ 294 ]
Online Video Game Store with Django Chapter 7
After the import statements, we can start registering the authentication URLs. At the end of
the urlpattens list, add the following code:
path(r'accounts/login/', login, {
'template_name': 'login.html',
'authentication_form': AuthenticationForm
}, name='login'),
So, here we are creating a new URL, 'accounts/login', and when requesting this URL
the function view login will be executed. The third argument for the path function is a
dictionary with some options, and the template_name specifies the template that will be
rendered on the page when browsing to the underlying URL. We also define the
authetication_form with the AuthenticationForm value that we just created. Lastly,
we set the keyword argument name to login; naming the URL is very helpful when we
need to create a link for this URL and also improves maintainability, because changes in the
URL itself won't require changes in the templates as the templates reference the URL by its
name.
Now that the login is in place, let's add the logout URL:
path(r'accounts/logout/', logout, {
'next_page': '/'
}, name='logout'),
Similar to the login URL, in the logout URL we use the path function passing first the URL
itself (accounts/logout); we pass the function logout that we imported from the Django
built-in authentication views, and, as an option, we set next_page to /. This means that
when the user logs out, we redirect the user to the application's root page. Lastly, we also
name the URL as logout.
Great. Now it is time to add the templates. The first template that we are going to add is the
login template. Create a file named login.html at gamestore/templates/ with the
following contents:
{% extends 'base.html' %}
{% block 'content' %}
<div>
<form action="." method="post" class="form-signin">
{% csrf_token %}
<h2 class="form-signin-heading">Login</h2>
<label for="inputUsername" class="sr-only">User name</label>
[ 295 ]
Online Video Game Store with Django Chapter 7
{{form.username}}
<label for="inputPassword" class="sr-only">Password</label>
{{form.password}}
<input class="btn btn-lg btn-primary btn-block"
type="Submit" value="Login">
</form>
<div class='signin-errors-container'>
{% if form.non_field_errors %}
<ul class='form-errors'>
{% for error in form.non_field_errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
</div>
</div>
{% endblock %}
In this template, we also extend the base template, and we add the content of the login
template with the content block that has been defined in the base template.
First, we create a form tag and set the method to POST. Then, we add the csrf_token tag.
The reason we add this tag is to prevent cross-site request attacks, where a malicious site
performs a request to our site on behalf of the current logged in user.
If you want to know more about this type of attack, you can visit the site
at
(CSRF).
After the Cross-Site Request Forgery tag, we add the two fields we need: username and
[ 296 ]
Online Video Game Store with Django Chapter 7
This is where we are going to display possible authentication errors. The forms object has a
property called non_field_error, which contains errors that are not related to field
validation. For example, if your user types the wrong username or password, then the error
will be added the to non_field_error list.
We create a ul element (unordered list) and loop through the non_field_errors list
adding li elements (list items) with the error text.
We have now the login in place, and we need to just include it to the page—more
specifically, to the base.html template. But, first, we need to create a little partial template
that will display the login and logout links on the page. Go ahead and add a file called
_loginpartial.html to the gamestore/templates directory that has the following
contents:
{% if user.is_authenticated %}
<form id="logoutForm" action="{% url 'logout' %}" method="post"
class="navbar-right">
{% csrf_token %}
<ul class="nav navbar-nav navbar-right">
<li><span class="navbar-brand">Logged as:
{{ user.username }}</span></li>
<li><a href="javascript:document.getElementById('
logoutForm').submit()">Log off</a></li>
</ul>
</form>
{% else %}
{% endif %}
This partial template will render two different contents depending on whether the user is
authenticated or not. If the user is authenticated, it will render the logout form. Note that
the action of the form makes use of the named URL; we don't set it to /accounts/logout
but to {% url 'logout' %}. Django's URL tag will replace the URL name with the URL.
Again, we need to add the csrf_token tag to prevent Cross-Site Request Forgery attacks,
and, finally, we define an unordered list with two items; the first item will display the text
Logged as: and the user's username, and the second item on the list will show the logout
button.
[ 297 ]
Online Video Game Store with Django Chapter 7
Note that we added an anchor tag inside of the list item element, and that the href
property has some JavaScript code in it. That code is pretty simple; it uses the function
getElementById to get the form and then call the form's submit function to submit to the
server the request to /accounts/logout.
This is just a preference for implementation; you could easily have skipped this JavaScript
code and added a submit button instead. It would have the same effect.
In case the user is not authenticated, we only show the login link. The login link also uses
the URL tag that will replace the name login with the URL.
Great! Let's add the login partial template to the base template. Open the file base.html at
gamestore/templates, and locate the unordered list, shown as follows:
We are going to add the _loginpartial.html template using the include tag:
{% include '_loginpartial.html' %}
The include tag will inject the content of the _loginpartial.html template in this
position in the markup.
The final touch here is to add some styling, so the login page looks nice like the rest of the
application. Open the file site.css in the gamestore/static/styles directory, and
include the following contents:
/* Styling extracted from
*/
.form-signin {
max-width: 330px;
padding: 15px;
margin: 0 auto;
}
.form-signin input[type="email"] {
margin-bottom: -1px;
}
[ 298 ]
Online Video Game Store with Django Chapter 7
.form-signin .form-signin-heading {;
}
padding: 0;
display: flex;
flex-direction: column;
list-style: none;
align-items: center;
color: red;
}
max-width: 350px;
}
[ 299 ]
Online Video Game Store with Django Chapter 7
This will tell Django that, after the login, the user will be redirected to "/".
Now we are ready to test the login and logout functionality, although you probably don't
have any users in the database. However, we created the superuser while we were setting
up our Django project, so go ahead and try logging in with that user. Run the command
runserver to start the Django development server again:
Browse to and note that you now have the login link in the top
right corner of the page:
[ 300 ]
Online Video Game Store with Django Chapter 7
If you click that, you will be redirected to /accounts/login, and the login page template
that we created will be rendered:
[ 301 ]
Online Video Game Store with Django Chapter 7
First, try typing the wrong password or username so we can verify that the error message is
being displayed correctly:
Great! It works!
Now log in with the superuser, and if everything works fine, you should be redirected to
the application root's URL. It says, Logged as with your username, and right after it there is
a logout link. Give it a go, and click on the link Log off:
[ 302 ]
Online Video Game Store with Django Chapter 7
There are some rules that we want to enforce when creating a new account. The rules are:
If any of these rules are not followed, we will not create the user account, and an error
should be returned to the user.
With that said, let's add a small helper function that will verify whether a field has a value
that already exists in the database. Open the file forms.py in gamestore/main. First, we
need to import the User model:
from django.contrib.auth.models import User
if existent_user:
raise forms.ValidationError(error_message)
[ 303 ]
Online Video Game Store with Django Chapter 7
This function gets an error message and keyword arguments that will be used as a criterion
to search for items matching a specific value. We create a variable called existent_user,
and filter the user models passing the criteria. If the value of the variable existent_user is
different to None, it means that we have found a user who matches our criterion. We then
raise a ValidationError exception with the error message that we passed to the function.
Nice. Now we can start adding a form that will contain all the fields that we want the user
to fill out when creating an account. In the same file, forms.py in
the gamestore/main directory, add the following class:
class SignupForm(forms.Form):
username = forms.CharField(
max_length=10,
widget=forms.TextInput({
'class': 'form-control',
'placeholder': 'First name'
})
)
first_name = forms.CharField(
max_length=100,
widget=forms.TextInput({
'class': 'form-control',
'placeholder': 'First name'
})
)
last_name = forms.CharField(
max_length=200,
widget=forms.TextInput({
'class': 'form-control',
'placeholder': 'Last name'
})
)
max_length=200,
widget=forms.TextInput({
'class': 'form-control',
'placeholder': 'Email'
})
)
password = forms.CharField(
min_length=6,
max_length=10,
[ 304 ]
Online Video Game Store with Django Chapter 7
widget=forms.PasswordInput({
'class': 'form-control',
'placeholder': 'Password'
})
)
repeat_password = forms.CharField(
min_length=6,
max_length=10,
widget=forms.PasswordInput({
'class': 'form-control',
'placeholder': 'Repeat password'
})
)
So, we start by creating a class called SignupForm that will inherit from Form, we define a
property for every field that is going to be necessary for creating a new account, and we add
a username, a first and a last name, an email, and then two password fields. Note that in the
password fields we set the min and max length for a password to 6 and 10, respectively.
Continuing in the same class, SignupForm, let's add a method called clean_username:
def clean_username(self):
username = self.cleaned_data['username']
validate_unique_user(
error_message='* Username already in use',
username=username)
return username
The prefix clean in the name of this method will make Django automatically call this
method when parsing the posted data for the field; in this case, it will execute when parsing
the field username.
So, we get the username value, and then call the method validate_unique_user, passing
a default error message and a keyword argument username that will be used as a filter
criterion.
Another field that we need to verify for uniqueness is the email ID, so let's implement the
clean_email method, as follows:
def clean_email(self):
validate_unique_user(
[ 305 ]
Online Video Game Store with Django Chapter 7
return email
It is basically the same as the clean username. First, we get the email from the request and
pass it to the validate_unique_user function. The first argument is the error message,
and the second argument is the email that will be used as the filter criteria.
Another rule that we defined for our create account page is that the password and (repeat)
password fields must match, otherwise an error will be displayed to the user. So let's add
the same and implement the clean method, but this time we want to validate the
repeat_password field and not password. The reason for that is that if we implement a
clean_password function, at that point repeat_password won't be available in the
cleaned_data dictionary yet, because the data is parsed in the same order as they were
defined in the class. So, to ensure that we will have both values we implement
clean_repeat_password:
def clean_repeat_password(self):
password1 = self.cleaned_data['password']
password2 = self.cleaned_data['repeat_password']
if password1 != password2:
raise forms.ValidationError('* Passwords did not match')
return password1
Great. So here we first define two variables; password1, which is the request value for the
password field, and password2, the request value for the field repeat_password. After
that, we just compare if the values are different; if they are, we raise a ValidationError
exception with the error message to inform the user that the password didn't match and the
account will not be created.
[ 306 ]
Online Video Game Store with Django Chapter 7
As we will be receiving data from a POST request, it is a good idea to add Cross-Site
Request Forgery checkings, so we need to import the csrf_protect decorator.
We also import the SignupForm that we just created so we can pass it to the view or use it
to parse the request data. Lastly, we import the User model.
if request.method == 'POST':
form = SignupForm(request.POST)
if form.is_valid():
user = User.objects.create_user(
username=form.cleaned_data['username'],
first_name=form.cleaned_data['first_name'],
last_name=form.cleaned_data['last_name'],
password=form.cleaned_data['password']
)
user.save()
return render(request,
'main/create_account_success.html', {})
else:
form = SignupForm()
return render(request, 'main/signup.html', {'form': form})
We start by decorating the signup function with the csrf_protect decorator. The
function starts by checking whether the request's HTTP method is equal to POST; in that
case, it will create an instance of the SignupForm passing as an argument the POST data.
Then we call the function is_valid() on the form, which will return true if the form is
valid; otherwise it will return false. If the form is valid, we create a new user and call the
save function, and, finally, we render the create_account_success.html.
[ 307 ]
Online Video Game Store with Django Chapter 7
If the request HTTP method is a GET, the only thing we do is create an instance of
a SignupForm without any argument. After that, we call the render function, passing as a
first argument the request object, then the template that we are going to render, and,
finally, the last argument is the instance of the SignupForm.
We are going to create both templates referenced in this function in a short while, but, first,
we need to create a new URL in the url.py file at gamestore/main:
path(r'accounts/signup/', views.signup, name='signup'),
This new URL can be added right at the end of the urlpatterns list.
We also need to create the templates. We start with the signup template; create a file called
{% extends "base.html" %}
{% block "content" %}
<div class="account-details-container">
<h1>Signup</h1>
<form action="{% url 'signup' %}" method="POST">
{% csrf_token %}
{{ form }}
<button class="btn btn-primary">Save</button>
</form>
</div>
{% endblock %}
This template is again very similar to the template that we created before, in that it extends
the base template and injects some data into the base template's content block. We add an
h1 tag with the header text and a form with the action set to {% url 'signup' %}, which
the url tag will change to /accounts/signup, and we set the method to POST.
As is usual in forms, we use the csrf_token tag that will work together with the
@csrf_protect decorator in the signup function in the views file to protect against
Cross-Site Request Forgery.
[ 308 ]
Online Video Game Store with Django Chapter 7
Then we just call {{ form }}, which will render the entire form in this area, and, right
after the fields, we add a button to submit the form.
Lastly, we create a template for showing that the account has been successfully created.
Add a file called create_account_success.html to the
gamestore/main/templates/main directory with the following contents:
{% extends 'base.html' %}
{% block 'content' %}
<div class='create-account-msg-container'>
<div class='circle'>
<i class="fa fa-thumbs-o-up" aria-</i>
</div>
<h3>Your account have been successfully created!</h3>
<a href="{% url 'login' %}">Click here to login</a>
</div>
{% endblock %}
Great! To make it look great, we are going to include some CSS code in the file site.css in
the gamestore/static directory. Add the content shown as follows, at the end of the file:
/* Account created page */
.create-account-msg-container {
display: flex;
flex-direction: column;
align-items: center;
margin-top: 100px;
}
.create-account-msg-container .circle {
width: 200px;
height: 200px;
border: solid 3px;
display: flex;
flex-direction: column;
align-items: center;
padding-top: 30px;
border-radius: 50%;
}
.create-account-msg-container .fa-thumbs-o-up {
font-size: 9em;
}
[ 309 ]
Online Video Game Store with Django Chapter 7
.create-account-msg-container a {
font-size: 1.5em;
}
.account-details-container #id_password,
.account-details-container #id_repeat_password {
width:200px;
}
.account-details-container {
max-width: 400px;
padding: 15px;
margin: 0 auto;
}
.account-details-container .btn.btn-primary {
margin-top:20px;
}
.account-details-container label {
margin-top: 20px;
}
.account-details-container .errorlist {
padding-left: 10px;
display: inline-block;
list-style: none;
color: red;
}
[ 310 ]
Online Video Game Store with Django Chapter 7
That's all for the create a user page; let's give it a go! Start the Django developer server
again, and browse to, where you should
see the create user form, as follows:
[ 311 ]
Online Video Game Store with Django Chapter 7
After you fill up all the fields, you should be redirected to a confirmation page, like this:
Perform some tests yourself! Try adding invalid passwords, just to verify that the
validations we implemented are working properly.
[ 312 ]
Online Video Game Store with Django Chapter 7
The requirements for the game's model that we are going to have on the site is:
With that said, let's start adding our first model class. Open the file models.py in
gamestore/main/, and add the following code:
class GamePlatform(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
Here, we have added the class GamePlatform, and it will represent the gaming platforms
that will be available at the store. The class is super simple; we just create a class inheriting
from the Model class, and we define just one property called name. The name property is
defined as a CharField of a maximum length of 100 characters. Django provides a large
variety of data types; you can see the complete list at
en/2.0/ref/models/fields/.
Then we override the method __str__. This method will dictate how an instance of
GamePlatform will be displayed when being printed out. The reason that I am overriding
this method is that I want to display the name of GamePlatform in the list
of GamePlatform in the Django admin UI.
The second model class that we are going to add here is the Game model. In the same file,
add the following code:
class Game(models.Model):
class Meta:
ordering = ['-promoted', 'name']
name = models.CharField(max_length=100)
[ 313 ]
Online Video Game Store with Django Chapter 7
release_year = models.IntegerField(null=True)
developer = models.CharField(max_length=100)
published_by = models.CharField(max_length=100)
image = models.ImageField(
upload_to='images/',
default='images/placeholder.png',
max_length=100
)
gameplatform = models.ForeignKey(GamePlatform,
null=False,
on_delete=models.CASCADE)
highlighted = models.BooleanField(default=False)
Like the previous model class that we created, the Game class also inherits from Model and
we define all the fields that we need according to the specifications. There are some things
to note here that are new; the property release_year is defined as an integer field, and we
set the property null=True, which means that this field will not be required.
Another property that used a different type is the image property, which is defined as an
ImageField, and that will allow us to provide the application's administrators the
possibility of changing the game's image. This type inherits from FileField, and in the
Django Administration UI the field will be rendered as a file picker. The ImageFile
argument upload_to specifies where the image will be stored, and the default is the
default image that will be rendered if the game does not have an image. The last argument
that we specify here is max_length, which is the image path's maximum length.
Then, we define a ForeignKey. If you don't know what it is, a foreign key is basically a file
that identifies a row in another table. In our case, here we want the game platform to be
associated with multiple games. There are a few keyword arguments that we are passing to
the definition of the primary key; first we pass the foreign key type, the null argument is
set to False, meaning that the field is required, and, lastly we set the deletion rule to
CASCADE, so if the application's admin deletes a gaming platform, that operation will
cascade and delete all the games associated with that specific gaming platform.
The last property that we define is the highlighted property. Do you remember that one
of the requirements was to be able to highlight some products and also have them in a more
visible area so the users can find them easily? This property does just that. It is a property
type Boolean that has the default value set to False.
[ 314 ]
Online Video Game Store with Django Chapter 7
Another detail, that I was saving for last is this: have you noticed that we have a class
named Meta inside the model class? This is the way that we can add meta information
about the model. In this example we are setting a property called ordering with the value
as an array of strings, where each item represents a property of the Game model, so we have
first -highlighted - the dash sign in front of the property name means descending
order—and then we also have the name, which will appear in ascending order.
def __str__(self):
return f'{self.gameplatform.name} - {self.name}'
Here, we have two things. First, we assign an instance of a class called GameManager, which
I will go into in more detail in a short while, and we also define the special method
__str__, which defines that when printing an instance of the Game object, it will display
the gaming platform and a symbol dash, followed by the name of the name itself.
Before the definition of the Gameclass, let's add another class called GameManager:
class GameManager(models.Manager):
def get_highlighted(self):
return self.filter(highlighted=True)
def get_not_highlighted(self):
return self.filter(highlighted=False)
Before we get into the details of this implementation, I just want to say a few words about
Manager objects in Django. The Manager is the interface between the database and the
model classes in Django. By default, every model class has a Manager, and it is accessed
through the property objects, so why define our own manager? The reason that I
implemented a Manager for this models class is that I wanted to leave all the code
concerning database operations within the model, as it makes the code cleaner and more
testable.
So, here I defined another class, GameManager, that inherits from Manager, and so far we
defined three methods—get_highlighted, which get all games that have the highlighted
flag set to True, get_not_highlighted, which gets all games that highlighted flag is set to
False, and get_by_platform, which gets all the games given a gaming platform.
[ 315 ]
Online Video Game Store with Django Chapter 7
About the two first methods in this class: I could have just used the filter function and
passed an argument where highlighted equals True or False, but, as I mentioned
previously, it is much cleaner to have all these methods inside the manager.
Now we are ready to create the database. In the terminal, run the following command:
python manage.py makemigrations
This command will create a migration file with the changes that we just implemented in the
model. When the migrations are created, we can run the command migrate and then apply
the changes to the database:
python manage.py migrate
Great! Next up, we are going to create a model to store the game's prices.
last_updated = models.DateTimeField(auto_now=True)
price_per_unit = models.DecimalField(max_digits=9,
decimal_places=2,
default=0)
game = models.OneToOneField(
Game,
on_delete=models.CASCADE,
primary_key=True)
def __str__(self):
return self.game.name
[ 316 ]
Online Video Game Store with Django Chapter 7
As you can see here, you have two datetime fields. The first one is added_at, and it has a
property auto_now_add equals True. What it does is get Django to automatically add the
current date when we add this price to the table. The last_update field is defined with
another argument, the auto_now equals True; this tells Django to set the current date every
time an update occurs.
Then, we have a field for the price called price_per_unit, which is defined as a
DecimalField with a maximum of 9 digits and 2 decimal places. This field is not required,
and it will always default to 0.
Next, we create a OneToOneField to create a link between the PriceList and the Game
object. We define that when a game is deleted, the related row in the PriceList table will
also be removed, and we define this field as the primary key.
Finally, we override the __str__ method so that it returns the game's name. This will be
helpful when updating prices using the Django admin UI.
Perfect! Now we are ready to start adding the views and the templates to display our games
on the page.
[ 317 ]
Online Video Game Store with Django Chapter 7
1. A section on the top of the page that will display the games that we want to
highlight. It could be a new game that arrived at the store, a very popular game,
or some game that has a good price for the moment.
2. Following the section with the highlighted games, we are going to list all the
other games.
The first template that we are going to add is a partial view that will be used to list games.
This partial view will be shared to all the templates that we want to display a list of games.
This partial view will receive two arguments: gameslist and highlight_games. Let's go
ahead and add a file called games-list.html at gamestore/main/templates/main/
with the following contents:
{% load staticfiles %}
{% load humanize %}
<div class='game-container'>
{% for game in gameslist %}
{% if game.highlighted and highlight_games %}
<div class='item-box highlighted'>
{% else %}
<div class='item-box'>
{% endif %}
<div class='item-image'>
<img src="{% static game.image.url %}"></img>
</div>
<div class='item-info'>
<h3>{{game.name}}</h3>
<p>Release year: {{game.release_year}}</p>
<p>Developer: {{game.developer}}</p>
<p>Publisher: {{game.published_by}}</p>
{% if game.pricelist.price_per_unit %}
<p class='price'>
Price:
${{game.pricelist.price_per_unit|floatformat:2|intcomma}}
</p>
{% else %}
<p class='price'>Price: Not available</p>
{% endif %}
</div>
<a href="/cart/add/{{game.id}}" class="add-to-cart btn
[ 318 ]
Online Video Game Store with Django Chapter 7
btn-primary">
<i class="fa fa-shopping-cart" aria-</i>
Add to cart
</a>
</div>
{% endfor %}
</div>
One thing to note here is that we added at the top of the page {% load humanize %}; this
is a set of template filters that are built into the Django framework, which we are going to
use to format the game price properly. To make use of these filters we need to edit the
settings.py file in the gamestore/gamestore directory and add
django.contrib.humanize to the INSTALLED_APPS setting.
This code will create a container with some boxes containing the game image, details, and
an add-to-cart button, similar to the following:
{% block 'content' %}
{% if highlighted_games_list %}
<div class='panel panel-success'>
<div class='panel-heading'>
<h2 class='panel-title'><i class="fa fa-gamepad"
aria-</i>Highlighted games</h2>
</div>
<div class='panel-body'>
{% include 'main/games-list.html' with
gameslist=highlighted_games_list highlight_games=False%}
[ 319 ]
Online Video Game Store with Django Chapter 7
{% if show_more_link_highlighted %}
<p>
<a href='/games-list/highlighted/'>See more items</a>
</p>
{% endif %}
</div>
</div>
{% endif %}
{% if games_list %}
{% include 'main/games-list.html' with gameslist=games_list
highlight_games=False%}
{% if show_more_link_games %}
<p>
<a href='/games-list/all/'>See all items</a>
</p>
{% endif %}
{% endif %}
{% endblock %}
As you can see, we are including the partial view and passing two parameters: gameslist
and highlight_games. The gameslist is obviously a list of games that we want the
partial view to render, while highlight_games will be used when we want to show the
promoted games with a different color so they can be easily identified. In the index page,
the highlight_games parameter is not used, but when we create a view to list all the
games regardless of the fact that it is promoted or not, it may be interesting to change the
color of the promoted ones.
Below the promoted games section, we have a section with a list of games that are not
promoted, which also makes use of the partial view games-list.html.
[ 320 ]
Online Video Game Store with Django Chapter 7
The last touch on the frontend side is to include the related CSS code, so let's edit the file
site.css at gamestore/static/styles/ and add the following code:
.game-container {
margin-top: 10px;
display:flex;
flex-direction: row;
flex-wrap: wrap;
}
.game-container .item-box {
flex-grow: 0;
align-self: auto;
width:339px;
margin: 0px 10px 20px 10px;
border: 1px solid #aba5a5;
padding: 10px;
background-color: #F0F0F0;
}
.game-container .item-box.highlighted {
background-color:#d7e7f5;
}
[ 321 ]
Online Video Game Store with Django Chapter 7
text-transform: uppercase;
font-size: 0.9em;
}
Now we need to modify the index view, so edit the views.py file at gamestore/main/
and perform these changes in the index function:
def index(request):
max_highlighted_games = 3
max_game_list = 9
highlighted_games_list = Game.objects.get_highlighted()
games_list = Game.objects.get_not_highlighted()
context = {
'highlighted_games_list':
highlighted_games_list[:max_highlighted_games],
'games_list': games_list[:max_game_list],
'show_more_link_games': show_more_link_games,
'show_more_link_promoted': show_more_link_promoted
}
Here, we first define how many items of each category of games we want to show; for
promoted games, it will be three games, and the non-promoted category will show a
maximum of nine games.
Then, we fetch the promoted and non-promoted games, and we create two
variables, show_more_link_promoted and show_more_link_games, which will be set to
True in case there are more games in the database than the maximum number we defined
previously.
[ 322 ]
Online Video Game Store with Django Chapter 7
We create a context variable that will contain all the data that we want to render in the
template, and, lastly, we call the render function and pass the request to the template we
want to render, along with the context.
Now we are ready to see the results on the page, but, first, we need to create some games.
To do that, we first need to register the models in the admin. To do that, edit the admin.py
file and include the following code:
from django.contrib import admin
admin.autodiscover()
admin.site.register(GamePlatform)
admin.site.register(Game)
admin.site.register(PriceList)
Registering the models within the Django admin site will allow us to add, edit, and remove
games, games platforms, and items in the price list. Because we will be adding images to
our games, we need to configure the location where Django should save the images that we
upload through the administration site. So, let's go ahead and open the file settings.py in
the gamestore/gamestore directory, and just below the STATIC_DIRS setting, add this
line:
MEDIA_ROOT = os.path.join(BASE_DIR, 'static'</span>)
[ 323 ]
Online Video Game Store with Django Chapter 7
If you click first in Game platforms, you will see an empty list. Click on the button ADD on
the Game platforms row on the top right-hand side of the page, and the following form will
be displayed:
Just type any name you like, and click on the SAVE button to save your changes.
Before we add the games, we need to find a default image and place it at
gamestore/static/images/. The image should be named placeholder.png.
The layout that we build will work better with images that are of the size
130x180. To make it simpler, when I am creating prototypes, and I don't
want to spend too much time looking for the perfect image, I go to the
site. Here, you can build a placeholder image
of any size you want. To get the correct size for our application you can go
directly to.
[ 324 ]
Online Video Game Store with Django Chapter 7
When you have the default image in place, you can start adding games the same way you
added the game platforms and just repeat the process multiple times to add a few games
that are set as promoted as well.
After adding the games, and going to the site again, you should see the list of games on the
index page, as follows:
On my project, I added four promoted games. Notice that because we only show three
promoted games on the first page, we render the link See more items.
[ 325 ]
Online Video Game Store with Django Chapter 7
Let's create two more URLs in the url.py file of the main app, and let's add these two to
the urlpatterns list:
path(r'games-list/highlighted/', views.show_highlighted_games),
path(r'games-list/all/', views.show_all_games),
Perfect! Now we need to add one template to list all the games. Create a file called
all_games.html at gamestore/main/templates/main with the following contents:
{% extends 'base.html' %}
{% block 'content' %}
<h2>Highlighted games</h2>
<hr/>
{% if games %}
{% include 'main/games-list.html' with gameslist=games
highlight_promoted=False%}
{% else %}
<div class='empty-game-list'>
<h3>There's no promoted games available at the moment</h3>
</div>
{% endif %}
{% endblock %}
[ 326 ]
Online Video Game Store with Django Chapter 7
{% block 'content' %}
<h2>All games</h2>
<hr/>
{% if games %}
{% include 'main/games-list.html' with gameslist=games
highlight_games=True%}
{% else %}
<div class='empty-game-list'>
<h3>There's no promoted games available at the moment</h3>
</div>
{% endif %}
{% endblock %}
There is nothing here that we haven't seen before. This template will receive a list of games,
and it will pass it down to the games-list.html partial view that will do all the work of
rendering the games for us. There is an if statement here that checks if there are games on
the list. If the list is empty, it will display a message that there are no games available at the
moment. Otherwise, it will render the content.
The last thing now is to add the views. Open the views.py file at gamestore/main/, and
add the following two functions:
def show_all_games(request):
games = Game.objects.all()
def show_highlighted_games(request):
games = Game.objects.get_highlighted()
These functions are very similar; one gets a list of all games and the other one gets a list of
only promoted games
[ 327 ]
Online Video Game Store with Django Chapter 7
Let's open the application again. As we have more promoted items in the database, let's
click on the link See more items in the Highlighted games section of the page. You should
land on the following page:
Next up, we are going to add functionality to the buttons so we can add those items to the
cart.
[ 328 ]
Online Video Game Store with Django Chapter 7
Now, there are many ways you can implement a shopping cart on an application, but we
are going to do it by simply saving the cart items on the database instead of doing an
implementation based in the user session.
With that said, open the file models.py in the gamestore/main directory, and let's add
our first class:
class ShoppingCartManager(models.Manager):
The same way we created a custom Manager for the Game object, we are also going to create
a Manager for the ShoppingCart. We are going to add three methods. The first one is
get_by_id, which, as the name says, retrieves a shopping cart, given an ID. The second
method is get_by_user, which receives as a parameter an instance
of django.contrib.auth.models.User, and it will return the cart given a user instance.
The last method is create_cart; this method will be called when the user creates an
account
[ 329 ]
Online Video Game Store with Django Chapter 7
Now that we have the manager with the methods that we need, let's add the
ShoppingCart class:
class ShoppingCart(models.Model):
user = models.ForeignKey(User,
null=False,
on_delete=models.CASCADE)
objects = ShoppingCartManager()
def __str__(self):
return f'{self.user.username}\'s shopping cart'
This class is super simple. As always, we inherit from Model, and we define one foreign key
for the type User. This foreign key is required, and if the user is deleted it will also delete
the shopping cart.
After the foreign key, we assign our custom Manager to the object's property, and we also
implement the special method __str__ so the shopping carts are displayed in a nicer way
in the Django admin UI.
Next, let's add a manager class for the ShoppingCartItem model, as follows:
class ShoppingCartItemManager(models.Manager):
Here, we only define one method, called get_items, which receives a cart object and
returns a list of items for the underlying shopping cart. After the Manager class, we can
create the model:
class ShoppingCartItem(models.Model):
quantity = models.IntegerField(null=False)
price_per_unit = models.DecimalField(max_digits=9,
decimal_places=2,
default=0)
cart = models.ForeignKey(ShoppingCart,
null=False,
on_delete=models.CASCADE)
game = models.ForeignKey(Game,
null=False,
on_delete=models.CASCADE)
objects = ShoppingCartItemManager()
[ 330 ]
Online Video Game Store with Django Chapter 7
We start by defining two properties: quantity, which is an integer value, and the price per
item, which is defined as a decimal value. We have price_per_item in this model as well,
because when a user adds an item to the shopping cart and if the administrator changes the
price for a product, we don't want that change in the price to be reflected on the items
already added to the cart. The price should be the same price as when the user first added
the product to the cart.
In case the user removes the item entirely and re-adds them, the new price should be
reflected. After those two properties, we define two foreign keys, one for the type
ShoppingCart and another one for Game.
Before we try to verify that everything is working, we should create and apply the
migrations. On the terminal, run the following command:
python manage.py makemigrations
As we did before, we need to run the migrate command to apply the migrations to the
database:
python manage.py migrate
[ 331 ]
Online Video Game Store with Django Chapter 7
So, we pass a few arguments to the inlineformset_factory function. First is the parent
model (ShoppingCart), then it's the model (ShoppingCartItems). Because in the
shopping cart we just want to edit the quantities and also remove items from the cart, we
add a tuple containing the fields from the ShoppingCartItem that we want to render on
the page—in this case, the quantity and price_per_unit. The next argument, extra,
specifies whether the form should render any empty extra rows on the form; in our case, we
don't need that, as we don't want to add extra items in the shopping cart to the shopping
cart view.
In the last argument, widgets, we can specify how the fields should be rendered in the
form. The quantity field will be rendered as a text input, and we don't want
price_per_unit to be visible, so we define it as a hidden input so it is sent back to the
server when we submit the form to the server.
Open the views.py file, and let's add a class-based view. First, we need to add some
import statements:
from django.views.generic.edit import UpdateView
from django.http import HttpResponseRedirect
from django.urls import reverse_lazy
from django.db.models import Sum, F, DecimalField
[ 332 ]
Online Video Game Store with Django Chapter 7
items = ShoppingCartItem.objects.get_items(self.object)
context['is_cart_empty'] = (items.count() == 0)
order = items.aggregate(
total_order=Sum(F('price_per_unit') * F('quantity'),
output_field=DecimalField())
)
context['total_order'] = order['total_order']
return context
def get_object(self):
try:
return
ShoppingCart.objects.get_by_user(self.request.user)
except ShoppingCart.DoesNotExist:
new_cart =
ShoppingCart.objects.create_cart(self.request.user)
new_cart.save()
return new_cart
This is slightly different than the view that we created so far, as this is a class-based view
that inherits from an UpdateView. In reality, views in Django are callable objects, and when
using classes instead of functions, we can take advantage of inheritance and mixins. In our
case, we use UpdateView because it is a view to display forms that will edit an existing
object.
This class view starts off by defining a few properties, such as the model, which is the
model that we are going to be editing in the form. The form_class is the form that is going
to be used for editing the data. Lastly, we have the template that will be used to render the
form.
[ 333 ]
Online Video Game Store with Django Chapter 7
We override the get_context_data because we include some extra data in the form
context. So, first, we call the get_context_data on the base class so as to build the context,
then we get the list of items of the current cart so we can determine whether the cart is
empty. We set this value to the context item called is_cart_empty, which can be accessed
from the template.
After that, we want to calculate the total value of the items that are currently in the cart. To
do that, we need to first calculate the total price for each item by doing (price * quantity),
and then sum the results. In Django, it is possible to aggregate the values of a QuerySet; we
have already the QuerySet that contains the list of items in a cart, so all we have to do is to
use the aggregate function. In our case, we are passing two arguments to the aggregate
function. First, we get the sum of the field price_per_unit multiplied by the quantity,
and the results will be stored in a property called total_order. The second argument of
the aggregate function defines the output data type, which we want to be a decimal value.
When we get the results of the aggregation, we create a new item in the context dictionary
called total_order and assign the results to it. Finally, we return the context.
We also override the get_object method. In this method, we try to get the shopping cart
for the requesting user. If the shopping cart does not exist, an exception
ShoppingCart.DoesNotExist will be raised. In that case, we create a shopping cart for
the user and return it.
Lastly, we also implement the form_valid method, which only saves the form and
redirects the user back to the cart page.
Before we add the view, let's go ahead and open the urls.py file in gamestore/main/ and
add the following URL:
path(r'cart/', views.ShoppingCartEditView.as_view(), name='user-
cart'),
[ 334 ]
Online Video Game Store with Django Chapter 7
Here, we define a new URL, 'cart/', and, when accessed, it will execute the class-based
view ShoppingCartEditView. We also define a name for the URL for simplicity.
{% extends 'base.html' %}
{% block 'content' %}
{% load humanize %}
<div class='cart-details'>
<h3>{{ shoppingcart}}</h3>
{% if is_cart_empty %}
{% else %}
{% csrf_token %}
{{ form.management_form }}
[ 335 ]
Online Video Game Store with Django Chapter 7
The template is quite simple; we just loop through the forms and render each one of them.
One thing to note here in that we are loading humanize in the beginning of the template.
humanize is a set of template filters that we can use to format data in the
template.
We use the intcomma filter from humanize to format the sum of all items in the shopping
cart. The intcomma filter will convert an integer or float value to a string and add a comma
every three digits.
You can try it out on the new view. However, the cart will be empty and no data will be
displayed. Next, we are going to add functionality to include items in the cart.
[ 336 ]
Online Video Game Store with Django Chapter 7
The first thing we need to do is create a new URL. Open the file url.py in the directory
gamestore/main/, and add this URL to the urlpatterns list:
path(r'cart/add/<int:game_id>/', views.add_to_cart),
Perfect. In this URL, we can pass the game ID, and it will execute a view called
add_to_cart. Let's add this new view. Open the file views.py in gamestore/main. First,
we add import statements, shown as follows:
from decimal import Decimal
from django.shortcuts import get_object_or_404
from django.contrib import messages
from django.contrib.auth.decorators import login_required
Now, we need a way to know if a specific item has been already added to the cart, so we go
over to the models.py in gametore/main and add a new method to the
ShoppingCartItemManager class:
existing_item =
ShoppingCartItem.objects.get_existing_item(cart,
game)
if existing_item is None:
[ 337 ]
Online Video Game Store with Django Chapter 7
price = (Decimal(0)
if not hasattr(game, 'pricelist')
else game.pricelist.price_per_unit)
new_item = ShoppingCartItem(
game=game,
quantity=1,
price_per_unit=price,
cart=cart
)
new_item.save()
else:
existing_item.quantity = F('quantity') + 1
existing_item.save()
messages.add_message(
request,
messages.INFO,
f'The game {game.name} has been added to your cart.')
return HttpResponseRedirect(reverse_lazy('user-cart'))
This function gets a request and the game ID, and we start by getting the game and the
current user's shopping cart. We then pass the cart and the game to the get_existing
function that we just created. If we don't have that specific item in the shopping cart, we
create a new ShoppingCartItem; otherwise, we just update the quantity and save.
We also add a message to inform the user that the item has been added to the shopping
cart.
As a final touch, let's open the site.css file in the gamestore/static/styles and add
the styling to our shopping cart's view:
.cart-details h3 {
margin-bottom: 40px;
}
[ 338 ]
Online Video Game Store with Django Chapter 7
.has-errors input:focus {
border-color: red;
box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px
rgba(255,0,0,1);
webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px
rgba(255,0,0,1);
}
.has-errors input {
color: red;
border-color: red;
}
.cart-details .footer {
display:flex;
justify-content: space-between;
}
Before we try this out, we need to add the link to the cart view on the top menu. Open the
file base.html in gamestore/templates, locate where we do the include of the
_loginpartial.html file, and include the following code right before it:
{% if user.is_authenticated%}
<li>
<a href="/cart/">
<i class="fa fa-shopping-cart"
aria-</i> CART
</a>
</li>
{% endif %}
[ 339 ]
Online Video Game Store with Django Chapter 7
Now we should be ready to test it out. Go to the first page, and try adding some games to
the cart. You should be redirected to the cart page:
Summary
It has been a long journey, and we have covered a lot of ground in this chapter. In this
chapter, you have seen how easy it is to build an application with Django. The framework
really honors the phrase Framework for perfectionists with deadlines.
You have learned how to create a new Django project and applications, with a short
walkthrough of the boilerplate code that Django generates for us when we start a new
project. We learned how to create models and use migrations to apply changes to the
database.
[ 340 ]
Online Video Game Store with Django Chapter 7
Django forms was also a subject that we covered a lot in this chapter, and you should be
able to create complex forms for your projects.
As a bonus, we learned how to install and use NodeJS Version Manager (NVM) to install
Node.js, so as to install project dependencies using the npm.
In Chapter 5, Building a Web Messenger with Microservices, we are going to extend this
application and create services that will handle the store inventory.
[ 341 ]
Order Microservice
8
In this chapter, we are going to extend the web application that we implemented in Chapter
7, Online Video Game Store with Django. I don't know if you noticed, but there are a few
important things missing in that project. The first is the ability to submit an order. As of
right now, users can browse products and add items to the shopping cart; however, there's
no way of sending the order and completing the purchase.
Another item that is missing is a page where the users of our application will be able to see
all the orders that have been sent, as well as a history of their orders.
With that said, we are going to create a microservice called order, which will do everything
related to orders made on the site. It will receive orders, update orders, and so on.
If you don't know how to use pipenv, in the section Setting up the
environment in Chapter 4, Exchange Rates and the Currency Conversion
Tool, there is a very good introduction about how to get started with
pipenv.
With the virtual environment created, we need to install the project dependencies. For this
project, we are going to install Django and the Django REST Framework:
pipenv install django djangorestframework requests python-dateutil
The reason that we are using Django and the Django REST Framework instead of a simpler
framework like Flask is that the main idea of this project is to provide a separation of
concerns, creating a microservice that will handle orders made in the online game store that
we developed in the previous chapter. We don't want to only provide APIs to be consumed
by the web application. It would be great to have a simple website so that we can list the
orders, see the details of each order, and also perform updates such as changing the order's
status.
As you saw in the previous chapter, Django already has a very powerful and flexible admin
UI that we can customize to provide that kind of functionality to our users--all without
spending too much time developing a web application.
verify_ssl = true
name = "pypi"
url = ""
[packages]
django = "*"
[ 343 ]
Order Microservice Chapter 8
djangorestframework = "*"
[dev-packages]
[requires]
python_version = "3.6"
Perfect! Now, we can start a new Django project. We are going to create the project using
the django-admin tool. Let's go ahead and create a project called order:
django-admin startproject order
With the project created, we are going to create a Django app. For this project, we are going
to create just one app that is going to be called main. First, we change the directory to the
service directory:
cd order
After creating the Django app, your project structure should look similar to the following
structure:
.
├── main
│ ├── admin.py
│ ├── apps.py
│ ├── __init__.py
│ ├── migrations
│ │ └── __init__.py
│ ├── models.py
│ ├── tests.py
│ └── views.py
├── manage.py
└── order
├── __init__.py
├── settings.py
├── urls.py
└── wsgi.py
Next up, we are going to start creating the model for our service.
[ 344 ]
Order Microservice Chapter 8
We will create a class called OrderCustomer that inherits from Model, and define three
properties; the customer_id, which will correspond to the customer ID in the online game
store, the name of the customer, and lastly, the email.
Then, we will create the model that will store information about the order:
class Order(models.Model):
ORDER_STATUS = (
(1, 'Received'),
(2, 'Processing'),
(3, 'Payment complete'),
(4, 'Shipping'),
(5, 'Completed'),
(6, 'Cancelled'),
)
order_customer = models.ForeignKey(
OrderCustomer,
on_delete=models.CASCADE
)
total = models.DecimalField(
max_digits=9,
decimal_places=2,
default=0
)
created_at = models.DateTimeField(auto_now_add=True)
last_updated = models.DateTimeField(auto_now=True)
status = models.IntegerField(choices=ORDER_STATUS, default='1')
[ 345 ]
Order Microservice Chapter 8
The Order class inherits from Model, and we start this class by adding a tuple containing
the status that the orders in our application can have. We also define a foreign key,
order_customer, which will create the relationship between the OrderCustomer and
Order. It is then time to define other fields, starting with total, which is the total purchase
value of that order. We then have two datetime fields; created_at, which is the date that
the order has been submitted by the customer, and last_update, which is a field that is
going to be used when we want to know when the order has a status update.
The last model that we are going to create is OrderItems. This will hold items belonging to
an order. We will define it like this:
class OrderItems(models.Model):
class Meta:
verbose_name_plural = 'Order items'
product_id = models.IntegerField()
name = models.CharField(max_length=200)
quantity = models.IntegerField()
price_per_unit = models.DecimalField(
max_digits=9,
decimal_places=2,
default=0
)
order = models.ForeignKey(
Order, on_delete=models.CASCADE, related_name='items')
Here, we also define a Meta class so we can set some metadata to the model. In this case, we
are setting the verbose_name_plural to Order items so that it looks correctly spelled in
the Django admin UI. Then, we define product_id, name, quantity, and
price_per_unit, which refer to the Game model in the online video game store.
Lastly, we have the item quantity and the foreign key Order.
[ 346 ]
Order Microservice Chapter 8
The only thing left is to create and apply the database migrations. First, we run the
command makemigrations:
python manage.py makemigrations
[ 347 ]
Order Microservice Chapter 8
In our case, the only model we are interested in creating is a custom model manager called
Order, but before we start implementing the order manager, we need to create a few helper
classes. The first class that we need to create is a class that will define custom exceptions
that may occur when performing queries on our database. Of course, we could use the
exceptions that are already defined in the standard library, but it is always a good practice
to create exceptions that make sense within the context of your application.
The three exceptions that we are going to create are InvalidArgumentError,
OrderAlreadyCompletedError, and OrderCancellationError.
The exception InvalidArgumentError will be raised when invalid arguments are passed
to the functions that we are going to define in the manager, so let's go ahead and create a
file called exceptions.py in the main app directory with the following contents:
class InvalidArgumentError(Exception):
def __init__(self, argument_name):
message = f'The argument {argument_name} is invalid'
super().__init__(message)
Here, we define a class called InvalidArgumentError that inherits from Exception, and
the only thing we do in it is override the constructor and receive an argument called
argument_name. With this argument, we can specify what caused the exception to be
raised.
We will also customize the exception message, and lastly, we will call the constructor on the
superclass.
We are also going to create an exception that will be raised when we try to cancel an order
that has the status as canceled, and also when we try to set the status of an order to
completed when the order is already completed:
class OrderAlreadyCompletedError(Exception):
def __init__(self, order):
message = f'The order with ID: {order.id} is already
completed.'
super().__init__(message)
class OrderAlreadyCancelledError(Exception):
def __init__(self, order):
message = f'The order with ID: {order.id} is already
cancelled.'
super().__init__(message)
[ 348 ]
Order Microservice Chapter 8
class OrderNotFoundError(Exception):
pass
These two classes don't do too much. They only inherit from Exception. We will configure
and customize a message for each exception and pass it over to the super class initializer.
The value of adding custom exception classes is that it will improve the readability and
maintainability of our applications.
Great! There is only one more thing we need to add before starting with the manager. We
will create functions in the model manager that will return data filtered by status. As you
can see, in the definition of the Order model, we defined the status like this:
ORDER_STATUS = (
(1, 'Received'),
(2, 'Processing'),
(3, 'Payment complete'),
(4, 'Shipping'),
(5, 'Completed'),
(6, 'Cancelled'),
)
Which means that if we want to get all the orders with a status of Completed, we would
need to write something similar to the following line:
Order.objects.filter(status=5)
There's only one problem with this code, can you guess what? If you guessed that
magic number, 5, you are absolutely right! Imagine how frustrated our colleagues would be
if they needed to maintain this code and see only the number 5 there and have no idea what
5 actually means. Because of this, we are going to create an enumeration that we can use to
express the different statuses. Let's create a file called status.py in the main app directory
and add the following enumeration:
from enum import Enum, auto
class Status(Enum):
Received = auto()
Processing = auto()
Payment_Complete = auto()
[ 349 ]
Order Microservice Chapter 8
Shipping = auto()
Completed = auto()
Cancelled = auto()
So, now, when we need to get all the orders with a Completed status, we can do:
Order.objects.filter(Status.Received.value)
Much better!
Now, let's create the model manager for it. Create a file called managers.py in the mail app
directory, and we can start by adding a few imports:
from datetime import datetime
from django.db.models import Manager, Q
Then, we define the OrderManager class and the first method called set_status:
class OrderManager(Manager):
if order.status is Status.Completed.value:
raise OrderAlreadyCompletedError()
order.status = status.value
order.save()
This method takes two parameters, order, and status. The order is an object of type Order
and the status is an item of the Status enumeration that we created previously.
[ 350 ]
Order Microservice Chapter 8
We start this method by validating the arguments and raising the corresponding exception.
First, we validate if the fields have a value and are the correct type. If the validation fails, it
will raise an InvalidArgumentError. Then, we check if the order that we are trying to set
the status for is already completed; in this case, we cannot change it anymore, so we raise an
OrderAlreadyCompletedError. If all the arguments are valid, we set the order's status
and save.
In our application, we want to be able to cancel an order that is still not being processed; in
other words, we will allow orders to be canceled only if the status is Received. Here is
what the cancel_order method should look like:
def cancel_order(self, order):
if order is None or not isinstance(order, models.Order):
raise InvalidArgumentError('order')
if order.status != Status.Received.value:
raise OrderCancellationError()
self.set_status(order, Status.Cancelled)
This method only gets the order argument, and first, we need to check if the order object is
valid and raise an InvalidArgumentError if it is invalid. Then, we check if the order's
status is not Received. In this case, we raise an OrderCancellationError exception.
Otherwise, we go ahead and call the set_status method, passing Status.Cancelled as
an argument.
In case the customer_id is invalid, for example, if we pass a string instead of an integer, a
ValueError exception will be raised. We catch this exception and raise our custom
exception InvalidArgumentError.
[ 351 ]
Order Microservice Chapter 8
The financial department of our online video game store had the requirement of getting a
list of all complete and incomplete orders for a specific user, so let's go ahead and add some
methods for it:
def get_customer_incomplete_orders(self, customer_id):
try:
return self.filter(
~Q(status=Status.Completed.value),
order_customer_id=customer_id).order_by('status')
except ValueError:
raise InvalidArgumentError('customer_id')
The Q() object allows us to write much more complex queries making use of | (OR) and &
(AND) operators.
[ 352 ]
Order Microservice Chapter 8
Next, every department that is responsible for taking care of the order life cycle wants an
easy way to get orders at a certain stage; for example, the workers responsible for shipping
the games want to get a list of all orders that have a status equal to Payment Complete so
they can ship these orders to the customers. So, we need to add a method that will do just
that:
def get_orders_by_status(self, status):
if status is None or not isinstance(status, Status):
raise InvalidArgumentError('status')
return self.filter(status=status.value)
This is a very simple method; here, we get the status as an argument. We check if the status
is valid; if not, we raise an InvalidArgumentError. Otherwise, we continue and filter the
orders by status.
Another requirement from our finance department is to get a list of orders in a given date
range:
def get_orders_by_period(self, start_date, end_date):
if start_date is None or not isinstance(start_date, datetime):
raise InvalidArgumentError('start_date')
Here, we get two parameters, start_date and end_date. As with all the other methods,
we start by checking if these arguments are valid; in this case, the arguments cannot be
None and have to be an instance of the Datetime object. If any of the fields are invalid, an
InvalidArgumentError will be raised. When the arguments are valid, we filter the orders
using the created_at field and we also use this special syntax, created_at__range,
which means that we are going to pass a date range and it will be used as a filter. Here, we
are passing start_date and end_date.
There is just one method that might be interesting to implement and it can add value to the
administrators of our application. The idea here is to add a method that, when called,
automatically changes the order to the next status:
def set_next_status(self, order):
if order is None or not isinstance(order, models.Order):
raise InvalidArgumentError('order')
[ 353 ]
Order Microservice Chapter 8
if order.status is Status.Completed.value:
raise OrderAlreadyCompletedError()
order.status += 1
order.save()
This method gets just one argument, the order. We check if the order is valid, and if it is
invalid, we raise an InvalidArgumentError. We also want to make sure that once the
order gets to the Completed status, it can no longer be changed. So, we check if the order is
of the status Completed, then we raise an OrderAlreadyCompleted exception. Lastly, we
add 1 to the current status and save the object.
Now, we can change our Order model so that it makes use of the OrderManager that we
just created. Open the model.py file in the main app directory, and at the end of the Order
class, add the following line:
objects = OrderManager()
So, now we can access all the methods that we defined in the OrderManager through
Order.objects.
Next up, we are going to add tests to our model manager methods.
Learning to test
So far in this book, we haven't covered how to create tests. Now is a good time to do that, so
we are going to create tests for the methods that we created in the model manager.
Why do we need tests? The short answer to this question is that tests will allow us to know
that the methods or functions are doing the right thing. The other reason (and one of the
most important, in my opinion) is that tests give us more confidence when it comes to
performing changes in the code.
Django has great tools out of the box for creating unit and integration tests, and combined
with frameworks like Selenium, it is possible to basically test all of our application.
With that said, let's create our first tests. Django creates a file called test.py in the app
directory when creating a new Django app. You can write your tests in there, or if you
prefer to keep the project more organized by separating the tests into multiple files, you can
remove that file and create a directory called tests and place all your tests files in there.
Since we are only going to create tests for the Order model manager, we are going to keep
all the tests in the tests.py file that Django created for us.
[ 354 ]
Order Microservice Chapter 8
Great! We start by importing the relative delta function so we can easily perform date
operations, like adding days or months to a date. This will be very helpful when testing the
methods that get orders for a certain period of time.
Now, we import some Django-related things. First is the TestCase class, which is a
subclass of unittest.TestCase. Since we are going to write tests that will interact with
the database, it is a good idea to use django.tests.TestCase instead of
unittest.TestCase. Django's TestCase implementation will make sure that your test is
running within a transaction to provide isolation. This way, we will not have unpredictable
results when running the test because of data created by another test in the test suite.
We also import some of the model classes that we are going to use in our test, the Order,
the OrderCustomer models, and also the Status class when we are going to test the method
that changes order statuses.
When writing tests for your application, we don't want to only test the good scenarios, we
also want to test when things go wrong, and bad arguments are passed to the functions and
methods that are being tested. For this reason, we are importing our custom error classes, so
we can make sure that the right exception is being raised in the right situation.
Now that we have the imports in place, it is time to create the class and the method that will
set up data for our tests:
class OrderModelTestCase(TestCase):
@classmethod
def setUpTestData(cls):
cls.customer_001 = OrderCustomer.objects.create(
customer_id=1,
[ 355 ]
Order Microservice Chapter 8
Order.objects.create(order_customer=cls.customer_001)
Order.objects.create(order_customer=cls.customer_001,
status=Status.Completed.value)
cls.customer_002 = OrderCustomer.objects.create(
customer_id=1,
)
Order.objects.create(order_customer=cls.customer_002)
Here, we create two users; the first one has two orders and one of the orders is set to
Completed. The second user has only one order.
The first test is quite straightforward; we only want to test if we can cancel an
order, setting its status to Cancelled
The second test is that it shouldn't be possible to cancel orders that have not been
received; in other words, only the orders that have the current status set to
Received can be canceled
We need to test if the correct exception is raised in case we pass an invalid
argument to the cancel_order method
self.assertIsNotNone(order)
self.assertEqual(Status.Received.value, order.status)
Order.objects.cancel_order(order)
[ 356 ]
Order Microservice Chapter 8
self.assertEqual(Status.Cancelled.value, order.status)
def test_cancel_completed_order(self):
order = Order.objects.get(pk=2)
self.assertIsNotNone(order)
self.assertEqual(Status.Completed.value, order.status)
with self.assertRaises(OrderCancellationError):
Order.objects.cancel_order(order)
def test_cancel_order_with_invalid_argument(self):
with self.assertRaises(InvalidArgumentError):
Order.objects.cancel_order({'id': 1})
The first test, test_cancel_order, starts off by getting an order with ID 1. We assert that
the returned value is not None using the assertIsNotNone function, and we also use the
function assertEqual to make sure that the order has the status 'Received'.
Then, we call the cancel_order method from the order model manager passing the order,
and lastly, we use the assertEqual function again to verify that the order's status is in fact
changed to Cancelled.
[ 357 ]
Order Microservice Chapter 8
If the correct exception is raised when passing an invalid argument to the method
def test_get_all_orders_by_customer(self):
orders =
Order.objects.get_all_orders_by_customer(customer_id=1)
self.assertEqual(2, len(orders),
msg='It should have returned 2 orders.')
def test_get_all_order_by_customer_with_invalid_id(self):
with self.assertRaises(InvalidArgumentError):
Order.objects.get_all_orders_by_customer('o')
The tests for the get_all_orders_by_customer method are quite simple. In the first test,
we fetch the orders for the customer with ID 1 and test if the returned number of items is
equal to 2.
The method returns the correct number of items and also if the item returned
does not have a status equal to Completed
We are going to test if an exception is raised when an invalid value is passed as
an argument to this method
def test_get_customer_incomplete_orders(self):
orders =
Order.objects.get_customer_incomplete_orders(customer_id=1)
self.assertEqual(1, len(orders))
self.assertEqual(Status.Received.value, orders[0].status)
def test_get_customer_incomplete_orders_with_invalid_id(self):
with self.assertRaises(InvalidArgumentError):
Order.objects.get_customer_incomplete_orders('o')
[ 358 ]
Order Microservice Chapter 8
The other test, exactly like the previous one testing that tested exceptions, just calls the
method and asserts that the correct exception has been raised.
self.assertEqual(1, len(orders))
self.assertEqual(Status.Completed.value, orders[0].status)
def test_get_customer_completed_orders_with_invalid_id(self):
with self.assertRaises(InvalidArgumentError):
Order.objects.get_customer_completed_orders('o')
If the method returns the correct number of orders given a specific status
That the correct exception is raised when passing an invalid argument to the
method
def test_get_order_by_status(self):
order = Order.objects.get_orders_by_status(Status.Received)
[ 359 ]
Order Microservice Chapter 8
self.assertEqual(2, len(order),
msg=('There should be only 2 orders '
'with status=Received.'))
self.assertEqual('customer_001@test.com',
order[0].order_customer.email)
def test_get_order_by_status_with_invalid_status(self):
with self.assertRaises(InvalidArgumentError):
Order.objects.get_orders_by_status(1)
Call the method, passing as arguments, and orders created within that period
should be returned
Call the method, passing as arguments valid dates where we know that no orders
were created, which should return an empty result
Test if an exception is raised when calling the method, passing an invalid start
date
Test if an exception is raised when calling the method, passing an invalid end
date
def test_get_orders_by_period(self):
self.assertEqual(3, len(orders))
[ 360 ]
Order Microservice Chapter 8
self.assertEqual(0, len(orders))
def test_get_orders_by_period_with_invalid_start_date(self):
start_date = timezone.now()
with self.assertRaises(InvalidArgumentError):
Order.objects.get_orders_by_period(start_date, None)
def test_get_orders_by_period_with_invalid_end_date(self):
end_date = timezone.now()
with self.assertRaises(InvalidArgumentError):
Order.objects.get_orders_by_period(None, end_date)
We start this method by creating date_from, which is the current date minus one day.
Here, we use the relativedelta method of the python-dateutil package to perform
date operations. Then, we define date_to, which is the current date plus two days.
Now that we have our period, we can pass these values as arguments to the
get_orders_by_period method. In our case, we set up three orders, all created with the
current date, so this method call should return exactly three orders.
Then, we define a different period where we know that there won't be any orders. The
date_from function is defined with the current date plus three days, so date_from is the
current date plus 1 month.
Calling the method again passing the new values of date_from and date_to should not
return any orders.
The last two tests for get_orders_by_period are the same as the exception tests that we
implemented previously.
[ 361 ]
Order Microservice Chapter 8
When we save an order in the database and set its status to, for example,
Status.Processing, the value of the status field in the database will be 2.
The function simply adds 1 to the current order's status, so it goes to the next status item
unless the status is Completed; that's the last status of the order's lifecycle.
Now that we have refreshed our memories about how this method works, it is time to
create the tests for it, and we will have to perform the following tests:
That the order gets the next status when set_next_status is called
Test if an exception will be raised when calling set_next_status and passing
as an argument an order with the status Completed
Test if an exception is raised when passing an invalid order as an argument
def test_set_next_status(self):
order = Order.objects.get(pk=1)
self.assertEqual(Status.Received.value, order.status,
msg='The status should have been
Status.Received.')
Order.objects.set_next_status(order)
self.assertEqual(Status.Processing.value, order.status,
msg='The status should have been
Status.Processing.')
def test_set_next_status_on_completed_order(self):
order = Order.objects.get(pk=2)
with self.assertRaises(OrderAlreadyCompletedError):
Order.objects.set_next_status(order)
def test_set_next_status_on_invalid_order(self):
with self.assertRaises(InvalidArgumentError):
Order.objects.set_next_status({'order': 1})
[ 362 ]
Order Microservice Chapter 8
The first test, test_set_next_status, starts by getting the order with an ID equal to 1.
Then, it asserts that the order object is not equal to none, and we also assert that the value of
the order's status is Received. Then, we call the set_next_status method, passing the
order as an argument. Right after that, we assert again to make sure that the status has
changed. The test will pass if the order's status is equals to 2, which is Processing in the
Status enumeration.
The other two tests are very similar to the order test where we assert exceptions, but it is
worth mentioning that the test test_set_next_status_on_completed_order asserts
that if we try calling the set_next_status on an order that has a status equal to
Status.Completed, then an exception of type OrderAlreadyCompletedError will be
raised.
Set a status and verify that the order's status has really changed
Set the status in an order that is already completed; it should raise an exception of
type OrderAlreadyCompletedError
Set the status in an order that is already canceled; it should raise an exception of
type OrderAlreadyCancelledError
Call the set_status method using an invalid order; it should raise an exception
of type InvalidArgumentError
Call the set_status method using an invalid status; it should raise an exception
of type InvalidArgumentError
def test_set_status(self):
order = Order.objects.get(pk=1)
Order.objects.set_status(order, Status.Processing)
self.assertEqual(Status.Processing.value, order.status)
def test_set_status_on_completed_order(self):
order = Order.objects.get(pk=2)
with self.assertRaises(OrderAlreadyCompletedError):
Order.objects.set_status(order, Status.Processing)
[ 363 ]
Order Microservice Chapter 8
def test_set_status_on_cancelled_order(self):
order = Order.objects.get(pk=1)
Order.objects.cancel_order(order)
with self.assertRaises(OrderAlreadyCancelledError):
Order.objects.set_status(order, Status.Processing)
def test_set_status_with_invalid_order(self):
with self.assertRaises(InvalidArgumentError):
Order.objects.set_status(None, Status.Processing)
def test_set_status_with_invalid_status(self):
order = Order.objects.get(pk=1)
with self.assertRaises(InvalidArgumentError):
Order.objects.set_status(order, {'status': 1})
We are not going to go through all the tests where we are testing exceptions, because they
are similar to the tests that we implemented previously, but it is worth going through the
first test. On the test test_set_status, it will get the order with an ID equal to 1, which as
we defined in the setUpTestData, has a status equal to Status.Received. We call the
set_status method passing the order and the new status as arguments, in this case,
Status.Processing. After setting the new status, we just call assertEquals to make
sure that the order's status in fact changed to Status.Processing.
For some of these endpoints, we are going to use the Django REST Framework. The
advantage of using the Django REST Framework is that the framework includes a lot of out
of the box features. It has different authentication methods, a really robust serialization of
objects, and my favorite is that it will give you a web interface where you can browse the
API, which also contains a large collection of base classes and mixins when you need to
create class-based views.
[ 364 ]
Order Microservice Chapter 8
The first thing that we need to do at this point is to create serializer classes for the entities of
our model, the Order, OrderCustomer, and OrderItem.
Go ahead and create a file called serializers.py in the main app directory, and let's start
by adding a few import statements:
import functools
We start by importing the functools module from the standard library; then, we import
the serializer from the rest_framework module. We are going to use it to create our model
serializers. Lastly, we will import the models that we are going to use to create the
serializers, the Order, OrderItems, and OrderCustomer.
[ 365 ]
Order Microservice Chapter 8
The last serializer that we are going to create is the OrderSerializer, so let's start by
defining a class called OrderSerializer:
class OrderSerializer(serializers.ModelSerializer):
items = OrderItemSerializer(many=True)
order_customer = OrderCustomerSerializer()
status = serializers.SerializerMethodField()
The status field is a little bit special; if you remember the status field in the Order model, it
is defined as a ChoiceField. When we save an order in the database, that field will store
the value 1 if the order has a status of Received, 2 if the status is Processing, and so on.
When the consumers of our API call the endpoint to get orders, they will be interested in
the name of the status and not the number.
So, the solution to this problem is to define the field as SerializeMethodField, and then
we are going to create a function called get_status, which will return the display name of
the order's status. We are going to see what the implementation of the get_status method
looks like in a short while.
Then, we define a Meta class, so that we can add some metadata information to the
serializer class:
class Meta:
depth = 1
model = Order
fields = ('items', 'total', 'order_customer',
'created_at', 'id', 'status', )
[ 366 ]
Order Microservice Chapter 8
The first property, depth, specifies the depth of the relationships that should be traversed
before the serialization. In this case, it is set to 1, because when fetching an order object, we
also want to have information about the customers and items. Like the other serializers, we
set the model to Order and the fields property specifies which fields will be serialized and
deserialized.
This is the method that will get the display value for the ChoiceField status. This will
override the default behavior and return the result of the get_status_display() function
instead.
The _created_order_item method is just a helper method which we are going to use to
create and prepare the order item's objects prior to performing a bulk insert:
def _create_order_item(self, item, order):
item['order'] = order
return OrderItems(**item)
Here, we are going to get two arguments. The first argument will be a dictionary with the
data about the OrderItem and an order argument with an object of type Order. First, we
update the dictionary passed in the first argument, adding the order object, then we call
the OrderItem constructor, passing the items as an argument in the item dictionary.
I am going to show you what that's used for a short while. Now that we have got to the core
of this serializer, we are going to implement the create method, which will be a method
that will be called automatically every time we call the serializer's save method:
def create(self, validated_data):
validated_customer = validated_data.pop('order_customer')
validated_items = validated_data.pop('items')
customer = OrderCustomer.objects.create(**validated_customer)
validated_data['order_customer'] = customer
order = Order.objects.create(**validated_data)
mapped_items = map(
functools.partial(
self._create_order_item, order=order), validated_items
)
[ 367 ]
Order Microservice Chapter 8
OrderItems.objects.bulk_create(mapped_items)
return order
So, the create method will be called automatically when calling the save method, and it will
get the validated_data as an argument. The validated_date is a validated, de-
serialized order data. It will look similar to the following data:
{
"items": [
{
"name": "Prod 001",
"price_per_unit": 10,
"product_id": 1,
"quantity": 2
},
{
"name": "Prod 002",
"price_per_unit": 12,
"product_id": 2,
"quantity": 2
}
],
"order_customer": {
"customer_id": 14,
"name": "Test User"
},
"order_id": 1,
"status": 4,
"total": "190.00"
}
As you can see, in this JSON, we are passing all the information at once. Here, we have the
order, the items property, which is a list of order items, and the order_customer, which
contains information about the customer who submitted the order.
Since we have to perform the creation of these objects individually, we first pop the
order_customer and the items so we have three different objects. The
first, validated_customer, will only contain data related to the person who made the
order. The validated_items object will only contain data related to each item of the
order, and finally, the validated_data object will only contain data related to the order
itself.
[ 368 ]
Order Microservice Chapter 8
After splitting the data, we can now start adding the objects. We start by creating an
OrderCustomer:
customer = OrderCustomer.objects.create(**validated_customer)
Then, we can create the order. The Order has a foreign key field called order_customer,
which is the customer that is connected to that particular Order. What we need to do is
create a new item in the validated_data dictionary with a key called order_customer,
and set its value to the customer that we just created:
validated_data['order_customer'] = customer
order = Order.objects.create(**validated_data)
Lastly, we are going to add OrderItems. Now, to add the order items, we need to do a few
things. The validated_items variable is a list of items that belong to the underlying
order, and we need to first set the order to each one of these items, and create an
OrderItem object for each one of the items on the list.
There are different ways of performing this operation. You could do it in two parts; for
example, first loop through the item's list and set the order property, then loop through the
list again and create the OrderItem objects. However, that wouldn't be so elegant, would
it?
A better approach here is to take advantage of the fact that Python is a multi-paradigm
programming language, and we can solve this problem in a more functional way:
mapped_items = map(
functools.partial(
self._create_order_item, order=order), validated_items
)
OrderItems.objects.bulk_create(mapped_items)
Here, we make use of one of the built-in function maps. The map function will apply a
function that I specify as the first argument to an iterable that is passed as the second
argument, which then returns an iterable with the results.
The function that we are going to pass as the first argument to map is a function
called partial, from the functools module. The partial function is a high-order
function, meaning that it will return another function (the one in the first argument) and
will add the argument and keyword arguments to its signature. In the preceding code, it
will return self._create_order_item, and the first argument will be an item of the
iterable validated_items. The second argument is the order that we created previously.
[ 369 ]
Order Microservice Chapter 8
After that, the value of mapped_items should contain a list of OrderItem objects, and the
only thing left to do is call bulk_create, which will insert all the items on the list for us.
Here, we import some things from the Django REST Framework, the main one being the
generic, which contains definitions for the generic view classes that we are going to use to
create our own custom views. The status contains all the HTTP status codes, which are very
useful when sending the response back to the client. Then, we import the Response class,
which will allow us to send content to the client that can be rendered in different content
types, for example, JSON and XML.
Then, we import the HttpResponse from Django with its equivalent of Response in the
rest framework.
We also import all the custom exceptions that we implemented previously, so we can
handle the data properly and send useful error messages to the client when something goes
wrong.
[ 370 ]
Order Microservice Chapter 8
The first class that we are going to create is the OrderListAPIBaseView class, which will
serve as a base class for all the views that will return a list of content to the client:
class OrderListAPIBaseView(generics.ListAPIView):
serializer_class = OrderSerializer
lookup_field = ''
Lastly, we implement the list method, which will first run the get_queryset method to get
the data that will be returned to the user. If an error occurs, it will return a response with
status 400 (BAD REQUEST), otherwise, it will use the OrderSerializer to serialize the
data. The result argument is the QuerySet result returned by the get_queryset method,
and the many keyword argument tells the serializer that we will serialize a list of items.
When the data is serialized properly, we send a response with status 200 (OK) with the
results of the query.
The idea of this base class is that all the children classes will only need to implement the
get_queryset method, which will keep the view classes small and neat.
[ 371 ]
Order Microservice Chapter 8
Now, we are going to add a function that will help us with the methods that will perform a
POST request. Let's go ahead and add a function called set_status_handler:
def set_status_handler(set_status_delegate):
try:
set_status_delegate()
except (
InvalidArgumentError,
OrderAlreadyCancelledError,
OrderAlreadyCompletedError) as err:
return HttpResponse(err, status=status.HTTP_400_BAD_REQUEST)
return HttpResponse(status=status.HTTP_204_NO_CONTENT)
This function is very simple; it will just get a function as an argument. Run the function; if
one of the exceptions occurs, it will return a 400 (BAD REQUEST) response back to the client,
otherwise, it will return a 204 (NO CONTENT) response.
Adding views
Now, it is time to start adding the views! Open the views.py file in the main app directory,
and let's add some import statements:
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
First, we will import the HttpReponse from the django.http module and
get_object_or_404 from the django.shortcuts module. The latter is just a helper
function that will get an object, and in case it cannot find it, it will return a response with
the status 440 (NOT FOUND).
Then, we import generics for creating generic views and statuses, and from
the rest_framework, we import the Response class.
[ 372 ]
Order Microservice Chapter 8
Lastly, we import some of the models, helper methods, and functions, and the serializer that
we are going to be using in the views.
We should be ready to start creating the views. Let's create a view that will get all the orders
for a given customer:
class OrdersByCustomerView(OrderListAPIBaseView):
lookup_field = 'customer_id'
Nice! So, we created a class that inherits from the base class (OrderListAPIBaseView),
which we created in the view_helpers.py, and since we have already implemented the
list method, the only method that we needed to implement here was the get_queryset.
The get_queryset method gets a customer_id as an argument and simply calls the
get_all_orders_by_customer that we created in the Order model manager, passing the
customer_id.
We also defined the value of the lookup_field, which will be used to get the value of the
keyword argument that is passed on to the kwargs of the list method on the base class.
Let's add two more views to get the incomplete and complete orders:
class IncompleteOrdersByCustomerView(OrderListAPIBaseView):
lookup_field = 'customer_id'
class CompletedOrdersByCustomerView(OrderListAPIBaseView):
lookup_field = 'customer_id'
Pretty much the same as the first view that we implemented, we define the lookup_field
and override the get_queryset to call the appropriated method in the Order model
manager.
[ 373 ]
Order Microservice Chapter 8
Now, we are going to add a view that will get a list of orders when given a specific status:
class OrderByStatusView(OrderListAPIBaseView):
lookup_field = 'status_id'
As you can see here, we are defining the lookup_field as status_id and we override the
get_queryset to call get_orders_by_status, passing the status value.
Here, we use Status(status_id), so we pass the Enum item and not only the ID.
All the views that we implemented so far will only accept GET requests and it will return a
list of orders. Now, we are going to implement a view that supports POST requests so we
are able to receive new orders:
class CreateOrderView(generics.CreateAPIView):
if serializer.is_valid():
order = serializer.save()
return Response(
{'order_id': order.id},
status=status.HTTP_201_CREATED)
return Response(status=status.HTTP_400_BAD_REQUEST)
Now, this class differs a bit from the previous ones that we created, the base class being
generics. CreateAPIView provides us with a post method, so we override that method in
order to add the logic that we need. First, we get the request's data and pass it as an
argument to the OrderSerializer class; it will deserialize the data and set it to the
serializer variable. Then, we call the method is_valid(), which will validate the received
data. If the request's data is not valid, we return a 400 response (BAD REQUEST), otherwise,
we go ahead and call the save() method. This method will internally call the create
method on the serializer, and it will create the new order along with the new order's
customer and the order's items. If everything goes well, we return a 202 response
(CREATED) together with the ID of the newly created order.
[ 374 ]
Order Microservice Chapter 8
Now, we are going to create three functions that will handle the order canceling, setting the
next order's status, and lastly, setting a specific order's status:
def cancel_order(request, order_id):
order = get_object_or_404(Order, order_id=order_id)
return set_status_handler(
lambda: Order.objects.cancel_order(order)
)
return set_status_handler(
lambda: Order.objects.set_next_status(order)
)
try:
status = Status(status_id)
except ValueError:
return HttpResponse(
'The status value is invalid.',
status=status.HTTP_400_BAD_REQUEST)
return set_status_handler(
lambda: Order.objects.set_status(order, status)
)
As you can see, we are not using the Django REST framework class-based views here. We
are just using regular functions. The first one, the cancel_order function, gets two
parameters—the request and the order_id. We start by using the shortcut function,
get_object_or_404. The get_object_or_404 function returns a 404 response (NOT
FOUND) if it cannot find the object matching the criteria passed in the second argument.
Otherwise, it will return the object.
[ 375 ]
Order Microservice Chapter 8
The set_next_status function is quite similar, but instead of calling the cancel_order
inside of the lambda function, we will call set_next_status, passing the order that we
want to set to the next status.
The set_status function contains a bit more logic in it, but it is also quite simple. This
function will get two arguments, the order_id and the status_id. First, we get the order
object, then we look up the status using the status_id. If the status doesn't exist, a
ValueError exception will be raised and then we return a 400 response (BAD REQUEST).
Otherwise, we call the set_status_handle, passing a lambda function that will execute
the set_status function passing the order and the status objects.
[ 376 ]
Order Microservice Chapter 8
To add new URLs, we need to use the path function to pass the first argument, the URL.
The second argument is the function that will be executed when a request is sent to the URL
specified by the first argument. Every URL that we create has to be added to the
urlspatterns list. Note that Django 2 simplified how parameters were added to the URL.
Previously, you would need to some using regular expressions; now, you can just follow
the notation <type:param>.
[ 377 ]
Order Microservice Chapter 8
Before we try this out, we have to open the urls.py file, but this time in the order directory
because we need to include the URLs that we just created.
urlpatterns = [
path('admin/', admin.site.urls),
]
Now, we want all the URLs that we defined on the main app to be under /api/. To achieve
this, the only thing we need to do is create a new route and include the URLs from the main
app. Add the following code in the urlpatterns list:
path('api/', include('main.urls')),
The order service won't be public when we deploy it to the AWS; however as an extra
security measure, we are going to enable token authentication for this service.
[ 378 ]
Order Microservice Chapter 8
To call the service's APIs, we will have to send an authentication token. Let's go ahead and
enable it. Open the settings.py file in the order directory and add the following content:
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
)
}
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'main',
'rest_framework',
'rest_framework.authtoken',
]
Perfect! Save the file, and on the terminal, run the following command:
python manage.py migrate
The Django REST framework has out of the box views, so the users can call and acquire a
token. However, for simplicity, we are going to create a user who can have access to the
APIs. Then, we can manually create an authentication token that can be used to do the
request to the order service APIs.
[ 379 ]
Order Microservice Chapter 8
Let's go ahead and create this user. Start the service with the following command:
python manage.py runserver
Under the AUTHENTICATION AND AUTHORIZATION tab, you will see the Users
model. Click on Add and create a user with the username api_user. When the user is
created, browse back to the admin first page and under the AUTH TOKEN, click on Add.
Select the api_user in the drop-down menu and click SAVE. You should see a page like
the following:
Copy the key and let's create a small script just to add an order so we can test the APIs.
Create a file called send_order.py; it can be placed anywhere you want as long as you
have the virtual environment activated, since we are going to use the package requests to
send the order to the order services. Add the following content to the send_order.py file:
import json
import sys
import argparse
from http import HTTPStatus
import requests
def setUpData(order_id):
data = {
"items": [
{
[ 380 ]
Order Microservice Chapter 8
return data
def send_order(data):
response = requests.put(
'',
data=json.dumps(data))
if response.status_code == HTTPStatus.NO_CONTENT:
print('Ops! Something went wrong!')
sys.exit(1)
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Create a order for test')
parser.add_argument('--orderid',
dest='order_id',
required=True,
help='Specify the the order id')
[ 381 ]
Order Microservice Chapter 8
args = parser.parse_args()
data = setUpData(args.order_id)
send_order(data)
[ 382 ]
Order Microservice Chapter 8
What? Something went wrong here, can you guess what it is? Note the log message that
was printed in the screenshot in the terminal where I have the Django development server
running:
[21/Jan/2018 09:30:37] "PUT /api/order/add/ HTTP/1.1" 401 58
Ok, it says here that the server has received a PUT request to /api/order/add/, and one
thing to notice here is that code 401 signifies Unauthorized. This means that the settings
that we have added in the settings.py file worked fine. To call the APIs, we need to be
authenticated, and we are using token authentication.
To create a token for a user, we need to log in in the Django administration UI. There, we
will find the AUTH TOKEN section as follows:
Click on that green plus sign on the right-hand side. Then, you can select the user you wish
to create a token for and when you are ready, click save. After that, you will see a list of
tokens that have been created:
[ 383 ]
Order Microservice Chapter 8
That key is the key you want to send in the request's HEADER.
Now that we have a token, we can modify the send_order.py script and add the token
information to the request, so on the top of the send_order function, add the following
code:
token = '744cf4f8bd628e62f248444a478ce06681cb8089'
headers = {
'Authorization': f'Token {token}',
'Content-type': 'application/json'
}
The token variable is the token that we created for the user api_user. To get the token, just
log in to the Django admin UI and under AUTH TOKEN, you will see the tokens that have
been created. Just remove the token that I added here and replace it with the one that was
generated for the api_user on your application.
Then, we need to send the headers along with the request. Change the following code:
response = requests.put(
'',
data=json.dumps(data))
[ 384 ]
Order Microservice Chapter 8
Now, we can go to the terminal and run our code again. You should see an output similar
to the output shown in the following screenshot:
This means that the authentication works properly. Go ahead and take the time to explore
the Django admin UI and verify that now we have one customer and one order with a
couple of items created on our database.
Let's try some of the other endpoints to see if they are working as expected. For example,
we can get all the orders for that customer that we just created.
[ 385 ]
Order Microservice Chapter 8
You can perform small tests to the endpoints using any tool you want.
There are a few very handy browser plugins that you can install, or, if you
are like me and like to do everything on the terminal, you can use cURL.
Alternatively if you want to try to build something with Python, there is
the httpie package that you can install using pip. Use the pip install
httpie --upgrade --user command to install httpie on your local
directory under ./local/bin. So, don't forget to add this directory to
your PATH. I like to use httpie instead of cURL because httpie shows a
nice and formatted JSON output so I can get a better view of the response
that I'm getting back from the endpoint.
[
{
"items": [
{
"name": "Prod 001",
"price_per_unit": 10,
"product_id": 1,
"quantity": 2
},
{
"name": "Prod 002",
"price_per_unit": 12,
"product_id": 2,
"quantity": 2
}
],
"order_customer": {
"customer_id": 14,
[ 386 ]
Order Microservice Chapter 8
Next up, we are going back to the online video game store and send the order.
At the moment, in the online video game store, it is not possible to submit orders.
The users of our site can only add items to the cart, visualize, and edit the cart's
items. We are going to finish that implementation and create a view so that we
can submit the order.
We are going to implement one more view where we can see the order history.
The first change that we are going to do is add the authentication token for the api_user
that we created in the service orders. We also want to add the base URL to the order service,
so it will be easier for us to build up the URLs that we need to perform the requests. Open
the settings.py file in the gamestore directory and add these two constant variables:
ORDER_SERVICE_AUTHTOKEN =
'744cf4f8bd628e62f248444a478ce06681cb8089'
ORDER_SERVICE_BASEURL = ''
It does not matter where you place this code, but maybe it's a good idea to just place it at
the end of the file.
[ 387 ]
Order Microservice Chapter 8
The next change that we are going to do is add a namedtuple called OrderItem, just to
help us prepare the order's data so it is compatible with the format that the order service is
expecting. Open the models.py file in the gamestore/main directory and add import:
from collections import namedtuple
Another change to the models file is that we are going to add a new method in the
ShoppingCartManager class called empty, so that when it's called, it will remove all the
cart's items. Inside of the ShoppingCartManager class, add the following method:
def empty(self, cart):
cart_items = ShoppingCartItem.objects.filter(
cart__id=cart.id
)
Next up, we are going to change the cart.html template. Locate the send order button:
<button class='btn btn-primary'>
<i class="fa fa-check" aria-</i>
SEND ORDER
</button>
Nice! We just created a form around the button and added the Cross-Site Request Forgery
token within the form, so that when we click the button, it will send a request to
cart/send.
[ 388 ]
Order Microservice Chapter 8
Let's add the new URLs. Open the urls.py file in the main app directory, and let's add two
new URLs:
path(r'cart/send', views.send_cart),
path(r'my-orders/', views.my_orders),
You can place these two URL definitions right after the definition of the /cart/ URL.
Then, we add a function that will help us with the serialization of the order data to be sent
to the order service:
def _prepare_order_data(cart):
cart_items = ShoppingCartItem.objects.values_list(
'game__name',
'price_per_unit',
'game__id',
'quantity').filter(cart__id=cart.id)
order = cart_items.aggregate(
total_order=Sum(F('price_per_unit') * F('quantity'),
output_field=DecimalField(decimal_places=2))
)
order_customer = {
'customer_id': cart.user.id,
'email': cart.user.email,
'name': f'{cart.user.first_name} {cart.user.last_name}'
}
order_dict = {
'items': order_items,
'order_customer': order_customer,
'total': order['total_order']
}
[ 389 ]
Order Microservice Chapter 8
Now, we have two more views to add, the first being the send_order:
@login_required
def send_cart(request):
cart = ShoppingCart.objects.get(user_id=request.user.id)
data = _prepare_order_data(cart)
headers = {
'Authorization': f'Token
{settings.ORDER_SERVICE_AUTHTOKEN}',
'Content-type': 'application/json'
}
service_url =
f'{settings.ORDER_SERVICE_BASEURL}/api/order/add/'
response = requests.post(
service_url,
headers=headers,
data=data)
if HTTPStatus(response.status_code) is HTTPStatus.CREATED:
request_data = json.loads(response.text)
ShoppingCart.objects.empty(cart)
messages.add_message(
request,
messages.INFO,
('We received your order!'
'ORDER ID: {}').format(request_data['order_id']))
else:
messages.add_message(
request,
messages.ERROR,
('Unfortunately, we could not receive your order.'
' Try again later.'))
return HttpResponseRedirect(reverse_lazy('user-cart'))
Next is the my_orders view, which will be the new view that returns the order history:
@login_required
def my_orders(request):
headers = {
'Authorization': f'Token
{settings.ORDER_SERVICE_AUTHTOKEN}',
'Content-type': 'application/json'
}
[ 390 ]
Order Microservice Chapter 8
get_order_endpoint =
f'/api/customer/{request.user.id}/orders/get/'
service_url =
f'{settings.ORDER_SERVICE_BASEURL}{get_order_endpoint}'
response = requests.get(
service_url,
headers=headers
)
if HTTPStatus(response.status_code) is HTTPStatus.OK:
request_data = json.loads(response.text)
context = {'orders': request_data}
else:
messages.add_message(
request,
messages.ERROR,
('Unfortunately, we could not retrieve your orders.'
' Try again later.'))
context = {'orders': []}
We need to create the my-orders.html file, which is going to be the template that is
rendered by the my_orders view. Create a new file called my-orders.html in the
main/templates/main/ directory with the following contents:
{% extends 'base.html' %}
{% block 'content' %}
<h3>Order history</h3>
<div class="order-container">
<div><strong>Order ID:</strong> {{order.id}}</div>
<div><strong>Create date:</strong> {{ order.created_at }}</div>
<div><strong>Status:</strong> <span class="label label-
success">{{order.status}}</span></div>
<div class="table-container">
<table class="table table-striped">
<thead>
<tr>
<th>Product name</th>
<th>Quantity</th>
<th>Price per unit</th>
[ 391 ]
Order Microservice Chapter 8
</tr>
</thead>
<tbody>
{% for item in order.items %}
<tr>
<td>{{item.name}}</td><td>{{item.quantity}}</td>
<td>${{item.price_per_unit}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div><strong>Total amount:</strong>{{order.total}}</div>
<hr/>
</div>
{% endfor %}
{% endblock %}
This template is very basic; it is just looping through the orders and then looping the items
and building a HTML table with the item's information.
We need to do some changes in site.css, where we have the custom styling of the online
video game store. Open the site.css file in the static/styles folder and let's do some
modifications. First, locate this code, which is shown as follows:
.nav.navbar-nav .fa-home,
.nav.navbar-nav .fa-shopping-cart {
font-size: 1.5em;
}
At the end of this file, we can add stylings that are specific to the order history page:
.order-container {
border: 1px solid #000;
margin: 20px;
padding: 10px;
}
[ 392 ]
Order Microservice Chapter 8
Now, we are going to add one more menu option that will be a link to the new my
orders page. Open the base.html file in the templates directory in the applications
root directory, and locate the menu option CART:
<li>
<a href="/cart/">
<i class="fa fa-shopping-cart" aria-</i> CART
</a>
</li>
Right after the closing </li> tag, add the following code:
<li>
<a href="/my-orders/">
<i class="fa fa-truck" aria-</i> ORDERS
</a>
</li>
Finally, the last change that we are going to do is improve the layout of error messages that
we show in the UI. Locate this code at the end of the base.html file:
{% if messages %}
{% for message in messages %}
</div>
{% endfor %}
{% endif %}
[ 393 ]
Order Microservice Chapter 8
One thing to keep in mind is that for testing, we will need to run the Django application in
different ports. We can run the website (game online store) using the default port 800, and
for the order services, we can use port 8001.
Open two terminals; in one terminal, we are going to start the online video game store:
python manage.py runserver
And, on the second terminal, we are going to start the order service:
python manage.py runserver 127.0.0.1:8001
Great! Open the browser and head to and log in with our
credentials. After logging in, you will notice that a few things are different. Now, there is a
new option in the top menu called ORDERS. It should be empty, so go ahead and add a few
items to the cart. When you are done, go to the cart view and click on the send order button.
If everything went right, you should see a notification at the top of the page, as follows:
Perfect! It worked just as expected. Notice that after sending the order to the order service,
the shopping cart got emptied as well.
[ 394 ]
Order Microservice Chapter 8
Now, click on the ORDERS option on the top menu, and you should see the order that we
just submitted:
Deploying to AWS
Now, it is time to show the world the work that we have been doing so far.
We are going to deploy the gamestore Django application and also the order service to EC2
instances in Amazon Web services.
Instead, we will assume that you already have your environment set up, and focus on:
[ 395 ]
Order Microservice Chapter 8
My AWS setup is quite simple, but it definitely works for more complex setups. Right now,
I have one VPC with one subnet and two EC2 instances on it (gamestore and order-
service). See the following screenshot:
We can start with the gamestore application; connect via ssh to the EC2 instance that you
wish to deploy the game online application on. Remember that to ssh in one of those
instances, you will need to have the .pem file:
ssh -i gamestore-keys.pem ec2-user@35.176.16.157
We will start by updating any package that we have installed on that machine; it is not
required, but it is a good practice since some of the packages may have security fixes and
performance improvements that you probably want to have on your installs. Amazon Linux
uses the yum package manager, so we run the following command:
sudo yum update
These EC2 instances do not have Python installed by default, so we need to install it as well:
sudo yum install python36.x86_64 python36-pip.noarch python36-
setuptools.noarch
Perfect! Now, we can copy our application, exit this instance, and from our local machine,
run the following command:
scp -R -i gamestore-keys.pem ./gamestore ec2-user@35.176.16.157:~/gamestore
[ 396 ]
Order Microservice Chapter 8
This command will recursively copy all the files from the gamestore directory on our local
machine over to our home directory in the EC2 instance.
We also need to change the ORDER_SERVICE_BASEURL that we defined at the end of the
file. It needs to be the address of the instance that we are going to deploy to the order
service. In my case, the IP is 35.176.194.15, so my variable will look like this:
ORDER_SERVICE_BASEURL = ""
We are going to create a folder to keep the application since it is not a good idea to keep the
application running in the ec2-user folder. So, we are going to create a new folder in the
root directory called app and copy the gamestore directory over to the newly created
directory:
sudo mkdir /app && sudo cp -R ./gamestore /app/
We need also to set the current permissions on that directory. When nginx is installed, it
also creates a nginx user and a group. So, let's change the ownership of the entire folder:
cd / && sudo chown -R nginx:nginx ./gamestore
Finally, we are going to set up nginx, edit the /etc/nginx/nginx.conf file, and under
service, add the following configuration:
location / {
proxy_pass;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
location /static {
root /app/gamestore;
}
[ 397 ]
Order Microservice Chapter 8
We need to restart the nginx service so that the service reflects the changes that we just
made:
sudo service nginx restart
Start the application with gunicorn. We are going to start the application as an nginx user:
sudo gunicorn -u nginx gamestore.wsgi
Now, we can browse to the site. You don't need to specify port 8000 since nginx will route
the requests coming from port 80 to 127.0.0.1:8000.
You can pretty much repeat all the steps up until installing the nginx step. Also, make sure
that you are using the elastic IP address of the other EC2 instance from now on.
After you install nginx, we can install the order service dependencies:
sudo pip-3.6 install django djangorestframework requests
We can now copy the project file. Go to the directory where you have the service's
directory, and run this command:
scp -R -i order-service-keys.pem ./order ec2-user@35.176.194.15:~/gamestore
Like gamestore, we also need to edit the settings.py file and add our EC2 instance
elastic IP:
ALLOWED_HOSTS=["35.176.194.15"]
[ 398 ]
Order Microservice Chapter 8
We will also create a folder in the root directory so the project is not laying around in the
ec2-user home directory:
Let's edit the /etc/nginx/nginx.conf file, and, under service, add the following
configuration:
location / {
proxy_pass;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
This time, we don't need to configure the static folder since the order services don't have
anything like images, templates, JS, or CSS files.
And start the application with gunicorn. We are going to start the application as an nginx
user:
sudo gunicorn -u nginx order.wsgi
Finally, we can browse to the address where the gamestore is deployed, and you should
see the site up and running.
[ 399 ]
Order Microservice Chapter 8
Browsing to the site, you will see the first page. All the products are loading, and the login
and logout sections are also working properly. Here's a screenshot of my system:
[ 400 ]
Order Microservice Chapter 8
If you browse to a view that makes use of the order service, for example, the orders section,
you can verify that everything is working, and if you have placed any orders on the site,
you should see the orders listed here, as shown in the following screenshot:
Summary
We have covered a lot of topics in this chapter; we have built the order service that was
responsible for receiving orders from the web application that we developed in the
previous chapter. The order service also provides other features, such as the ability to
update the status of orders and provide order information using different criteria.
This microservice was an extension of the web application that we developed in the
previous chapter, and in the following chapter, we are going to extend it even further by
adding serverless functions to notify the users of our application when an order is
successfully received and also when the order's status has changed to shipped.
[ 401 ]
Notification Serverless
9
Application
In this chapter, we are going to explore AWS Lambda Functions and AWS API Gateway.
AWS Lambda enables us to create serverless functions. Serverless doesn't mean that it is
without a server; in reality, it means that these functions don't require the DevOps overhead
that you would have if you were running the application on, for example, an EC2 instance.
Serverless architecture is not the silver bullet or the solution to all the problems, but there
are many advantages, such as pricing, the fact that almost no DevOps is required, and
support for different programming languages.
In the case of Python, tools like Zappa and the microframework for AWS Chalice, which is
also developed by Amazon, make creating and deploying serverless functions incredibly
easy.
To build this service we are going to use the micro web framework Flask, so let's install that:
pipenv install flask
We are also going to install the requests package, which will be used when sending requests
to the order service:
pipenv install requests
That should be everything we need for now. Next, we are going to see how we can use
AWS Simple Email Service to send emails from our applications.
The installation is quite simple, as it can be installed via pip, and the AWS CLI has support
for Python 2 and Python 3 and runs on different operating systems, such as Linux, macOS,
and Windows.
[ 403 ]
Notification Serverless Application Chapter 9
The upgrade option will tell pip to update all the requirements that are already installed,
and the --user option means that pip will install the AWS CLI in our local directory, so it
won't touch any library that is installed globally on our system. On Linux systems, when
installing a Python package using the --user option, the package will be installed in the
directory .local/bin, so make sure that you have that in your path.
Just to verify that the installation worked properly, type the following command:
aws --version
Here you can see the AWS CLI version, as well as the operating system version, Python
version, and which version of botocore is currently in use. botocore is the core library
used by the AWS CLI. Also, boto is an SDK for Python, which allows developers to write
software to work with Amazon services like EC2 and S3.
Now we need to configure the CLI, and we will need to have some information at hand.
First, we need the aws_access_key_id and the aws_secret_access_key, as well as your
preferred region and output. The most common value, the output option, is JSON.
To create the access keys, click on the drop-down menu with your username on the top
right hand of the AWS console page, and select My Security Credentials. You will land on
this page:
[ 404 ]
Notification Serverless Application Chapter 9
Here you can configure different account security settings, such as changing the password
or enabling multi-factor authentication, but the one you should choose now is Access keys
(access key ID and secret access key). Then click on Create New Access Key, and a dialog
will be opened with your keys. You will also be given the option to download the keys. I
suggest you download them and keep them in a safe place.
You will be asked to provide the access key, the secret access key, the region, and the
default output format.
To get it working, we will need to have two email accounts that we can use. In my case, I
have my own domain. I have also created two email
accounts—donotreply@dfurtado.com, which will be the email that I will use to send
emails, and pythonblueprints@dfurtado.com, which is the email that will receive the
email. A user in an online (video) game store application will use this email address and we
will place a few orders so we can test the notification later on.
[ 405 ]
Notification Serverless Application Chapter 9
As you can see, the list is empty, so let's go ahead and add two emails. Click on Verify a
New Email Address and a dialog will appear where you can enter an email address. Just
enter the email that you wish to use and click on Verify This Email Address button. By
doing this a verification email will be sent to the email address that you specified, and
therein you will find a link for the verification.
Repeat the same steps for the second email, the one that will receive the messages.
Now, go over to the left side menu again and click on SMTP Settings under Email
Sending.
There you will see all the configurations necessary to send emails, and you will also have to
create SMTP credentials. So click on the button Create My SMTP Credentials, and a new
page will be opened where you can input the IAM username that you wish. In my case, I'm
adding python-blueprints. After you have done that, click the button Create. After the
credentials have been created, you will be presented with a page where you can see the
SMTP username and password. You will have the option to download these credentials if
you like.
[ 406 ]
Notification Serverless Application Chapter 9
Creating an S3 bucket
In order to send a template email to the users, we need to copy our templates to an S3
bucket. We can easily do that through the web, or you can use the AWS CLI that we just
installed. The command to create the S3 bucket in the es-west-2 region is something like:
aws s3api create-bucket \
--bucket python-blueprints \
--region eu-west-2 \
--create-bucket-configuration LocationConstraint=eu-west-2
Here we use the command s3api, which will provide us with different sub-commands to
interact with the AWS S3 service. We call the sub-command create-bucket, which, as the
name suggests, will create a new S3 bucket. To this sub-command, we specify three
arguments. First, --bucket, which specifies the S3 bucket's name, then --region, to
specify which region the bucket will be created - in this case, we are going to create the
bucket in the eu-west-2. Lastly, locations outside the region us-east-1 request the
setting LocationConstraint so the bucket can be created in the region that we wish.
Let's go ahead and create a file called app.py in the notifier directory, and to start with,
let's add some imports:
import smtplib
from http import HTTPStatus
from smtplib import SMTPAuthenticationError, SMTPRecipientsRefused
import boto3
from botocore.exceptions import ClientError
[ 407 ]
Notification Serverless Application Chapter 9
First, we import the JSON module so we can serialize and deserialize data. We import
HTTPStatus from the HTTP module so we can use the HTTP status constants when
sending responses back from the service's endpoints.
Then we import the modules that we will need to send emails. We start by importing the
smtplib and also some exceptions that we want to handle.
We also import MIMEText, which will be used to create a MIME object out of the email
content, and the MIMEMultipart that will be used to create the message that we are going
to send.
Next, we import the boto3 package so we can work with the AWS services. There are some
exceptions that we will be handling; in this case, both exceptions are related to the S3
buckets.
Next are some Flask related imports, and last but not least, we import the Jinja2 package
to template our emails.
Continuing working on the app.py file, let's define the constant that will hold the name or
the S3 bucket that we created:
S3_BUCKET_NAME = 'python-blueprints'
Then we are going to define two helper functions. The first one is to send emails:
def _send_message(message):
smtp = smtplib.SMTP_SSL('email-smtp.eu-west-1.amazonaws.com',
465)
try:
smtp.login(
user='DJ********DER*****RGTQ',
password='Ajf0u*****44N6**ciTY4*****CeQ*****4V')
except SMTPAuthenticationError:
return Response('Authentication failed',
status=HTTPStatus.UNAUTHORIZED)
[ 408 ]
Notification Serverless Application Chapter 9
try:
smtp.sendmail(message['From'], message['To'],
message.as_string())
except SMTPRecipientsRefused as e:
return Response(f'Recipient refused {e}',
status=HTTPStatus.INTERNAL_SERVER_ERROR)
finally:
smtp.quit()
Here, we define the function _send_message, which gets just one argument, message. We
start this function by creating an object that will encapsulate an SMTP connection. We use
SMTP_SSL because the AWS Simple Email Service required TLS. The first argument is the
SMTP host, which we created at the AWS Simple Email Service, and the second argument is
the port, which will be set as 456 when SMTP connections over SSL are required.
Then we call the login method, passing the username and the password, which can also be
found in the AWS Simple Email Service. In cases where
an SMTPAuthenticationError exception is thrown we send an UNAUTHORIZED response
back to the client.
If logging into the SMTP server is successful, we call the sendmail method, passing the
email that is sending the message, the destination recipient, and the message. We handle
the situation where some of the recipients reject our message, in that we return an
INTERNAL SERVER ERROR response, and then we just quit the connection.
Lastly, we return the OK response stating that the message has been sent successfully.
Now, we create a helper function to load the template file from the S3 bucket and return a
rendered template for us:
def _prepare_template(template_name, context_data):
s3_client = boto3.client('s3')
try:
file = s3_client.get_object(Bucket=S3_BUCKET_NAME,
Key=template_name)
except ClientError as ex:
error = ex.response.get('Error')
error_code = error.get('Code')
if error_code == 'NoSuchBucket':
raise S3Error(
[ 409 ]
Notification Serverless Application Chapter 9
content = file['Body'].read().decode('utf-8')
template = Template(content)
return template.render(context_data)
First, we create an S3 client, then we use the get_object method to pass the bucket name
and the Key. We set the bucket keyword argument to S3_BUCKET_NAME, which we defined
at the top of this file with the value of python-blueprints. The Key keyword argument is
the name of the file; we set it to the value that we specified in the argument
template_name.
Next, we access the key Body in the object returned from the S3 bucket, and call the method
read. This will return a string with the file contents. Then, we create a Jinja2 Template
object passing the contents of the template's file, and finally, we call the render method
passing the context_data.
Now, let's implement the endpoint that will be called to send a confirmation email to the
customer whose order we receive:
@app.route("/notify/order-received/", methods=['POST'])
def notify_order_received():
data = json.loads(request.data)
order_items = data.get('items')
customer = data.get('order_customer')
customer_email = customer.get('email')
customer_name = customer.get('name')
order_id = data.get('id')
total_purchased = data.get('total')
[ 410 ]
Notification Serverless Application Chapter 9
message = MIMEMultipart('alternative')
context = {
'order_items': order_items,
'customer_name': customer_name,
'order_id': order_id,
'total_purchased': total_purchased
}
try:
'order_received_template.html',
context
)
except S3Error as ex:
return Response(str(ex),
status=HTTPStatus.INTERNAL_SERVER_ERROR)
message.attach(MIMEText(email_content, 'html'))
return _send_message(message)
We start this function by getting all the data that has been passed in the request. In Flask
applications this data can be accessed on request.data; we use the json.loads method
to pass request.data as an argument, so it will deserialize the JSON objects into a Python
object. Then we get the items, which are a list with all the items included in the order, and
we get the value of the attribute order_customer so we can get the customer's email and
the customer's name.
After that, we get the order ID, which can be accessed via the property id, and lastly, we
get the total purchase value that is in the property total of the data that has been sent to
this endpoint.
[ 411 ]
Notification Serverless Application Chapter 9
Lastly, we do the final setup for our email message; we attach the rendered template to the
message, we set subject, sender, and destinations, and we call the _send_message function
to send the message.
Next, we are going to add the endpoint that will notify the users when their order has
changed status to Shipping:
@app.route("/notify/order-shipped/", methods=['POST'])
def notify_order_shipped():
data = json.loads(request.data)
customer = data.get('order_customer')
customer_email = customer.get('email')
customer_name = customer.get('name')
order_id = data.get('id')
message = MIMEMultipart('alternative')
try:
'order_shipped_template.html',
{'customer_name': customer_name}
)
except S3Error as ex:
return Response(ex,
status=HTTPStatus.INTERNAL_SERVER_ERROR)
message.attach(MIMEText(email_content, 'html'))
return _send_message(message)
[ 412 ]
Notification Serverless Application Chapter 9
We start by getting the data that has been passed in the request - basically the same as the
previous function, the notify_order_received. We also create an instance of
MIMEMultipart, setting the MIME type to multipart/alternative. Next, we use the
_prepare_template function to load the template and render using the context that we
are passing in the second argument; in this case, we are passing only the customer's name.
Then we attach the template to the message and do the final set up, setting the subject, the
send, and the destination. Finally, we call _send_message to send the message.
Next, we are going to create two email templates, one that we are going to use when
sending an order confirmation notification to the user and the other for when an order has
been shipped.
Now we are going to create the templates that are going to be used when sending the
notification emails to the online (video) game store's customers.
In the application's root directory, create a directory called templates and create a file
called order_received_template.html, with the contents shown as follows:
<html>
<head>
</head>
<body>
<h1>Hi, {{customer_name}}!</h1>
<h3>Thank you so much for your order</h3>
<p>
<h3>Order id: {{order_id}}</h3>
</p>
<table border="1">
<thead>
<tr>
<th align="left" width="40%">Item</th>
<th align="left" width="20%">Quantity</th>
<th align="left" width="20%">Price per unit</th>
</tr>
</thead>
[ 413 ]
Notification Serverless Application Chapter 9
<tbody>
{% for item in order_items %}
<tr>
<td>{{item.name}}</td>
<td>{{item.quantity}}</td>
<td>${{item.price_per_unit}}</td>
</tr>
{% endfor %}
</tbody>
</table>
<div style="margin-top:20px;">
<strong>Total: ${{total_purchased}}</strong>
</div>
</body>
</html>
<html>
<head>
</head>
<body>
<h1>Hi, {{customer_name}}!</h1>
<h3>We just want to let you know that your order is on its way!
</h3>
</body>
</html>
If you have read Chapter 7, Online Video Game Store with Django, you should be familiar
with this syntax. The Jinja 2 syntax has a lot of similarities when compared to the Django
template language.
Now we can copy the template to the S3 bucket that we created previously. Open a terminal
and run the following command:
aws s3 cp ./templates s3://python-blueprints --recursive
[ 414 ]
Notification Serverless Application Chapter 9
The installation is pretty straightforward. Within the virtual environment that we have been
using to develop this project, you can just run the pipenv command:
pipenv install zappa
After the installation, you can start the configuration. You just need to make sure that you
have a valid AWS account and the AWS credentials file is in place. If you followed this
chapter from the beginning and installed and configured the AWS CLI you should be all
set.
You will see the ASCII Zappa logo (very beautiful BTW), and it will start asking some
questions. The first one is:
Your Zappa configuration can support multiple production stages, like
'dev', 'staging', and 'production'.
What do you want to call this environment (default 'dev'):
You can just hit Enter to default to dev. Next, Zappa will ask the name of an AWS S3
bucket:
Your Zappa deployments will need to be uploaded to a private S3 bucket.
If you don't have a bucket yet, we'll create one for you too.
What do you want call your bucket? (default 'zappa-uc40h2hnc'):
Here you can either specify an existent or create a new one. Then, Zappa will try to detect
the application that we are trying to deploy:
It looks like this is a Flask application.
What's the modular path to your app's function?
This will likely be something like 'your_module.app'.
We discovered: notify-service.app
Where is your app's function? (default 'notify-service.app'):
[ 415 ]
Notification Serverless Application Chapter 9
As you can see, Zappa automatically found the Flask app defined in the notify-
service.py file. You can just hit Enter to set the default value.
Next, Zappa will ask if you would like to deploy the application globally; we can keep the
default and answer n. Since we are deploying this application in a development
environment, we don't really need to deploy it globally. When your application goes into
production you can evaluate if you need to deploy it globally.
Lastly, the complete configuration will be displayed, and here you have to change the
review and make any modifications if needed. You don't need to be too worried about
saving the configuration or not because the Zappa settings file is just a text file with the
settings in JSON format. You can just edit the file at any time and change it manually.
If everything went well, you should see a file called zappa_settings.json on the root's
directory of your application, with the contents similar to the content shown as follows:
{
"dev": {
"app_function": "notify-service.app",
"aws_region": "eu-west-2",
"project_name": "notifier",
"runtime": "python3.6",
"s3_bucket": "zappa-43ivixfl0"
}
}
Here you can see the dev environment settings. The app_function specifies the Flask app
that I created on the notify-service.py file, the aws_region specifies in which region
the application will be deployed - in my case since I'm in Sweden, I chose eu-west-2
(London) which is the closest region to me. The project_name will get by default the name
of the directory where you run the command zappa init.
Then we have the runtime, which refers to the Python version that you are running with the
application. Since the virtual environment that we created for this project used Python 3,
the value for this property should be a version of Python 3 - in my case, I have installed
3.6.2. Lastly, we have the name of the AWS S3 bucket that Zappa will use to upload the
project files.
Now, let's deploy the application that we just created! On the terminal, simply run the
following command:
zappa deploy dev
[ 416 ]
Notification Serverless Application Chapter 9
Zappa will perform lots of tasks for you, and at the end it will display the URL where the
application has been deployed. In my case I've got:
Yours will look slightly different. So, we have defined two endpoints in our Flask
application, /notify/order-received and /notify/order-shipped. These endpoints
can be called with the following URLs:
eived
pped
If you want to see more information about the deployment, you can use the Zappa
command: zappa status.
In the next section, we are going to learn how to restrict access to these endpoints and create
an access key that can be used to make the API calls.
To do that, log into our account on AWS console and on the Services menu search for and
select Amazon API Gateway. Under the API on the left side menu, you will see the
notifier-dev:
[ 417 ]
Notification Serverless Application Chapter 9
Great! Here we are going to define a usage plan. Click on Usage Plans and then click on the
Create button, and you will see a form for creating a new usage plan. Enter the name up-
blueprints, uncheck the checkboxes for Enable throttling and Enable Quota, and click
the Next button.
The next step is to associate an API stage. So far we have only dev, so let's add the stage
dev; click on Add API Stage button, and on the drop-down list select the notifier-dev and
the stage dev. Make sure to click on the check button, the same row as the drop-down
menus, otherwise, the Next button won't be enabled.
After clicking Next you will have to add an API key to the Usage Plan that we just created.
Here you will have two options; add a new one or pick an existing one:
Let's add a new one. Click on the button labeled Create API Key and add to Usage Plan.
The API Key creation dialog will be shown, so just enter the name notifiers-devs and
click save.
[ 418 ]
Notification Serverless Application Chapter 9
Great! Now if you select API Keys on the left side menu, you should see the newly created
API Key on the list. If you selected it, you will be able to see all the details regarding the
key:
Now, on the left side menu, select APIs -> notifier-dev -> Resources, and on the tab
Resources, select the root route /. On the right side panel, you can see the / Methods:
[ 419 ]
Notification Serverless Application Chapter 9
Note that ANY says Authorization None and that API Key is set to Not required. Let's
change that so the API Key is required. On the Resources panel, click on ANY, you should
see now a panel similar to the screenshot shown as follows:
[ 420 ]
Notification Serverless Application Chapter 9
Click on the pen icon next to API Key Required and, on the drop-down menu, select the
value true.
Great! Now, the API calls to the stage dev should be restricted to requests with the API key
notifier-dev in the request's Header.
Lastly, head over to API Keys and click on notifier-keys. On the right side panel, in the API
Key, click on the link show, and the API key will be displayed for you. Copy that key,
because we are going to use it in the next section.
[ 421 ]
Notification Serverless Application Chapter 9
The first thing we have to do is to include the notifier service API key and its base URL in
the settings.py file in the directory, called order on the order's root directory, and
include the following content at the end of the file:
NOTIFIER_BASEURL =
''
NOTIFIER_API_KEY = 'WQk********P7JR2******kI1K*****r'
Replace these values with the corresponding values on your environment. If you don't have
the value for the NOTIFIER_BASEURL, you can obtain it running the following command:
zappa status
Now, we are going to create two files. The first one it is a file
called notification_type.py in the order/main directory. In this file, we will define an
enumeration with the notification types that we want to make available in our service:
from enum import Enum, auto
class NotificationType(Enum):
ORDER_RECEIVED = auto()
ORDER_SHIPPED = auto()
Next, we are going to create a file with a helper function that will make the calls to the
notification service. Create a file called notifier.py in the order/main/ directory with
the contents shown as follows:
import requests
import json
header = {
'X-API-Key': settings.NOTIFIER_API_KEY
[ 422 ]
Notification Serverless Application Chapter 9
response = requests.post(
f'{settings.NOTIFIER_BASEURL}/{endpoint}',
json.dumps(order.data),
headers=header
)
return response
From the top, we included some import statements; we are importing requests to perform
the request to the notifier service, so we import the module json, so we can serialize the data
to be sent to the notifier service. Then we import the settings so we can get hold of the
constants that we defined with the base URL to the notifier service and the API key. Lastly,
we import the notification type enumeration.
The function notify that we defined here takes two arguments, the order and the
notification type, which are the values defined in the enumeration NotificationType.
We start by deciding which endpoint we are going to use, depending on the notification's
type. Then we add an entry X-API-KEY to the request's HEADER with the API key.
After that, we make a POST request that passes a few arguments. The first argument is the
endpoint's URL, the second is the data that we are going to send to the notifier service (we
use the json.dumps function so the data is sent in JSON format), and the third argument is
the dictionary with the header data.
Now we need to modify the view that is responsible for handling a POST request to create a
new order, so that it calls the notify function when an order is created in the database. Let's
go ahead and open the file view.py in the order/main directory and add two import
statements:
from .notifier import notify
from .notification_type import NotificationType
The two lines can be added before the first class in the file.
Perfect, now we need to change the method post in the CreateOrderView class. Before the
first return statement in that method, where we return a 201 (CREATED) response, include
the code shown as follows:
notify(OrderSerializer(order),
NotificationType.ORDER_RECEIVED)
[ 423 ]
Notification Serverless Application Chapter 9
So here we call the notify function, passing the serialized order using the
OrderSerializer on the first argument, and the notification type - in this case, we want to
send an ORDER_RECEIVED notification.
We will allow the user of the order service application to update the order using the Django
Admin. There, they will be able to, for example, update an order's status, so we need to
implement some code that will handle data changes made by users using the Django
Admin.
To do this, we need to create a ModelAdmin class inside of the admin.py file in the
order/main directory. First, we add some import statements:
Here, we create a class called OrderAdmin that inherits from the admin.ModelAdmin, and
we override the method save_model so we have the chance to perform some actions before
the data is saved. First, we get the order current status, then we check if the field status is
between the list of fields that have been changed.
The if statement checks if the status field has changed, and if the current status of the order
equals to Status.Shipping then we call the notify function, passing the serialized order
object and the notification type NotificationType.ORDER_SHIPPED.
[ 424 ]
Notification Serverless Application Chapter 9
Lastly, we call the save_model method on the super class to save the object.
This will register the admin model OrderAdmin for the Order model. Now, when the user
saves the order in the Django admin UI, it will call the save_model in the OrderAdmin
class.
Open a terminal, change to the directory where you have implemented the online (video)
game store, and execute the following command to start up the Django development server:
python manage.py runserver
This command will start the Django development server running on the default port 8000.
Now let's start the order microservice. Open another terminal window, change to the
directory where you implemented the order microserver, and run the following command:
python manage.py runserver 127.0.0.1:8001
Now we can browse to, log in to the application and add some
items to the cart:
[ 425 ]
Notification Serverless Application Chapter 9
As you can see, I added three items and the total amount of this order is $32.75. Click on the
button SEND ORDER, and you should get a notification on the page that the order has
been sent.
Great! Working as expected so far. Now we check the user's email, to verify if the
notification service actually sent the order confirmation email.
[ 426 ]
Notification Serverless Application Chapter 9
Note that the sender and the destination recipients are the emails that I registered in the
AWS Simple Email Service.
So now let's log in to the order service's Django admin and change the status for the same
order to verify that the confirmation email that the order has been shipped will be sent to
the user. Remember that the email will only be sent if the order has changed its status field
to shipped.
[ 427 ]
Notification Serverless Application Chapter 9
Click on Orders and then select the order that we just submitted:
On the drop-down menu Status, change the value to Shipping and click the button SAVE.
[ 428 ]
Notification Serverless Application Chapter 9
Now, if we verify the order customer's email again we should have got another email
confirming that the order has been shipped:
Summary
In this chapter, you have learned a bit more about serverless functions architecture, how to
build a notification service using the web framework Flask, and how to deploy the final
application to AWS Lambda using the great project Zappa.
Then, you learned how to install, configure, and use the AWS CLI tool, and used it to
upload files to an AWS S3 bucket.
We also learned how to integrate the web application that we developed in Chapter
7, Online Video Game Store with Django, and the order microservice that we developed in
Chapter 8, Order Microservice, with the serverless notification application.
[ 429 ]
Other Books You May Enjoy
If you enjoyed this book, you may be interested in these other books by Packt:
ISBN: 978-1-78588-111-4
Other Books You May Enjoy
[ 431 ]
Other Books You May Enjoy
[ 432 ]
Index
[ 434 ]
35, 36 environment, setting up 49, 50
weekend weather forecast, getting 43, 46, 47 RPC (Remote Procedure Calls) 187
passwords
storing, Bcrypt used 239 S
storing, in database 238 S3 bucket
pgAdmin creating 407
reference 235 service models
PhantomJS 10 creating 345, 347
player, Spotify service URLs
creating 85, 86 setting up 376, 380, 383, 387
DataManager class, creating 95, 96, 97, 99 services
menu panel, creating 92, 93, 94 splitting 249, 251
menu panel, implementing 89, 90, 91 shopping cart model
menus, adding for albums and track selection 88, creating 328
89 form, creating 331
music, listening to 99, 100, 103, 106 items, adding 337, 340
Postgres dependency view, creating 334
creating 228 Simple Email Service
Postgres Docker container, starting 228 configuring 405
user dependency, creating 230 emails, registering 406
user model, creating 229 Single Responsibility Principle 187
project structure, Django Spotify app
exploring 281 about 48
package directory 283 configuration file reader, implementing 58, 59
SQLite, exploring 282 configuration file, creating 56, 57
Pyenv creating 52, 53, 55
reference 189 player, creating 85
Python Redis client SQLAlchemy
installing 198 reference 230
R T
RabbitMQ 188 TempMessenger
RabbitMQ container goals 186, 227
starting 189 requirements 186, 227
Redis Dependency Provider test files
client, designing 200 creating 355
Dependency Provider, creating 201 test
Message Service, creating 202 creating 354
summarizing 203 Twitter voting application
Redis building 132, 133, 134, 135, 136, 137
about 197 code, enhancing 137, 138, 140, 141, 143, 145,
container, starting 197 146, 147, 148, 151
reference 268 Twitter
using 198 about 112
remote-control application, with Spotify
[ 435 ]
application, creating 116, 118 parsers, loading dynamically 10, 11, 12
authentication, performing 123, 124 weather application
configuration file, adding 119, 120, 121, 123 ArgumentParser, users input getting with 20, 22,
environment, setting up 113, 114, 116 23, 25, 26
core functionality 10
U data, fetching from weather website 19, 20
user authentication environment, setting up 8, 10
password, authenticating 247 parser, creating 27, 28, 29
users, retrieving from database 246 web API, Spotify
user passwords application, authorizing with authorization code
handling 241, 243 flow 71, 73, 75
users authenticating with 63
authenticating 246 authorization code flow, implementing 68, 69, 70
creating 232 client credentials flow, implementing 64, 65, 66,
service, creating 232, 238 67, 68
querying 77, 78, 81, 83, 85
V web sessions
about 256
views
adding 372
users, logging in 264, 266
creating 370
users, logging out 263, 264
virtualenv
installation link 190
Z
W Zappa
reference 415
weather application, core functionality
used, for deploying notification serverless
model, creating 12, 14, 17, 19
application 415
|
https://www.scribd.com/document/383291919/Python-Programming-Blueprints
|
CC-MAIN-2019-35
|
refinedweb
| 78,644
| 52.49
|
Introduction : Applets are
small Java programs that are embedded in Web pages. They can be transported over
the Internet from one computer (web server) to another (client computers). They
transform the web into rich media and support the delivery of applications via the
Internet. It is also a special Java program that can be embedded in HTML
documents. A Java applet is a Java program written in a special format to have a
graphical user interface. The graphical user interface is also called a GUI ,
and it allows a user to interact with a program by clicking the mouse, typing
information into boxes, and performing other familiar actions. With a Java
applet, GUIs are easy to create even if you've never run into such GUI before.
Life Cycle Of An Applet : These are the different stages involved in the
life cycle of an applet:
Initialization State
Running state
Idle or stopped state
Dead state
Display state
Applet Life Cycle
Initialization State : This state is the first state of the applet life
cycle. An applet is created by the method init(). This method initializes the
created applet. It is Called exactly once in an applet's life when applet is
first loaded, which is after object creation, e.g. when the browser visits the
web page for the first time.Used to read applet parameters, start downloading
any other images or media files, etc. Init() method should be overrided in our
applet.
General form is: Public void init()
{ bgColor = Color.cyan; setBackground(bgColor);
} Running State : This state is the second stage of the applet life
cycle. This state comes when start() method is called. Called at least
once.Called when an applet is started or restarted, i.e., whenever the browser
visits the web page.
General form is : Public void start()
{ super.start();
} Idle or Stopped State : This state is the third stage of the applet
life cycle. This state comes when stop() method is called implicitly or
explicitly.stop() method is called implicitly. It
is called at least once when the browser leaves the web page when we move from
one page to another. This method is called only in the running state and can be
called any number of times.
It should be overrided in our applet.
General form: Public void stop()
{ super.stop(); } Dead State : This state is the fourth stage of the applet life cycle. This
state comes when destroy() method is called. In this state the applet is
completely removed from the memory. It called exactly once when the browser
unloads the applet.Used to perform any final clean-up. It occurs only once in
the life cycle. It should be overrided in our applet.
General form: Public void destroy()
{ super.destroy(); }
Display State : This state
is the fifth stage of the applet life cycle. This state comes when use s the
applet displays something on the screen. This is achieved by calling paint()
method.Paint() method can be called any number of times.This can be called only
in the running state.This method is a must in all applets. It should be
overrided in our applet.
General form: Public void paint(Graphics
obj)
{ super.paint(g);
} Creating Simple Application of Applet : Here we create two applications to
understand the applet working.
App.java : In this
application we simple print the "Hello Apllet world".
import
java.applet.Applet; import java.awt.*; public class app extends
Applet
{ Color bgColor; public void init() { bgColor = Color.cyan; setBackground(bgColor); } public void stop() {} public void paint(Graphics g) { g.drawString("Hello,Applet world!", 20,15); g.drawArc(50,40,30,30,0,360); }
} AppletApplication.java : In this application we make arectangle and fill
it with color. import java.awt.*; import java.applet.*; public class AppletApplication
extends Applet
{ Font bigFont; Color redColor; Color weirdColor; Color bgColor; public void init() { bigFont = new Font("Arial",Font.BOLD,16); redColor = Color.red; weirdColor = new Color(60,60,122); bgColor = Color.cyan; setBackground(bgColor); } public void stop() { } public void paint(Graphics
g) { g.setFont(bigFont); g.drawString("Shapes and Colors",80,20); g.setColor(redColor); g.drawRect(100,100,100,100); g.fillRect(110,110,80,80); g.setColor(weirdColor); g.fillArc(120,120,60,60,0,360); g.setColor(Color.yellow); g.drawLine(140,140,160,160); g.setColor(Color.black); }
}
Run the Application : Run
it on the browser. OUTPUT :
App.java :
ApplicationApplet :
View All
|
http://www.c-sharpcorner.com/UploadFile/0d4935/describing-the-life-cycle-of-applet/
|
CC-MAIN-2017-51
|
refinedweb
| 733
| 60.01
|
Comment on Tutorial - How to use ArrayList in Java By Hong
Comment Added by : Lionpam
Comment Added at : 2017-05-05 09:02:36
Comment on Tutorial : How to use ArrayList in Java By Hong
Lionp. java.lang.NoSuchMethodError: main
<
View Tutorial By: mark at 2010-09-27 03:46:48
2. Simple and easy code..........
View Tutorial By: mandalson at 2011-12-24 04:08:12
3. Nice Article....
View Tutorial By: Vipin Joshi at 2008-04-13 15:35:42
4. import java.lang.*;
import java.io.*;
View Tutorial By: satya at 2012-12-09 10:57:28
5. Good
View Tutorial By: Siva Sreekanth at 2013-10-01 16:29:55
6. fitst read fully and put comments
View Tutorial By: prasant at 2009-10-07 06:16:19
7. Great explanations! I looked for other guides and
View Tutorial By: A.Lepe at 2010-09-15 21:36:42
8. Wow Its awesome.
Thank you for giving such
View Tutorial By: sukumar maji at 2010-07-25 12:47:30
9. i have using struts tag in jsp ,
i have us
View Tutorial By: sachin khatode at 2008-11-11 01:24:33
10. HI,
I want to send an sms via website to mo
View Tutorial By: Hemant at 2008-11-04 05:26:30
|
http://java-samples.com/showcomment.php?commentid=41065
|
CC-MAIN-2019-04
|
refinedweb
| 220
| 76.01
|
Headless
Headless is the Ruby interface for Xvfb. It allows you to create a headless display straight from Ruby code, hiding the low-level action. It can also capture images and video from the virtual framebuffer. For example, you can record screenshots and screencasts of your failing integration specs.
I created it so I can run Selenium tests in Cucumber without any shell scripting. Even more, you can go headless only when you run tests against Selenium.
Other possible uses include pdf generation with
wkhtmltopdf, or screenshotting.
Documentation is available at rubydoc.info
Note: Headless will NOT hide most applications on OS X. Here is a detailed explanation
Installation
On Debian/Ubuntu:
sudo apt-get install xvfb gem install headless
Usage
Block mode:
require 'rubygems' require 'headless' require 'selenium-webdriver' Headless.ly do driver = Selenium::WebDriver.for :firefox driver.navigate.to '' puts driver.title end
Object mode:
require 'rubygems' require 'headless' require 'selenium-webdriver' headless = Headless.new headless.start driver = Selenium::WebDriver.for :firefox driver.navigate.to '' puts driver.title headless.destroy
Cucumber
Running cucumber headless is now as simple as adding a before and after hook in
features/support/env.rb:
# change the condition to fit your setup if Capybara.current_driver == :selenium require 'headless' headless = Headless.new headless.start end
Running tests in parallel
If you have multiple threads running acceptance tests in parallel, you want to spawn Headless before forking, and then reuse that instance with
destroy_at_exit: false.
You can even spawn a Headless instance in one ruby script, and then reuse the same instance in other scripts by specifying the same display number and
reuse: true.
# spawn_headless.rb Headless.new(display: 100, destroy_at_exit: false).start # test_suite_that_could_be_ran_multiple_times.rb Headless.new(display: 100, reuse: true, destroy_at_exit: false).start # reap_headless.rb headless = Headless.new(display: 100, reuse: true) headless.destroy # kill_headless_without_waiting.rb headless = Headless.new headless.destroy_without_sync
There's also a different approach that creates a new virtual display for every parallel test process - see this implementation by @rosskevin.
Cucumber with wkhtmltopdf
Note: this is true for other programs which may use headless at the same time as cucumber is running
When wkhtmltopdf is using Headless, and cucumber is invoking a block of code which uses a headless session, make sure to override the default display of cucumber to retain browser focus. Assuming wkhtmltopdf is using the default display of 99, make sure to set the display to a value != 99 in
features/support/env.rb file. This may be the cause of
Connection refused - connect(2) (Errno::ECONNREFUSED).
headless = Headless.new(:display => '100') headless.start
Capturing video
Video is captured using
ffmpeg. You can install it on Debian/Ubuntu via
sudo apt-get install ffmpeg or on OS X via
brew install ffmpeg. You can capture video continuously or capture scenarios separately. Here is typical use case:
require 'headless' headless = Headless.new headless.start Before do headless.video.start_capture end After do |scenario| if scenario.failed? headless.video.stop_and_save("/tmp/#{BUILD_ID}/#{scenario.name.split.join("_")}.mov") else headless.video.stop_and_discard end end
Video options
When initiating Headless you may pass a hash with video options.
headless = Headless.new(:video => { :frame_rate => 12, :codec => 'libx264' })
Available options:
- :codec - codec to be used by ffmpeg
- :frame_rate - frame rate of video capture
- :provider - ffmpeg provider - either :libav (default) or :ffmpeg
- :provider_binary_path - Explicit path to avconv or ffmpeg. Only required when the binary cannot be discovered on the system $PATH.
- :pid*file_path - path to ffmpeg pid file, default: "/tmp/.headless_ffmpeg*#@display.pid"
- :tmp*file_path - path to tmp video file, default: "/tmp/.headless_ffmpeg*#@display.mov"
- :log_file_path - ffmpeg log file, default: "/dev/null"
- :extra - array of extra ffmpeg options, default: []
Taking screenshots
Call
headless.take_screenshot to take a screenshot. It needs two arguments:
- file_path - path where the image should be stored
- options - options, that can be: :using - :imagemagick or :xwd, :imagemagick is default, if :imagemagick is used, image format is determined by file_path extension
Screenshots can be taken by either using
import (part of
imagemagick library) or
xwd utility.
import captures a screenshot and saves it in the format of the specified file. It is convenient but not too fast as
it has to do the encoding synchronously.
xwd will capture a screenshot very fast and store it in its own format, which can then be converted to one
of other picture formats using, for example, netpbm utilities -
xwdtopnm <xwd_file> | pnmtopng > capture.png.
To install the necessary libraries on ubuntu:
import - run
sudo apt-get install imagemagick
xwd - run
sudo apt-get install X11-apps and if you are going to use netpbm utilities for image conversion -
sudo apt-get install netpbm
Troubleshooting
/tmp/.X11-unix is missing
Xvfb requires this directory to exist. It cannot be created automatically, because the directory must be owned by the root user. (You will never get this error if running as root - for example, in a Docker container.)
On macOS, the directory will be created when you run XQuartz.app. But since
/tmp is cleared on reboot, you will need to open XQuartz.app after a reboot before running Xvfb. (You don't need to leave it running.)
To create this directory manually, on either macOS or Linux:
mkdir /tmp/.X11-unix sudo chmod 1777 /tmp/.X11-unix sudo chown root /tmp/.X11-unix/
Note that you may need to run these commands after every reboot, too.
Display socket is taken but lock file is missing
This means that there is an X server that is taking up the chosen display number, but its lock file is missing. This is an exceptional situation. Please stop the server process manually (
pkill Xvfb) and open an issue.
Video not recording
If video is not recording, and there are no visible exceptions, try passing the following option to Headless to figure out the reason:
Headless.new(video: {log_file_path: STDERR}). In particular, there are some issues with the version of avconv packaged with Ubuntu 12.04 - an outdated release, but still in use on Travis.
Contributors
© 2011-2015 Leonid Shevtsov, released under the MIT license
|
https://www.rubydoc.info/github/leonid-shevtsov/headless
|
CC-MAIN-2019-04
|
refinedweb
| 1,003
| 50.12
|
My original plan was it to write in this post about the next rules to error handling. But I changed my plan to write about the future: contracts in C++20.
By Fabuio - Own work, CC0, Link
Here are the rules I will skip.
E.8: State your postconditions
Why did I change my plan? I did it for a few reasons.
The consequence of this points is quite simple. Contracts seem to be important for error handling, C++20 will presumably have contracts, therefore, I write in this post about contracts in C++20.
In case you want to have more details to contracts. This post is based on the proposals P0380R1 and P0542R5.
First of all.
A contract specifies in a precise and checkable way interfaces for software components. This software components are typically functions and methods, that have to fulfil preconditions, postconditions, and invariants. Here are the shortened definitions from the proposals.
The precondition and the postconditon is in C++20 placed outside the function defintion but the invariant is placed inside the function definition. A predicate is a function which returns a boolean.
int push(queue& q, int val)
[[ expects: !q.full() ]]
[[ ensures !q.empty() ]]{
...
[[assert: q.is_ok() ]] ...
}
The attribute expects is a precondition, the attribute ensures is a postcondition, and the attribute assert is an assertion.
The contracts for the function push are that the queue is not full before adding an element, that is not empty after adding and the assertion q.is_ok() holds.
Preconditions and postconditions are part of the function interface. This means they can't access local members of a function or private or protected members of a class. In contrast, assertions are part of the implementation and can, therefore, access local members of a function of private or protected members of a class.
class X {
public:
void f(int n)
[[ expects: n<m ]] // error; m is private
{
[[ assert: n<m ]]; // OK
// ...
}
private:
int m;
};
m is private and can, therefore, not be part of a precondition.
By default, a violation of a contract terminates the program. This is not the full story, let me give you more details.
Here is the full syntax of the contract attributes: [[contract-attribute modifier: conditional-expression ]]
For the ensures attribute, there is an additional identifier available. [[ensures modifier identifier: conditional-expression ]]
The identifier let you refer to the return value of the function.
int mul(int x, int y)
[[expects: x > 0]] // implicit default
[[expects default: y > 0]]
[[ensures audit res: res > 0]]{
return x * y;
}
res as the identifier is, in this case, an arbitrary name. As shown in the example, you can use more contracts of the same kind.
Let me dive deeper into the modifiers and the handling of the contract violations.
A compilation has three assertion build levels:
If a contract violation occurs - that means the predicate evaluates to false -, the violation handler is invoked. The violation handler is a function of type noexcept which takes a const std::contract_violation and returns a void. Because the function is noexcept, this means that std::terminate is called in case of a violation of the contract. A user can set a violation handler.
The class std::contract_violation gives information about the violation of the contract.
namespace std{
class contract_violation{
public:
uint_least32_t line_number() const noexcept;
string_view file_name() const noexcept;
string_view function_name() const noexcept;
string_view comment() const noexcept;
string_view assertion_level() const noexcept;
};
}
There are a few rules to keep in mind if you declare a contract.
A contract can be placed on the declaration of a function. This includes declarations of virtual functions or function templates.
int f(int x)
[[expects: x>0]]
[[ensures r: r>0]];
int f(int x); // OK. No contract.
int f(int x)
[[expects: x>=0]]; // Error missing ensures and different expects condition
struct B{
virtual void f(int x)[[expects: x > 0]];
virtual void g(int x);
}
struct D: B{
void f(int x)[[expects: x >= 0]]; // error
void g(int x)[[expects: x != 0]]; // error
};
Both contract definitions of class D are erroneous. The contract of the method f differs from the one from B::f. The method D::g adds a contract to B::g.
Impressed? Me too! I still can not imagine how fundamentally contracts will change the way we write functions and think about interfaces and exception handling. Maybe Herb Sutter's thoughts on Sutter's Mill give you an idea because for him "contracts is the most impactful feature of C++20 so far, and arguably the most impactful feature we have added to C++ since C++11."
With my next post, I will continue with a step back to the present time and write about the rules to exception handling.
Wow! Almost 200 readers participated in the vote to the next pdf bundle. Here are the winners.
I need at least a week to proofread and prepare the pdf bundles12
All 1580548
Currently are 129 guests and no members online
Kubik-Rubik Joomla! Extensions
Read more...
Read more...
|
http://www.modernescpp.com/index.php/c-core-guidelines-a-detour-to-contracts
|
CC-MAIN-2019-09
|
refinedweb
| 836
| 63.8
|
Name | Synopsis | Description | Return Values | Errors | Attributes | See Also | Notes
#include <signal.h> int sigaltstack(const stack_t *restrict ss, stack_t *restrict oss);
The sigaltstack() function allows a thread to define and examine the state of an alternate stack area on which signals are processed. If ss is non-zero, it specifies a pointer to and the size of a stack area on which to deliver signals, and informs the system whether the thread is currently executing on that stack. When a signal's action indicates its handler should execute on the alternate signal stack (specified with a sigaction(2) call), the system checks whether the thread chosen to execute the signal handler is currently executing on that stack. If the thread is not currently executing on the signal stack, the system arranges a switch to the alternate signal stack for the duration of the signal handler's execution.
The stack_t structure includes the following members:
int *ss_sp long ss_size int ss_flags
If ss is not NULL, it points to a structure specifying the alternate signal stack that will take effect upon successful return from sigaltstack(). The ss_sp and ss_size members specify the new base and size of the stack, which is automatically adjusted for direction of growth and alignment. The ss_flags member specifies the new stack state and may be set to the following:
The stack is to be disabled and ss_sp and ss_size are ignored. If SS_DISABLE is not set, the stack will be enabled.
If oss is not NULL, it points to a structure specifying the alternate signal stack that was in effect prior to the call to sigaltstack(). The ss_sp and ss_size members specify the base and size of that stack. The ss_flags member specifies the stack's state, and may contain the)
The value SIGSTKSZ is defined to be the number of bytes that would be used to cover the usual case when allocating an alternate stack area. The value MINSIGSTKSZ is defined to be the minimum stack size for a signal handler. In computing an alternate stack size, a program should add that amount to its stack requirements to allow for the operating system overhead.
The following code fragment is typically used to allocate an alternate stack with an adjacent red zone (an unmapped page) to guard against stack overflow, as with default stacks:
#include <signal.h> #include <sys/mman.h> stack_t sigstk; sigstk.ss_sp = mmap(NULL, SIGSTKSZ, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); if (sigstk.ss_sp == MAP_FAILED) /* error return */; sigstk.ss_size = SIGSTKSZ; sigstk.ss_flags = 0; if (sigaltstack(&sigstk, NULL) < 0) perror("sigaltstack");SunOS 5.11 Last Revised 1 Nov 2003
Name | Synopsis | Description | Return Values | Errors | Attributes | See Also | Notes
|
http://docs.oracle.com/cd/E19082-01/819-2241/sigaltstack-2/index.html
|
CC-MAIN-2015-22
|
refinedweb
| 446
| 60.24
|
Now that you understand the elements of a .NET executable, let's talk about the services that the CLR provides to support management and execution of .NET assemblies. There are many fascinating components in the CLR, but for brevity, we will limit our discussions to just the major components, as shown in Figure 2-4.
The major components of the CLR include the class loader, verifier, JIT compilers, and other execution support, such as code management, security management, garbage collection, exception management, debug management, marshaling management, thread management, and so on. As you can see from Figure 2-4, your .NET PE files lay on top of the CLR and execute within the CLR's Virtual Execution System (VES), which hosts the major components of the runtime. Your .NET PE files will have to go through the class loader, the type verifier, the JIT compilers, and other execution support components before they will execute.
When you run a standard Windows application, the OS loader loads it before it can execute. At the time of this writing, the default loaders in the existing Windows operating systems, such as Windows 98, Windows Me, Windows 2000, and so forth, recognize only the standard Windows PE files. As a result, Microsoft has provided an updated OS loader for each of these operating systems that support the .NET runtime. The updated OS loaders know the .NET PE file format and can handle the file appropriately.
When you run a .NET application on one of these systems that have an updated OS loader, the OS loader recognizes the .NET application and thus passes control to the CLR. The CLR then finds the entry point, which is typically Main( ), and executes it to jump-start the application. But before Main( ) can execute, the class loader must find the class that exposes Main( ) and load the class. In addition, when Main( ) instantiates an object of a specific class, the class loader also kicks in. In short, the class loader performs its magic the first time a type is referenced.
The class loader loads .NET classes into memory and prepares them for execution. Before it can successfully do this, it must locate the target class. To find the target class, the class loader looks in several different places, including the application configuration file (.config) in the current directory, the GAC, and the metadata that is part of the PE file, specifically the manifest. The information that is provided by one or more of these items is crucial to locating the correct target class. Recall that a class can be scoped to a particular namespace, a namespace can be scoped to a particular assembly, and an assembly can be scoped to a specific version. Given this, two classes, both named Car, are treated as different types even if the version information of their assemblies are the same.
Once the class loader has found and loaded the target class, it caches the type information for the class so that it doesn't have to load the class again for the duration of this process. By caching this information, it will later determine how much memory is needed to allocate for the newly created instance of this class. Once the target class is loaded, the class loader injects a small stub, like a function prolog, into every single method of the loaded class. This stub is used for two purposes: to denote the status of JIT compilation and to transition between managed and unmanaged code. At this point, if the loaded class references other classes, the class loader will also try to load the referenced types. However, if the referenced types have already been loaded, the class loader has to do nothing. Finally, the class loader uses the appropriate metadata to initialize the static variables and instantiate an object of the loaded class for you.
Scripting and interpreted languages are very lenient on type usages, allowing you to write code without explicit variable declarations. This flexibility can introduce code that is extremely error-prone and hard to maintain, and that is often a culprit for mysterious program crashes. Unlike scripting and interpreted languages, compiled languages require types to be explicitly defined prior to their use, permitting the compiler to ensure that types are used correctly and the code will execute peacefully at runtime.
The key here is type safety, and it is a fundamental concept for code verification in .NET. Within the VES, the verifier is the component that executes at runtime to verify that the code is type safe. Note that this type verification is done at runtime and that this is a fundamental difference between .NET and other environments. By verifying type safety at runtime, the CLR can prevent the execution of code that is not type safe and ensure that the code is used as intended. In short, type safety means more reliability.
Let's talk about where the verifier fits within the CLR. After the class loader has loaded a class and before a piece of IL code can execute, the verifier kicks in for code that must be verified. The verifier is responsible for verifying that:
The metadata is well formed, meaning the metadata must be valid.
The IL code is type safe, meaning type signatures are used correctly.
Both of these criteria must be met before the code can be executed because JIT compilation will take place only when code and metadata have been successfully verified. In addition to checking for type safety, the verifier also performs rudimentary control-flow analysis of the code to ensure that the code is using types correctly. You should note that since the verifier is a part of the JIT compilers, it kicks in only when a method is being invoked, not when a class or assembly is loaded. You should also note that verification is an optional step because trusted code will never be verified but will be immediately directed to the JIT compiler for compilation.
JIT compilers play a major role in the .NET platform because all .NET PE files contain IL and metadata, not native code. The JIT compilers convert IL to native code so that it can execute on the target operating system. For each method that has been successfully verified for type safety, a JIT compiler in the CLR will compile the method and convert it into native code.
One advantage of a JIT compiler is that it can dynamically compile code that is optimized for the target machine. If you take the same .NET PE file from a one-CPU machine to a two-CPU machine, the JIT compiler on the two-CPU machine knows about the second CPU and may be able to spit out the native code that takes advantage of the second CPU. Another obvious advantage is that you can take the same .NET PE file and run it on a totally different platform, whether it be Windows, Unix, or whatever, as long as that platform has a CLR.
For optimization reasons, JIT compilation occurs only the first time a method is invoked. Recall that the class loader adds a stub to each method during class loading. At the first method invocation, the VES reads the information in this stub, which tells it that the code for the method has not been JIT-compiled. At this indication, the JIT compiler compiles the method and injects the address of the native method into this stub. During subsequent invocations to the same method, no JIT compilation is needed because each time the VES goes to read information in the stub, it sees the address of the native method. Because the JIT compiler only performs its magic the first time a method is invoked, the methods you don't need at runtime will never be JIT-compiled.
The compiled, native code lies in memory until the process shuts down and until the garbage collector clears off all references and memory associated with the process. This means that the next time you execute the process or component, the JIT compiler will again perform its magic.
If you want to avoid the cost of JIT compilation at runtime, you can use a special tool called ngen.exe, which compiles your IL during installation and setup time. Using ngen, you can JIT-compile the code once and cache it on the machine so that you can avoid JIT compilation at runtime (this process is referred to as pre-JITting). In the event that the PE file has been updated, you must PreJIT the PE file again. Otherwise, the CLR can detect the update and dynamically command the appropriate JIT compiler to compile the assembly.
By now, you should see that every component in the CLR that we've covered so far uses metadata and IL in some way to successfully carry out the services that it supports. In addition to the provided metadata and generated managed code, the JIT compiler must generate managed data that the code manager needs to locate and unwind stack frames.[12] The code manager uses managed data to control the execution of code, including performing stack walks that are required for exception handling, security checks, and garbage collection. Besides the code manager, the CLR also provides a number of important execution-support and management services. A detailed discussion of these services is beyond the scope of this book, so we will briefly enumerate a few of them here:
[12] By the way, you can write a custom JIT compiler or a custom code manager for the CLR because the CLR supports the plug-and-play of these components.
Unlike C++, where you must delete all heap-based objects manually, the CLR supports automatic lifetime management for all .NET objects. The garbage collector can detect when your objects are no longer being referenced and perform garbage collection to reclaim the unused memory.
Prior to .NET, there was no consistent method for error or exception handling, causing lots of pain in error handling and reporting. In .NET, the CLR supports a standard exception-handling mechanism that works across all languages, allowing every program to use a common error-handling mechanism. The CLR exception-handling mechanism is integrated with Windows Structured Exception Handling (SEH).
The CLR performs various security checks at runtime to make sure that the code is safe to execute and that the code is not breaching any security requirements. In addition to supporting code access security, the security engine also supports declarative and imperative security checks. Declarative security requires no special security code, but you have to specify the security requirements through attributes or administrative configuration. Imperative security requires that you write the code in your method to specifically cause security checks..
The CLR supports interoperation between the managed (CLR) and unmanaged (no CLR) worlds. The COM Interop facility serves as a bridge between COM and the CLR, allowing a COM object to use a .NET object, and vice versa. The Platform Invoke (P/Invoke) facility allows you to call Windows API functions.
This is by no means an exhaustive list. The one thing that we want to reiterate is that like the class loader, verifier, JIT compiler, and just about everything else that deals with .NET, these execution-support and management facilities all use metadata, managed code, and managed data in some way to carry out their services.
|
http://etutorials.org/Programming/.NET+Framework+Essentials/Chapter+2.+The+Common+Language+Runtime/2.7+CLR+Execution/
|
CC-MAIN-2018-05
|
refinedweb
| 1,897
| 51.48
|
This year’s Balisage conference was preceded by the international symposium on Native XML User Interfaces, which naturally enough centered around XForms.
As someone who’s written multiple articles surveying XForms implementations, I have to say that it’s fantastic to finally see one break out of the pack. Nearly every demo I saw in Montreal used XSLTForms if it used XForms at all. And yet, one participant I conversed with afterwards noted that very little that transpired at the symposium couldn’t have been done ten years ago.
It’s safe to say I have mixed emotions about XForms. One one hand, watching how poorly the browser makers have treated all things XML, I sometimes muse about what it would look like if we started fresh today. If we were starting anew, a namespace-free specification might be a possibility. But with XForms 2.0 around the corner, it’s probably more fruitful to muse about implementations. Even though XSLTForms is awesome, I still want more. :-)
- A stronger JavaScript interface. It needs to be possible to incrementally retrofit an existing page using POHF (plain old HTML forms) toward using XForms in whole or in part. We need an obvious mapping from XForms internals to HTML form controls.
- Better default UI. I still see InfoPath as the leader here. Things designed in that software just look fantastic, even if quickly tossed together.
- Combining the previous two bullets, the UI needs to be more customizable, and easier so. It needs to be utterly straightforward to make XForms parts of pages fit in with non-XForms parts of pages.
- Rich text: despite several assertions during the week, XForms can actually handle mixed text, just not very well. One of the first demo apps (in the DENG engine–remember that?) was an HTML editor. The spec is explicitly designed in such a way as to allow new and exciting forms widgets, and a mixed-content widget would be A Big Deal, if done well.
- Moar debugging tools
During the main conference, Michael Kay demonstrated Saxon-CE, an impressive tour-de-force in routing around the damage that is browser vendors’ attitudes toward XML. And though he didn’t make a big deal of it, it’s now available freely under an open source license. This just might change everything.
Curious about what others think here–I welcome your comments.
-m
|
http://dubinko.info/blog/2013/08/
|
CC-MAIN-2020-34
|
refinedweb
| 397
| 65.12
|
I am trying to include my constants which are placed in a
separate file. There are quite a number of these constants
defined as shown below :
use constant IP_ADDR = '192.345.786.897'; # as an example
Coming from a C/C++ background where these constants are
kept in a header file and included at compile time and not at run time. All I get is bare words. It works fine if it is in the same file but not in a separate one. I tried creating a module with no success for handling purely constants. Would appreciate any help. Thanks
You need to use the Exporter module in your module, and use the constant-holding module in your main program.
package Constants:
use strict;
use vars qw( @ISA @EXPORT_OK );
require Exporter;
@ISA = qw( Exporter );
use constant IP_ADDR = '192.34.56.78';
# and in another file
use Constants qw( IP_ADDR );
[download]'
If you define module with constants you should use Exporter to export them into the namespace of your script. For example:
package MyConstants;
use base qw(Exporter);
our @EXPORT = qw(CONST1 CONST2);
use constant CONST1 => 12356;
use constant CONST2 => 'xxx';
1;
[download]
In this example all constants are exported by default but you may want to make it optional. See Exporter documentation for details.
Simple script which uses these constants:
use MyConstants;
use strict;
use warnings;
print CONST1;
[download]
All I get is bare words.
What leads me to idea that you should use strict and warnings. It would catch this as error.
--
Ilya Martynov, ilya@iponweb.net
CTO IPonWEB (UK) Ltd
Quality Perl Programming and Unix Support
UK managed @ offshore prices -
Personal website -
Because said subroutine only exists in the namespace of your header file, your main program cannot access it. There are however a number of ways for your program to access this constant. Assuming header.pm contains your constants, and program.pl is your script
package header;
@ISA=('Exporter');
@EXPORT=('camel');
use constant camel => 'flea-ridden';
1; # I'm a well-behaving module
[download]
# program.pl
use header;
*header::camel=*::camel;
print &camel;
# Note that you have to call camel as a function here.
[download]
CURobartes-
package MyConfig;
sub new
{
my $proto = shift;
my $class = ref($proto) || $proto;
my $config =
{
"Servers to poll" =>
{
# host login password
"theophyline" => { "admin" => "secret" },
"caffeine" => { "admin" => "buzzword" },
"theobromine" => { "admin" => "mystery" },
},
"times to poll" =>
{
"3:00 AM",
"4:21 PM",
},
};
bless($config, $class);
return $config;
}
"the end";
[download]
use MyConfig;
my $externalConfig = MyConfig->new();
foreach my $server
(keys %{$externalConfig->{'Servers to poll'}})
{
my ($login, $password) =
each %{$externalConfig->{'Servers to poll'}->{$server}};
# etc....
}
[download]
Yes
No
Other opinion (please explain)
Results (99 votes),
past polls
|
http://www.perlmonks.org/index.pl/jacques?node_id=212508
|
CC-MAIN-2015-40
|
refinedweb
| 441
| 61.77
|
There is a lot of confusion about how to set up and use global hook functions. This essay attempts to clear up some of these issues.
It may be worth pointing out that Flounders disapprove of hooks in general, but these hooks are felt to be acceptable.
Note that none of the problems described below occur if you are simply hooking operations from your own process. This only happens if you want to get events system-wide.
The key problem here is address space. When a global DLL executes, it executes in the context of the process whose event it is hooking. This means that the addresses it sees even for its own variables are addresses in the context of the target process. Since this is a DLL, it has a private copy of its data for every process that is using it, which means that any values you set in variables global in the DLL (such as those declared at file-level) are private variables, and will not inherit anything from the original DLL's context. They are going to be initialized anew, meaning, typically, they will be zero.
A recent post even suggested the notion of storing a callback address in the DLL. This is impossible. Well, it is not impossible to store it, but it is impossible to use it. What you've stored is a bunch of bits. Even if you follow the instructions below to create a shared memory variable that is visible to all instances of the DLL, the bunch of bits (which you think is an address) is actually meaningful as an address only in the context of the process that stored it. For all other processes, this is merely a bunch of bits, and if you try to use it as an address, you will call some address in the process whose event is being intercepted, which is completely useless. It will most likely just cause the app to crash.
This concept of separate address spaces is a hard concept to grasp. Let me use a picture to illustrate it.
What we have here are three processes. Your process is shown on the left. The DLL has code, data, and a shared segment, which we'll talk about how to do later. Now when the hook DLL executes to intercept an event for Process A, it is mapped into Process A's address space as shown. The code is shared, so the addresses in Process A refer to the same pages as the addresses in Your Process. Coincidentally, they happen to be relocated into Process A at the same virtual addresses, meaning the addresses process A sees. Process A also gets its very own private copy of the data segment, so anything in "Data" that Process A sees is completely private to Process A, and cannot affect any other process (or be affected by another process!). However, the trick that makes this all work is the shared data segment, shown here in red. The pages referred to by Your Process are exactly the same memory pages referred to in Process A. Note that coincidentally, these pages happen to appear in Process A's address space in exactly the same virtual addresses as in Your Process. If you were sitting debugging Your Process and Process A concurrently (which you can do with two copies of VC++ running!), if you looked at &something that was in the shared data segment, and looked at it in Your Process and then at the same &something in Process A, you would see exactly the same data, even at the same address. If you used the debugger to change, or watched the program change, the value of something, you could go over to the other process, examine it, and see that the new value appeared there as well.
&something
something
But here's the kicker: the same address is a coincidence. It is absolutely, positively, not guaranteed. Take a look at Process B. When the event is hooked in Process B, the DLL is mapped in. But the addresses it occupied in Your Process and Process A are not available in Process B's address space. So all that happens is the code is relocated into a different address in Process B. The code is happy; it actually doesn't care what address it is executing at. The data addresses are adjusted to refer to the new position of the data, and even the shared data is mapped into a different set of addresses, so it is referenced differently. If you were running the debugger in Process B and looked at &something in the shared area, you would find that the address of something was different, but the contents of something would be the same; making a change in the contents in Your Process or Process A would immediately make the change visible in Process B, even though Process B sees it at a different address. It is the same physical memory location. Virtual memory is a mapping between the addresses you see as a programmer and the physical pages of memory that actually comprise your computer.
While I've referred to the similar placement as a coincidence, the "coincidence" is a bit contrived; Windows attempts whenever possible to map DLLs into the same virtual location as other instances of the same DLL. It tries. It may not be able to succeed.
If you know a little bit (enough to be dangerous), you can say, Aha! I can rebase my DLL so that it loads at an address that does not conflict, and I'll be able to ignore this feature. This is a prime example of a little knowledge being a dangerous thing. You cannot guarantee this will work in every possible executable that can ever run on your computer! Because this is a global hook DLL, it can be invoked for Word, Excel, Visio, VC++, and six thousand applications you've never heard of, but you might run someday or your customers might run. So forget it. Don't try rebasing. You will lose, eventually. Usually at the worst possible time, with your most important customer (for example, the magazine reviewer of your product, or your very best dollar-amount customer who is already nervous about other bugs you may have had...) Assume that the shared data segment is "moveable". If you didn't understand this paragraph, you don't know enough to be dangerous, and you can ignore it.
There are other implications to this relocation. In the DLL, if you had stored a pointer to a callback function in Your Process, it is meaningless for the DLL to execute it in Process A or Process B. The address will cause a control transfer to the location it designates, all right, but that transfer will happen into Process A or Process B's address space, which is pretty useless, not to mention almost certainly fatal.
It also means you can't use any MFC in your DLL. It can't be an MFC DLL, or an MFC Extension DLL. Why? Because it would call MFC functions. Where are they? Well, they're in your address space. Not in the address space of Process A, which is written in Visual Basic, or Process B, which is written in Java. So you have to write a straight-C DLL, and I also recommend ignoring the entire C runtime library. You should only use the API. Use lstrcpy instead of strcpy or tcscpy, use lstrcmp instead of strcmp or tcscmp, and so on.
lstrcpy
strcpy
tcscpy
lstrcmp
strcmp
tcscmp
There are many solutions to how your DLL communicates to its controlling server. One solution is to use ::PostMessage or ::SendMessage (note that I refer here to the raw API calls, not MFC calls!) Whenever it is possible to use ::PostMessage, use it in preference to ::SendMessage, because you can get nasty deadlocks. If Your Process stops, eventually, every other process in the system will stop because everyone is blocked on a ::SendMessage that will never return, and you've just taken the entire system down, with potential serious lossage of data in what the user sees as critical applications. This is Most Decidedly Not A Good Thing.
::PostMessage
::SendMessage
You can also use queues of information in the shared memory area, but I'm going to consider that topic outside the scope of this essay.
In the ::SendMessage or ::PostMessage, you cannot pass back a pointer (we'll ignore the issue of passing back relative pointers into the shared memory area; that's also outside the scope of this essay). This is because any pointer you can generate is either going to be referring to an address in the DLL (as relocated into the hooked process) or an address in the hooked process (Process A or Process B) and hence is going to be completely useless in Your Process. You can only pass back address-space- independent information in the WPARAM or LPARAM.
WPARAM
LPARAM
I strongly suggest using Registered Window Messages for this purpose (see my essay on Message Management). You can use the ON_REGISTERED_MESSAGE macro in the MESSAGE_MAP of the window you send or post the message to.
ON_REGISTERED_MESSAGE
MESSAGE_MAP
Getting the HWND of that window in is now the major requirement. Fortunately, this is easy.
HWND
The first thing you have to do is create the shared data segment. This is done by using the #pragma data_seg declaration. Pick some nice mnemonic data segment name (it must be no more than 8 characters in length). Just to emphasize the name is arbitrary, I've used my own name here. I've found that in teaching, if I use nice names like .SHARE or .SHR or .SHRDATA, students assume that the name has significance. It doesn't.
#pragma data_seg
.SHR
.SHRDATA
#pragma data_seg(".JOE")
HANDLE hWnd = NULL;
#pragma dta_seg()
#pragma comment(linker, "/section:.JOE,rws")
Any variables you declare in the scope of the #pragma that names a data segment will be assigned to the data segment, providing they are initialized. If you fail to have an initializer, the variables will be assigned to the default data segment and the #pragma has no effect.
#pragma
It appears at the moment that this precludes using arrays of C++ objects in the shared data segment, because you cannot initialize a C++ array of user-defined objects (their default constructors are supposed to do this). This appears to be a fundamental limitation, an interaction between formal C++ requirements and the Microsoft extensions that require initializers be present.
The #pragma comment causes the linker to have the command line switch shown added to the link step. You could go into the VC++ Project | Settings and change the linker command line, but this is hard to remember to do if you are moving the code around (and the usual failure is to forget to change the settings to All Configurations and thus debug happily, but have it fail in the Release configuration. So I find it best to put the command directly in the source file. Note that the text that follows must conform to the syntax for the linker command switch. This means you must not have any spaces in the text shown, or the linker will not parse it properly.
#pragma comment
You typically provide some mechanism to set the window handle, for example
void SetWindow(HWND w)
{
hWnd = w;
}
although this is often combined with setting the hook itself as I will show below.
The functions setMyHook and clearMyHook must be declared here, but this is explained in my essay on The Ultimate DLL Header File.
setMyHook
clearMyHook
#define UWM_MOUSEHOOK_MSG \
_T("UMW_MOUSEHOOK-" \
"{B30856F0-D3DD-11d4-A00B-006067718D04}")
#include "stdafx.h"
#include "myhook.h"
#pragma data_seg(".JOE")
HWND hWndServer = NULL;
#pragma data_seg()
#pragma comment("linker, /section:.JOE,rws")
HINSTANCE hInstance;
UINT HWM_MOUSEHOOK;
HHOOK hook;
// Forward declaration
static LRESULT CALLBACK msghook(int nCode, WPARAM wParam, LPARAM lParam);
/****************************************************************
* DllMain
* Inputs:
* HINSTANCE hInst: Instance handle for the DLL
* DWORD Reason: Reason for call
* LPVOID reserved: ignored
* Result: BOOL
* TRUE if successful
* FALSE if there was an error (never returned)
* Effect:
* Initializes the DLL.
****************************************************************/
BOOL DllMain(HINSTANCE hInst, DWORD Reason, LPVOID reserved)
{
switch(Reason)
{ /* reason */
//**********************************************
// PROCESS_ATTACH
//**********************************************
case DLL_PROCESS_ATTACH:
// Save the instance handle because we need it to set the hook later
hInstance = hInst;
// This code initializes the hook notification message
UWM_MOUSEHOOK = RegisterWindowMessage(UWM_MOUSEHOOK_MSG);
return TRUE;
//**********************************************
// PROCESS_DETACH
//**********************************************
case DLL_PROCESS_DETACH:
// If the server has not unhooked the hook, unhook it as we unload
if(hWndServer != NULL)
clearMyHook(hWndServer);
return TRUE;
} /* reason */
/****************************************************************
* setMyHook
* Inputs:
* HWND hWnd: Window whose hook is to be set
* Result: BOOL
* TRUE if the hook is properly set
* FALSE if there was an error, such as the hook already
* being set
* Effect:
* Sets the hook for the specified window.
* This sets a message-intercept hook (WH_GETMESSAGE)
* If the setting is successful, the hWnd is set as the
* server window.
****************************************************************/
__declspec(dllexport) BOOL WINAPI setMyHook(HWND hWnd)
{
if(hWndServer != NULL)
return FALSE;
hook = SetWindowsHookEx(
WH_GETMESSAGE,
(HOOKPROC)msghook,
hInstance,
0);
if(hook != NULL)
{ /* success */
hWndServer = hWnd;
return TRUE;
} /* success */
return FALSE;
} // SetMyHook
/****************************************************************
* clearMyHook
* Inputs:
* HWND hWnd: Window whose hook is to be cleared
* Result: BOOL
* TRUE if the hook is properly unhooked
* FALSE if you gave the wrong parameter
* Effect:
* Removes the hook that has been set.
****************************************************************/
__declspec(dllexport) BOOL clearMyHook(HWND hWnd)
{
if(hWnd != hWndServer)
return FALSE;
BOOL unhooked = UnhookWindowsHookEx(hook);
if(unhooked)
hWndServer = NULL;
return unhooked;
}
/****************************************************************
* msghook
* Inputs:
* int nCode: Code value
* WPARAM wParam: parameter
* LPARAM lParam: parameter
* Result: LRESULT
*
* Effect:
* If the message is a mouse-move message, posts it back to
* the server window with the mouse coordinates
* Notes:
* This must be a CALLBACK function or it will not work!
****************************************************************/
static LRESULT CALLBACK msghook(int nCode, WPARAM wParam, LPARAM lParam)
{
// If the value of nCode is < 0, just pass it on and return 0
// this is required by the specification of hook handlers
if(nCode < 0)
{ /* pass it on */
CallNextHookEx(hook, nCode,
wParam, lParam);
return 0;
} /* pass it on */
// Read the documentation to discover what WPARAM and LPARAM
// mean. For a WH_MESSAGE hook, LPARAM is specified as being
// a pointer to a MSG structure, so the code below makes that
// structure available
LPMSG msg = (LPMSG)lParam;
// If it is a mouse-move message, either in the client area or
// the non-client area, we want to notify the parent that it has
// occurred. Note the use of PostMessage instead of SendMessage
if(msg->message == WM_MOUSEMOVE ||
msg->message == WM_NCMOUSEMOVE)
PostMessage(hWndServer,
UWM_MOUSEMOVE,
0, 0);
// Pass the message on to the next hook
return CallNextHookEx(hook, nCode,
wParam, lParam);
} // msghook
In the header file, add this to the protected section of the class:
afx_msg LRESULT OnMyMouseMove(WPARAM,LPARAM);
In the application file, add this at the front of the file somewhere:
UINT UWM_MOUSEMOVE = ::RegisterWindowMessage(UWM_MOUSEMOVE_MSG);
In the MESSAGE_MAP, add the following line outside the magic //{AFX_MSG comments:
//{AFX_MSG
ON_REGISTERED_MESSAGE(UWM_MOUSEMOVE, OnMyMouseMove)
In your application file, add the following function:
LRESULT CMyClass::OnMyMouseMove(WPARAM, LPARAM)
{
// ...do stuff here
return 0;
}
I've written a little sample application to show this, but since I was bored doing a global hook function for the n+1st time, I gave it a nice user interface. The cat looks out the window and watches the mouse. But be careful! Get close enough to the cat and it will grab the mouse!
You can download this project and build it. The real key is the DLL subproject; the rest is decorative fluff that uses it.
There are several other techniques shown in this example, including various drawing techniques, the use of ClipCursor and SetCapture, region selection, screen updating, etc., so for beginning programmers in various aspects of Windows programming this has other value besides demonstrating the use of the hook function.
ClipCursor
SetCapt.
|
http://www.codeproject.com/Articles/1037/Hooks-and-DLLs?fid=2061&df=90&mpp=10&sort=Position&spc=None&tid=2034239
|
CC-MAIN-2015-35
|
refinedweb
| 2,635
| 59.03
|
Recently, I've been exposed to the whole world there is to the ever smaller and lighter electronic-equipments. I've always been interested in cutting-edge technology and somehow I got involved in an aeromodelism group where it was decided that the best (and simplest) solution for measuring flight data was to use a GPS device. No doubt we chose the world leading brand Garmin, of all the features available in their devices, the one that was important to us was track recording. As the sole Windows application programmer in the group, I was requested to create software that would transfer data between the GPS unit and a Pocket PC so that adjustments could be made instantly based on the data collected which would be analyzed in graphs.
Garmin uses a proprietary format that is not complicated, but let's cover its basics here as there aren't many thorough resources on the internet.
Information transferred to and from the GPS is divided into packets, which we'll refer to as messages. Each message starts with a hexadecimal 0x10 code and ends with two bytes 0x10 and 0x03. The information itself is found between these starting and finishing bytes. The second byte refers to the kind of information that is being transmitted, i.e. the message ID. Next, we have a byte which represents the number of bytes that are to be sent starting from the following byte up to the last one, just before a checksum byte and the trailing 0x10 0x03. But if it were as simple as that, the protocol would not be totally robust. Let's imagine for example that the first information-byte, which is the 4th, has the bits set to 0x10 and the following one 0x03. A simple interpreter would get it as a message-finalizer, thus wrongly recognizing a message-escape sequence and causing an error. In order to remove such a possibility, Garmin chose to repeat the corresponding byte whenever 0x10 should be sent, as long as it's an information-byte, so that in the above case we would receive 0x10 0x10 0x03 accounting for only two bytes, thus removing any possible errors. Repeated 0x10 accounts for only one byte as far as the third-byte (count byte) is concerned. Let's see some examples of messages. Move your mouse over the bytes to see their descriptions:
Pocket PC: 10 0A 02 06 00 EE 10 03 - Ask for tracks, the first message sent. GPS: 10 06 02 0A 00 EE 10 03 - Reply to the previous message, means OK. GPS: 10 1B 02 05 00 DE 10 03 - Number of records to be sent next: 5. Pocket PC: 10 06 02 22 00 D6 10 03 - Ask for the next record. GPS: 10 63 0D 01 FF 41 43 54 49 56 45 20 4C 4F 47 00 D2 10 03 - Track name: ACTIVE LOG. Pocket PC: 10 06 02 22 00 D6 10 03 - Ask for the next record. GPS: 10 22 18 01 02 03 04 05 06 07 08 09 10 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 DE 10 03 - Point in track. Pocket PC: 10 06 02 22 00 D6 10 03 - Ask for the next record. GPS: 10 0C 02 06 22 CA 10 03 - Track EOF.
In order to calculate the checksum of the message we first sum up all the information-bytes and get the least significant byte of the result by applying an AND (&) operation. Then, we invert the bits by calling XOR (^) 0xff and then we just add 1. The code for doing this is shown below:
private bool CheckSum(System.Collections.ArrayList command,
bool errorDetails)
{
int res=0;
int orig=(byte)command[command.Count-3];
for(int i= 1;i<command.Count-3;i++)
{
res+=(byte)command[i];
}
res &= 0xff;
res ^= 0xff;
res+=1;
bool retval=(byte)(res) == (byte)orig;
if(!retval && errorDetails)
{
System.Windows.Forms.MessageBox.Show(
"Received message:\n" +
ToHEXstring(command) + "\n\n" +
"Received checksum: " + orig.ToString() +
"\nCalculated checksum:" + res.ToString(),
"Error details",
System.Windows.Forms.MessageBoxButtons.OK,
System.Windows.Forms.MessageBoxIcon.Asterisk,
System.Windows.Forms.MessageBoxDefaultButton.Button1);
}
return ( retval );
}
For each point data sent by the GPS, there is the latitude, longitude, time, altitude and whether, it is a new segment within the same track. Each of the first four fields is composed of 4 bytes, in a way that the most significant one is the one to the right. Next we'll discuss how to obtain data values from the bytes.
Both the latitude and longitude are represented by an int32 ranging from -2147483648 to +2147483647 that should be translated into numbers from -90 to +90 for latitude and from -180 to +180 for longitude. The mathematical formulae for both are the same and are shown in the extract below which comprises of all the parsing of a track point message.
int32
The time is the simplest to retrieve from the message: we just read the four corresponding bytes and store them.
The altitude is not easy to calculate from within the .NET Compact Framework. This field is transmitted as a float32 and we must retrieve a variable of that type based on the 4 bytes. This complex routine, which I'll not go into detail here, is also shown in the extract below.
float32
Once I discovered which byte to check for such information, getting its data was fairly trivial.
latitude=( ((byte)command[6]<<24 |
(byte)command[5]<<16 |
(byte)command[4]<<8 |
(byte)command[3])
* ( 180.0 / 2147483648.0) );
longitude=( ((byte)command[10]<<24 |
(byte)command[9]<<16 |
(byte)command[8]<<8 |
(byte)command[7])
* ( 180.0 / 2147483648.0 ) );
time=(uint)((byte)command[14]<<24 |
(byte)command[13]<<16 |
(byte)command[12]<<8 |
(byte)command[11]);
if((byte)command[23]==1)
isNewSegment=true;
else
isNewSegment=false;
/*);
For every new track in the GPS database a message is sent containing the name of a new track and its ID, as seen earlier in the message examples. Next is a snippet from the code that is used to get the track name:
name=""
for(int i=5;i<=(byte)command[2]+1;i++)
name+=Convert.ToChar((byte)command[i]).ToString();
This is just an outline of what the protocol seems to be according to my analysis. For more information on other types of data that can be transferred, you may refer to this.
Having the protocol interpreter done, the next step was to build the data analysis tools, which was not as easy as expected due to the limitations found while comparing the .NET Framework to the .NET Compact Framework. The main feature usually used in graphing applications is vector graphics, achieved with the aid of matrix-transformations such as scale and translation. As a consequence, all the drawing routines had to be created from scratch.
For serial communications, I grabbed routines from Microsoft and the progress bar used to indicate the transfer progress from a GPS unit was taken from the OpenNETCF Smart Device Extensions project, which adds a fancy gradient background to the control.
Three important classes used for communication between a Pocket PC and a Garmin GPS unit are included in the source code: Garmin, Track and TrackPoint. The first one is responsible for communicating with the unit and storing the information received into tracks of type Track, each made of points of type TrackPoint, and stored by each track as ArrayLists.
Garmin
Track
TrackPoint
ArrayList
Making the Garmin class communicate with the GPS seemed to be trivial at first, but came out to be much more complex than expected.
I tried two methods of communication before getting to the one that I am now using, which hasn't failed even once throughout my tests with an iPaq H2215 device. However, when I tried it on an older model also from HP, the Jornada 548, I couldn't get it to work, probably because of some difference in the hardware implementation of the serial port. Next, I will describe each of the methods that sometimes worked but were not stable and their problems, and also the reliable one that is currently in use:
The first one I tried consisted of parsing the data as it was received from the GPS and creating Tracks and TrackPoints according to what was received. The problem with this was as the serial port is asynchronous, I couldn't find out when the message was over while still not skipping any bytes that are the first ones from the next message unless I wrote a complex routine that would do the trick. After adding some delays to make sure that all the data had come and still not getting the expected results, I decided to try another method.
By using this method, whenever the data came in, a send next command was sent to the GPS so as to avoid the problems created by using the artificial delays of the previous method. This method never got to work due to the bytes being skipped.
In this method, I mix the second one with a new concept to make the code reliable. Whenever data is received it is added to an ArrayList and, when an EOF (End of File) is received a function is called to split the messages from the array of bytes stored in the ArrayList and then the Track and its TrackPoints are added. By using this method, the saving and loading of files was made much easier, as the process of loading data from the GPS or from a file would be the same. To save data I need to just copy the bytes in the ArrayList to the storage memory and to load it, do just the reverse and call the function that splits the messages accordingly.
Creating a code that would flawlessly break the bytes at every message-end took many hours until I got the idea of an algorithm that would do the trick. As mentioned earlier, when an information-byte has a value of 0x10, it is repeated. So, if we count the number of adjacent 0x10 present in the actual message we'll always get an even number as there will never be a single 0x10, they come in pairs. However, if there's an ending 0x10 byte we'll get an odd number because the ending-byte is always sent on its own. That's it! Breaking the messages was as simple as counting adjacent 0x10 and checking the result. If it is even we should go on. Otherwise, we have found a message break:
private static System.Collections.ArrayList SplitBytes(
System.Collections.ArrayList arrayListBytes)
{
System.Collections.ArrayList retval=
new System.Collections.ArrayList(10);
System.Collections.ArrayList tempBytes;
int count=0;
for(int i= 0;i<arrayListBytes.Count;i++)
{
if((byte)arrayListBytes[i]==0x10)
{ /* First byte in a message */
tempBytes=new System.Collections.ArrayList(8);
tempBytes.Add(arrayListBytes[i]);
for(int x=i+1;;x++)
{
i=x;
tempBytes.Add(arrayListBytes[x]);
if((byte)arrayListBytes[x]==0x10)
++count;
else if((byte)arrayListBytes[x]==0x03)
{
if(count%2==1) /* If found an odd number of
* 0x10 followed by 0x03 we
* have to split the message
* here */
break;
}
else
count=0;
}
retval.Add(tempBytes);
}
}
return retval;
}
In order to connect your Pocket PC to a GPS unit software-wise you just need to create a variable of type Garmin and call its .GetTracks.
.GetTracks
Apart from the software, you'll have to establish a real physical connection between the device's serial port and the GPS. For this, I personally recommend Pfranc plugs. I got mine here in Brazil with no problems and they work just great. On the other end of the cable you'll have the Pocket PC. In my case, I had an iPaq which comes with a power adapter. I used this adapter and added some extra wires to it so that it became a charging and serial port connector. Below is an image showing the HP iPaq universal 22-pin connector diagram that shows the wires to connect to the GPS. If you need assistance in creating the cables feel free to e-mail me, but keep in mind that the connections you make on your own could void your warranty and damage your equipment. I got mine to work with no problems at all, but there is a possibility of damaging both the devices. Do whatever you do at your own risk.
Solder-side view of the iPaq power adapter and the pins to solder.
eTrex Pfranc plug, frontal view from the latch.
This is the result of the modifications made to the original plugs.
One interesting feature added to the sample application is the ability to save a spreadsheet file which can be read by most of the spreadsheet editors available in the market. It saves files using the known CSV (Comma Separated Values) format. However, while implementing the save function, I discovered a problem with the CSV format which I couldn't overcome: The decimal-separator character seems to depend on the current system's regional settings, and as a consequence we can't guarantee that a saved file will be read properly by a configuration. Their might be some way to elegantly fix this problem, but the way I figured out works satisfactorily: I use Excel formulae to overcome this issue. Non-integer numbers are multiplied by 1010 and Excel is made to calculate the result of the division of such a number by 1010. This way the decimal separator will always be displayed according to each system's configuration and still will be made possible for reading by whichever configuration. Let's see an example of the formula we use for the altitude measurement in Excel: =7749426479104/10000000000 which accounts for approximately 774.9426 meters.
Plotter
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
/*);
float f;
f=*((float *)&command[15]);
typedef struct t_position_record{
int lat;
int lon;
unsigned long time;
float h1;
float h2;
long res;
unsigned char tail[3];
}position_record;
/* packet[] is a byte array from the garmin processed earlier */
position_record *pos;
pos=(position_record *)&packet[0];
printf("Latitude: %.3f, Altitude: %.3f \n",(pos->lat)*180.0/M_PI,pos->h1);
float
unsafe
struct
General News Suggestion Question Bug Answer Joke Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
|
http://www.codeproject.com/Articles/12320/Speaking-Garmin?msg=1364037
|
CC-MAIN-2015-06
|
refinedweb
| 2,422
| 59.64
|
In another Question many users recommend FlexWiki for Network Documentation. FlexWiki.com appears to be down. I was able to download the latest package from sourceforge.net, but cannot find installation instructions.
Config: Win2k3 w/ IIS 6.
Thanks in Advance
This comes from the 'cached' link of a google search with "Flexwiki QuickSetup". Google says this was cached on 27th March 2009.
PS: This is one more place with some references: Flexwiki at Winart.com.br.
PS: This is one more place with some references: Flexwiki at Winart.com.br.
what follows is a cut-and-paste from the google cached page. Sorry for the formatting mess.
What you need first
* Windows Server 2003 (or XP)
o Running IIS
* The web-full-Release.zip from the sourceforge download page
Steps.
Deployment
* If this server is for the FlexWiki, do the following:
o Unzip the files into the webroot folder (c:\Inetpub\wwwroot by default)
* If you run more web applications (more wikis maybe)
o Unzip the files into a chosen folder
o In IIS manager, share this folder as a virtual directory ( more info )
later on we will refer to the shared folder as fwfolder.
Giving rights
* If you want Anonymous read/write
o Make sure the IUSR_{computername} user can read fwfolder and can write the subfolders of fwfolder\WikiBases
* Advanced
o Take a look at fwfolder\Web.config file security settings section (about line 105-147)
Now, you are ready to use your flexwiki with a default namespace, try it! (Always use the same domainname in the url, or the cache will mess up links. Eg. don't use , just ).
Configuring a namespace
* Open the fwfolder\WikiBases\NamespaceMap.xml and edit the "DefaultNamespace" and the provider parameters
* rename the fwfolder\WikiBases subfolders respectively
* edit the _ContentBaseDefinition through the wiki engine, or at file level
If you are open to alternatives, i have used WampServer and found it quite easy to setup on windows (even desktop systems).
It includes Apache, MySQL and PHP. MySQL is now owned by Sun Microsystem so you might want to check licensing details.
By posting your answer, you agree to the privacy policy and terms of service.
asked
5 years ago
viewed
2680 times
active
|
http://serverfault.com/questions/25266/flexwiki-install-instructions
|
CC-MAIN-2014-42
|
refinedweb
| 371
| 65.22
|
How to randomize blocks in OpenSesame (a solution not a question)
Hello everyone,
I've had this problem where I wanted to randomize blocks of trials (i.e., randomize the presentation of the blocks, not the trials within a block). After some researching, I found Sebastian's youtube video on how to counterbalance blocks, and I found that extremely useful. However, if you would like to purely randomize blocks for each participant, I came up with a solution that I think anyone can do fairly simply. I am not a programmer, so if anyone sees something wrong or how to do this more simply, let me know!
1) The first step is to create an inline code at the beginning of the experiment (see the picture in step 2 to figure out where to place it. Mine is called "new_inline_script_3"):
from random import shuffle #create a list of the number of blocks that you need. Always start at 0. Here I have eight blocks. block_list = [0, 1, 2, 3, 4, 5, 6, 7] #randomize the list that you just made shuffle(block_list) #create variables that will be used to help randomize later in your MainSequence. The number of variables depends on the number of blocks you have in your experiment (and should correspond to how many are in the block_list). So if you have only 3 blocks, you would use b0, b1 and b2. b0 = block_list[0] b1 = block_list[1] b2 = block_list[2] b3 = block_list[3] b4 = block_list[4] b5 = block_list[5] b6 = block_list[6] b7 = block_list[7] #Make these variables part of the experiment exp.set('b0',b0) exp.set('b1',b1) exp.set('b2',b2) exp.set('b3',b3) exp.set('b4',b4) exp.set('b5',b5) exp.set('b6',b6) exp.set('b7',b7)
2) Next set up your experiment hierarchically to include a Main Loop and Main Sequence. Call them MainLoop and MainSequence (if you call them something else, you will have to change the 'count_MainSequence' variable in step 4 to whatever you call your "MainSequence" sequence). Add the blocks within the Main Sequence.
3) For the main loop, you need to have as many cycles as you have blocks. v3.1 is a bit different than previous versions in that you can't specify how many cycles you want through a drop down menu. But all you have to do is double click on cells in the first column to specify this.
4) Click on the your Main Sequence and then add the following to the "run if" arguments next to each block:
block1 --> =self.get('b0) == self.get('count_MainSequence')
block2 --> self.get('b1') == self.get('count_MainSequence')"
etc...
Notice that the "b" variables start with 0. So Block 1 should be associated with b0
You can do this by going into the code itself:
set flush_keyboard yes set description "Runs a number of items in sequence" run Block1 "=self.get('b0') == self.get('count_MainSequence')" run Block2 "=self.get('b1') == self.get('count_MainSequence')" run Block3 "=self.get('b2') == self.get('count_MainSequence')" run Block4 "=self.get('b3') == self.get('count_MainSequence')" run Block5 "=self.get('b4') == self.get('count_MainSequence')" run Block6 "=self.get('b5') == self.get('count_MainSequence')" run Block7 "=self.get('b6') == self.get('count_MainSequence')" run Block8 "=self.get('b7') == self.get('count_MainSequence')"
Or you can just click on the "run if" boxes and adding the code.
That's it! Each time you run a participant, they should get a random order of each block. I hope this helps someone, and there is an easier way of doing this, let me know!
I tried this but it keeps showing me there are syntax errors in both the set flush and the set description lines.
Have you encountered this before?
How do you define the blocks as variables?
|
https://forum.cogsci.nl/discussion/2580/how-to-randomize-blocks-in-opensesame-a-solution-not-a-question
|
CC-MAIN-2021-25
|
refinedweb
| 629
| 64.41
|
In real-world programming, the Java If Statement is one of the most useful decision-making statements. The Java if statement allows the compiler to test the condition first and, depending upon the result, it will execute the statements. If the test condition is true, then only statements within the if statement will run.
Java If Statement Syntax
If statement in Java Programming language has a simple structure:
if (test condition) { Statement 1; Statement 2; Statement 3; …………. …………. Statement n; }
From the above code snippet, If the test condition inside the If statement is true, then the statements (Statement 1, Statement 2, Statement 3, ……., Statement n) will be executed. Otherwise, all these statements inside the Java if statement will skip. Let us see the flow chart for a better understanding.
Flow Chart of a Java If Statement
The following picture will show the flow chart behind this Java If Statement
If the test condition is true, then STATEMENT 1 is executed, followed by STATEMENT N. If the condition is False, then the STATEMENT N will run. Because it is out of the if condition block and it has nothing to do with the condition result, let us see one example for a better understanding.
Java If Statement example
This Java if statement program allows the user to enter any positive integer, and it will check whether a number is Positive or Not using the if statement.
/* Java If Statement example */ package ConditionalStatements; import java.util.Scanner; public class IfStatement { private static Scanner sc; public static void main(String[] args) { int Number; sc = new Scanner(System.in); System.out.println("Please Enter any integer Value: "); Number = sc.nextInt(); if (Number > 1) { System.out.println("\nYou have entered POSITIVE Number"); } } }
You can observe that we entered 25 as Number, and this program will check whether 25 is greater than 1 or not. As we all know that it is True, it is printing (System.ot.println statement) inside the curly brackets ({}}.
Please Enter any integer Value: 25 You have entered POSITIVE Number
Java If condition does not require the curly brackets to hold a single line, but for multiple or group of code lines, it is mandatory. It is always good practice to use curly brackets following the If statements. Let us change the value to check what happens if the Java condition fails? (number < 1).
Please Enter any integer Value: -5
It prints nothing because we have nothing to print after the if statement block. I guess you are confused about the result. Let us see one more example.
Java If Statement example 2
The If statement program allows you to enter any positive integer, and it will check whether a number is Positive or Not.
package ConditionalStatements; import java.util.Scanner; public class IfStatement { private static Scanner sc; public static void main(String[] args) { int Number; sc = new Scanner(System.in); System.out.println(" Please Enter any integer Value: "); Number = sc.nextInt(); if (Number > 1) { System.out.println("You have entered POSITIVE Number"); } System.out.println("This Message is coming from Outside the IF STATEMENT"); } }
As you can observe from the above output, Java printed both the System.ot.println statements because 23 is greater than 1. Let us try the negative values to fail the condition deliberately.
Please Enter any integer Value: -50 This Message is coming from Outside the IF STATEMENT
Here, Condition inside the If statement failed (number < 1). It prints nothing from the If statement block, so it printed only one System.ot.println statement, which is outside the statement block.
|
https://www.tutorialgateway.org/java-if-statement/
|
CC-MAIN-2021-43
|
refinedweb
| 594
| 56.15
|
If you are starting Joomla! development right now, my opinion is to start
using the legacy classes. From my knowledge, the legacy support will be in
the next major release (3.5) as well in the current STS releases (3.1,
3.2).
What is going to happen in the future is rather a thing that will be
discussed, software is evolving, so is Joomla.
You should learn using the legacy classes because:
you will find most of the documentation / books / support about them
core components are build using them (and understanding how core components
work, is a key to your success in developing extensions).
Native classes:
are rather poorly documented
not so many examples (for example just the Joomla installer is using them)
not so many use them, so getting support might be rather difficult
it good t
According to what you've described , you just need a function that will
sort
the links by the abc.
function just_host($link)
{
return array_shift( explode( '.', str_replace('www.', '', parse_url($link,
PHP_URL_HOST))));
}
$multi = $_POST['multi_links']; //$_Post is not right , all upper-case!
$links = explode("
", $multi);
$links = array_map($links , 'just_host'); //Call the 'just_host' for every
link and update the value in the array.
sort($links); //Sort the array
foreach($links as $link) //Instead of 'for' , use 'foreach'
{
echo $link . "<br />";
}
Should work , please update me if not and I'll edit it.
Usually, it's about exploiting a vulnerability in a process that runs as
root: Either a server that accepts connections (sockets, pipes, etc.) or an
executable with the SETUID flag.
If by "gain root access" you mean take control of a shell running as root,
the buffer overflow payload must start a shell and use dup2 to redirect its
input and output to something the attacker controls (such as a socket
connection to a "command and control" server running on the attacker's
machine).
I had a similar problem. To get my particular site working, I added the
following code to my configuration file:
define('WP_HOME','');
define('WP_SITEURL','');
After adding the lines, my CSS and uploaded images came back.
Don't forget to replace example.com with your site's domain name.
I found that code at:.
Actual user results may vary.
I was able to use a different DNS server via the host command via shell...
$p = trim(trim(explode(' pointer',shell_exec('host -W 2 180.76.5.168
68.238.96.12'))[1]),'.');
Did you issued the flush privileges after granting access to the wildcard
user?
What happens if you add an entry with user = sadmicrowave and host = [your
actual ip] (don't forget to issue the flush privileges command after adding
the user) ?
The problem may be that you have not defined default_host for test
environment. Define default_host inside config/environments/test.rb like
this:
config.action_mailer.default_url_options = {:host => "localhost:3000"}
It seems like the target platform defined under 'Window -> Preferences ->
Plug-in Development - Target Platform' prevented the export to succeed.
I added a new entry copying the settings from my current target platform
(chose option 'Current Target'). There, I changed under 'Environment' the
'Architecture' value to 'arm'. As 'arm' was not an option provided by the
drop-down list, I typed it manually into the text field.
That's it. When using this target configuration, everything works fine now.
The bundle is exported successfully and I can use it on my Android device.
The declaration of the memoryPool variable must use the correct type
parameter. You don't say what T is; whatever it is it's incompatible with
double[][].
DynamicMemoryPool<double[][]> memoryPool = new
DynamicMemoryPool<double[][]>(200, false, new JavaAllocator(), size);
How do you know its buffered? Check the config file on the client side
after proxy generation. Sometimes the proxy generated config file has
incorrect transfermode.
When you start writing the file on the client, don't any see any chunk wise
increase in the size of file?
The hosting shouldn't affect the transfermode.
The only difference between IIS and Console would be the way
activation/deactivation is managed.
From a design perspective, I would prefer approach #1 because it means that
you don't have to manage threads in your JNI code. This adheres to the
"single responsibility principle": your native code only needs to change if
your algorithm changes. I also think that the facilities (threadpools and
futures) that Java provides are easier to use than direct threads.
However, if you do this you should pay particular attention to the warning
about pinning and unpinning arrays from multiple threads.
A better approach IMO is to allocate a direct ByteBuffer, and access it
from JNI using GetDirectBufferAddress. This would let you use a Java-side
threadpool to manage the work, and would eliminate any native-side concerns
about buffer copies.
"The native hadoop library is supported on *nix platforms only. The library
does not to work with Cygwin or the Mac OS X platform."
I was having the exact same issue and finally resolved it by randomly
choosing a datanode, and checking whether lzop was installed properly.
If it wasn't, I did:
sudo apt-get install lzop
Assuming you are using Debian-based packages.
The translation could be something like this:
public long PHash (string pValue)
{
int dValue;
double dAccumulator;
int lTemp;
string sValue;
sValue = pValue.Trim().ToUpper();
dAccumulator = 0;
for (lTemp = 1; lTemp <= sValue.Length; lTemp ++)
{
dValue = (int)char.Parse(sValue.Substring(lTemp, 1));
if ((lTemp % 1) == 1)
{
dAccumulator = Math.Sin(dAccumulator + dValue);
}
else
{
dAccumulator = Math.Cos(dAccumulator + dValue);
}
}
dAccumulator = dAccumulator * (long)(10 ^ 9);
return (long)(dAccumulator);
}
The function translated were:
Trim: Removes spaces on both the left and the right side of a string. In
C#: Trim().
UCase: Converts a specified string to uppe
Personally, I would prefer WCF (the "new" way) over ASMX (the "old" way -
ref: the link you provided to the MSDN site)
You must remember that the address of a pointer is relative to a specific
process. So, the pointer you send (which just becomes an integer) means
nothing to the receiving process (it'll just be a random address to
unrelated memory).
You should use WM_COPYDATA instead:
By default, the routes will not accept anything after the ? as part of the
page being routed to since by definition the ? separates the query string
from the resource in the URL. One way that might work is
routes.MapPageRoute("blog-slug", _
"~/blogArticles/Default.aspx")
But the "financial-literacy-efficacy" value will instead be a key since it
is ?x not ?slug=x. However, since that is the legacy url, there might
already exist some portion of your code that checks keys in query strings
as opposed to values since most dynamic webforms legacy urls look soemthing
like
blog/?slug=x
And then they check Request.Querystring["slug"]. You would need to provide
more information in your question if that causes you trouble.
You need to have the server respond with a permanent redirect 301 code to
the new address. This will be cached by browsers, and also tell search
engines to drop the old content from their indexes.
The easiest and fastest approach would be to create a page.php file in your
webroot that issues the redirect.
<?php
if(isset($_GET["hash"]))
{
$location = "/controller/action/hash:"+$_GET["hash"];
header ('HTTP/1.1 301 Moved Permanently');
header ('Location: '.$location);
}
else
{
header('HTTP/1.0 404 Not Found');
}
I have no idea where it needs to redirect too, but that was just an
example..
You could create a structure to store your float/double values and pass the
address of that structure in the lParam value. If you are Posting the
message rather than Sending it, you will need to get the recipient to free
the memory occupied by the structure.
#define MYMESSAGECODE (WM_APP + 123 )
typedef struct
{
float f;
double d;
} MyDataStruct;
MyDataStruct data;
data.f = 1.0;
data.d = 2.0;
pWpfWnd->SendMessage( MYMESSAGECODE, 0, (LPARAM) &data );
I think the easiest way is to use a css pre-processor to namespace all of
bootstraps css components.
If you got to their github repo: you
will see they have a LESS distrubution of the code. From there, you can
namespace all of their styles by wrapping the library in some kind of
class, such as millimoose mentioned.
From their you can add the bootstrap namespace to certain html elements,
and the library will only effect that dom node and its children.
Firstly, you may have an error in the code. The selector "#container
.input" refers to a class of input, whereas the other code refers to
#input, i.e. the id input.
The following jsfiddle example will work as intended.
The example doesn't use RequireJS to load jQuery at all. Instead, it
defines the jquery module explicitly, after loading jQuery with a regular
<script> tag.
This will ensure that the global jQuery object and the AMD jquery module
value are one and the same thing. Therefore keeping a single jQuery to
register events with, etc.
<script
src=""></script>
<script
src=""></script>
<script>define("jquery", function() { ret
I'm really wary about what I'm about to suggest, as I think this is an
unfortunate problem of things being incorrectly designed originally; you're
sort of running against the basic way Javascript works. I'd really prefer
to think of this kind of issue as "job security" for the person assigned to
re-make this stuff as outside-of-HTML code.
But if you want to hear it, I do have a possible solution that uses eval.
For that alone, I think I'm going to be downvoted, and not without good
reason. I haven't even tested this (except for the 'script with alternate
type' and its selection), but seeing this question had two upvotes, no
answer, I figure I'll suggest it. So, you're going to have to evaluate it
with its potential security risks.
Start by replacing in-page scripts with this:
<script
Light Table uses leining for the project management, so you can very easily
keep repl open in another window connected to the same project to get the
traditional REPL expierence. This lets you switch between the two quickly.
Light Table is evolving rapidly and who knows if standalone repl mode has
been added since I last looked or will be added soon.
Turns out that the md5 in symfony2 uses a salt by default. There may be an
easier way, but I just created a custom md5 password encoder interface that
ignores salt.
Register a service
namespace.project.md5password.encoder:
class: NamepspaceMyBundleServicesCustomMd5PasswordEncoder
Create the encoder service
namespace NamespaceMyBundleServices;
use SymfonyComponentSecurityCoreEncoderPasswordEncoderInterface;
class CustomMd5PasswordEncoder implements PasswordEncoderInterface
{
public function __construct() {
}
public function encodePassword($raw, $salt) {
return md5($raw);
}
public function isPasswordValid($encoded, $raw, $salt) {
return md5($raw) == $encoded;
}
}
Use the new service in security.yml
security:
encoders:
Namesp
I got this response from Google AdMob
Hello,
Thanks for contacting AdMob support.
Our engineers have fixed this issue. Ads should now be serving
correctly. Your reporting should return to normal within 24 hours.
Thanks for your patience,
The Google AdMob Team
Looks like all is good now...On Aug 8th and 9th they had the problem, but
for the past 5 days it has been stable. Check out this fill rate...been
>99% for the past five days.
I suppose that you use JPA annotations to declare your mapping.
First problem. Just do not apply @GeneratedValue annotation.
public class SomeEntityWithAutogeneratedId {
@Id
@GeneratedValue // autogeneration
private Long id;
}
public class SomeEntityWithoutAutogeneratedId {
@Id
private String id;
}
Second problem. You can prepare a base class to simplify mapping of common
fields. Then you can use @PrePersist to apply correct values for all
necessary fields before update:
public abstract class AbstractEntity {
@Column
private Date dateLastModified;
@PrePersist
public void beforePersist() {
this.dateLastModified = new Date();
}
}
public class Entity1 extends AbstractEntity {
public class Entity2 extends AbstractEntity {
public class En
It is helluva easy to decompile the jar file. Just download the (currently)
most widely used java decompiler, click File -> Open and open your jar
file. You can then browse the code in the main window, and copy and paste
it to actual files.
command.com does not exist on 64 bit windows.
Try using C:WindowsSysWOW64cmd.exe instead. C:WindowsSysWOW64 is a folder
giving you backwards compatibility stuff for 32 bit.
But see the comment below (taken from Euro Micelli).
Really you should use %SYSTEMROOTSystem32cmd.exe instead. First, Windows is
not always installed in C:Windows; you should let the system figure that
out. Second, using System32 is always correct for a 32-bit application:
when running on Win32, it is the correct folder; when running on Win64,
Windows will map %SYSTEMROOT%System32 to %SYSTEMROOT%SysWOW64
In the documentation on the django website it states "In particular,
you’ll need to rearrange models’ order, so that models that refer to
other models are ordered properly."
What exactly does this mean?
In Python in general, in order to refer to any name, it needs to be defined
first; because only then is it mapped; so this will result in an error:
print(hello)
hello = 'world'
Similarly, in models.py, when you are referring to another model class in
any relationship; you have to make sure the class is declared before it is
referred to - or you need to quote the class name. Since the inspection
cannot guaratee the order of models being created, you get the warning. It
is designed to prevent this scenario, which will result in an error:
class A(models.Model):
foo =
Use dispatchEvent:
window.dispatchEvent(new CustomEvent('test'));
You could easily create a wrapper:
$.fn.nativeTrigger = function(type) {
return this.each(function() {
this.dispatchEvent( new CustomEvent(type) );
});
}
$('body').trigger('test').nativeTrigger('test');
Another way would be to extend the $.fn.trigger but that’s pretty deep
water.
Cloud SQL Instances are not restricted to work only with AppEngine apps in
the same project. You can just create a new project at (which will have Cloud SQL enabled), and
from that project create a new Cloud SQL Database. Just make sure you
replace the default authorized AppEngine project with the old one on the
Create screen.
Before LINQ you were just limited to all the built-in List/List<T>
methods, and yes Find is one of them (still is). The difference is it
expects a Predicate<T> as opposed to a Func<Boolean, T> which
you can still do inline e.g.
var found = list.Find(delegate(Item item) { return item != null; });
Or as you demonstrated by using a named method.
This will help
You can get access to parameters using request.request_parameters() or
something like that and use them.
Did you try prefer-application-packages within the weblogic-application.xml
as well?
The mechanism that Weblogic calls the Filtering Classloader, here are the
links:
Figured it out thanks to this answer (albeit lightly modified). Basically,
it updates the user behind the scenes to use the new system if the current
system doesn't match up with it.
/**
* Login method
*/
public function login() {
$this->layout = 'homepage';
// If the user is already logged in, redirect to their user page
if($this->Auth->user() != null) {
$this->redirect();
} else {
// If this is being POSTed, check for login information
if($this->request->is('post')) {
if($this->Auth->login($this->loginHelper($this->request->data)))
{
// Redirect to origin path, ideally
} else {
$this->Session->setFlash('Invalid username or
password, try again');
The legacy controls are members of the Selection.FormFields collection. The
do not have events, the nearest equivalents are the EntryMacro and
ExitMacro properties.
Sub Macro2()
Selection.FormFields.Add Range:=Selection.Range,
Type:=wdFieldFormDropDown
Selection.PreviousField.Select
With Selection.FormFields(1)
.Name = "Dropdown1"
.EntryMacro = "Macro1"
.ExitMacro = "Macro2"
.Enabled = True
.OwnHelp = False
.HelpText = ""
.OwnStatus = False
.StatusText = ""
End With
Selection.FormFields("Dropdown1").DropDown.ListEntries.Clear
End Sub
The ExitMacro doesn't run on selecting, or changing, a drop-down item, but
when tabbing away from the control.
There is some MS information here about these legacy controls
There are a few ways date comparisons can go wrong. None of them have
anything to do with CURRENT_DATE, which has standard, well-defined,
consistent behavior.
First, php usually executes on the web server; CURRENT_DATE executes on the
database server. Sometimes the web server and the database server are the
same machine, but sometimes they're not. Two different servers might be
operating with mismatched clocks. And it's at least theoretically possible
for the web server and the database server to be in (or to be set to) two
different time zones. I've never seen servers set up that way myself, but
it's possible.
Second, your PHP expression returns a string (not a date) in the form of a
timestamp (not in the form of a date). CURRENT_DATE returns a date. They're
not the same data type. Com
List<Object>= new List<Object>;
list.add("hello");
String s=(String)list.get(0);
Should be
List<String>= new ArrayList<String>(); // this is now a list
of String, not a list of object
^^^^^^ ^^^^^^
list.add("hello");
String s=list.get(0); // no casting needed
^
You parameterize by the type you want. Your example are 2 ways to do the
same thing, since you parameterize by the most basic class.
The advantage of generics is that you can write classes that are more
specific to one class, String here. This gives you better type safety to
catch bugs early during compilation. This prevents issues arising from the
casting approach.
The first thing is the stray RewriteCond %{HTTPS} !=on that you have at the
top. It looks like it belongs to the rule under it, as in:
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} !^ [NC]
RewriteCond %{HTTP_HOST} (.+)$ [NC]
RewriteRule ^(.*)$ [R=301,L]
As far as the rule that you have commented that doesn't work, the ? is a
reserved character for regular expressions, and your pattern actually says
that the second p in /index.php is "optional". Additionally, you can't
match against the query string in a rewrite rule, you need to use a rewrite
condition and match against the %{QUERY_STRING} variable:
RewriteCond %{QUERY_STRING} ^option=com_chronocontact&Itemid=54$
RewriteRule ^(index.php)?$ /contact/? [R=301,L]
is probably more along the lines of what
|
http://www.w3hello.com/questions/Anybody-host-ASP-NET-with-legacy-native-DLL-s-
|
CC-MAIN-2018-17
|
refinedweb
| 3,030
| 56.76
|
JDriven Blog 2021-01-04T08:13:30.378Z JDriven Hexo Detect & delete unreferenced code with ArchUnit 2021-01-03T17:36:57.000Z 2021-01-04T08:13:30.378Z <div class="paragraph"> <p>When you maintain a large Java project for a longer period, the moments where you’re finally able to remove unused code can be very satisfying. No more upkeep, library version migrations or dark corners to maintain, for code that’s no longer being used. But finding out which parts of the code base can be removed can be a challenge, and tooling in this space seems not to have kept pace with recent development practices in Java. In this post we’ll outline an approach to find unreferenced code with ArchUnit, which allows you to iteratively detect & delete unused code from your Java projects.</p> </div> Java Joy: Optional orElse orElseGet That Is The Question 2020-12-30T13:18:08.000Z 2021-01-04T08:13:30.377Z <div class="paragraph"> <p>The <code>Optional</code> class has the <code>orElse</code> and <code>orElseGet</code> methods to return a value when the <code>Optional</code> object is empty. This is useful to return a default value for example. But there is a small difference between the two methods. The <code>orElseGet</code> method needs a <code>Supplier</code> argument that returns a value of the type of the <code>Optional</code> value. The <code>Supplier</code> is only invoked when the <code>Optional</code> value is empty. The statement passed as argument to the <code>orElse</code> method is always executed, even when the <code>Optional</code> value is not empty. Preferrably we should use <code>orElseGet</code> as it will only invoke statements if needed.</p> </div> iTerm2 2020-12-05T16:00:00.000Z 2021-01-04T08:13:30.377Z <div class="paragraph"> <p>Since I’ve been working on a Mac, I replaced the default terminal with iTerm2. It provides some nice features like searching, autocomplete, or allowing to see images in the terminal. But this one is my favorite one, the undo close tab / session.</p> </div> Formatting in pre-commit hook 2020-11-28T19:52:14.000Z 2021-01-04T08:13:30.377Z <div class="paragraph"> <p>Many projects force their code to be formatted. We use <a href="" target="_blank" rel="noopener">spotless</a> for this purpose. It can check for propper formatting, and also format the code for you. Then build pipeline checks if the code is properly formatted. Failing pipelines due to formatting errors are annoying and cost a lot of time and money. This blog proposes a solution.</p> </div> How to hack a box - Privilege Escalation 2020-11-27T08:00:00.000Z 2021-01-04T08:13:30.377Z <div class="paragraph"> <p>Welcome back to the final blog in de series "How to hack a box"! In this blog we’ll cover the basics of Privilege Escalation and see it in practice on the Blocky box from Hack The Box.</p> </div> How to hack a box - Enumeration 2020-11-13T09:30:00.000Z 2021-01-04T08:13:30.377Z <div class="paragraph"> <p>Welcome back to the blog series about how to hack a box! In the past few blogs we’ve gone through a few steps which gives you an idea of how you can hack a box. We went from the <a href="">Introduction</a>, to <a href="">Exploration</a>, to <a href="">Gaining Access</a>. In this blog, we’ll cover the basics of Enumeration.</p> </div> Deprecation with Replace hits 2020-11-10T16:51:53.000Z 2021-01-04T08:13:30.377Z <div class="paragraph"> <p>When code evolves we usually deprecate old code. Sometimes we come across deprecations without any hints with what to replace it with. Kotlin has a solution for this by allowing you to specify a replace instruction.</p> </div> Async Retrofit with coroutines and Spring Boot 2020-11-09T19:32:05.000Z 2021-01-04T08:13:30.376Z <div class="paragraph"> <p>Spring boot supports a non-blocking programming model with the spring-webflux module. Webflux supports a Reactive API using the Reactor library Flux and Mono API types. This model forces you to write your code in a different style than most people are used to. It generally is much harder to follow and debug.</p> </div> Custom SSLContext with Apaches fluent HttpClient5 2020-11-09T11:00:00.000Z 2021-01-04T08:13:30.377Z <div class="paragraph"> <p>Apaches fluent httpclient API is a facade API to simplify the httpclients usage for standard use cases. It’s also better readable and results in cleaner code. In this post we’ll see how to use a custom SSLContext with the fluent API. We’ll use the new 5.0 version because it contains some changes compared to 4.x.</p> </div> How to hack a box - Gaining Access 2020-11-06T11:00:00.000Z 2021-01-04T08:13:30.377Z <div class="paragraph"> <p>Welcome back to the blog series about how to hack a box! In this third post I’ll guide you through the second step: gaining access.</p> </div> Clojure Goodness: Getting Part Of A Vector With subvec 2020-11-05T06:00:27.000Z 2021-01-04T08:13:30.376Z <div class="paragraph"> <p>In Clojure we can get part of a vector collection using the <code>subvec</code>.</p> </div> Clojure Goodness: Split Collection With Predicate 2020-11-04T05:58:34.000Z 2021-01-04T08:13:30.376Z <div class="paragraph"> <p>To split a collection in Clojure we can use the <code>split-with</code> and <code>split-at</code> functions. The <code>split-with</code> function takes a predicate as first argument and a colletion as second argument. The function will return a vector with two items. The first item is the result of the function <code>take-while</code> with the given predicate. The second item in the result vector is the resul of the <code>drop-while</code> function with the same predicate.</p> </div> Clojure Goodness: Shuffle A Collection 2020-11-03T05:56:21.000Z 2021-01-04T08:13:30.376Z <div class="paragraph"> <p>In Clojure we can use the <code>shuffle</code> function with a collection argument to get a new collection where the items of the input collection are re-ordered randomly. The function delegates to the Java <code>java.util.Collections#shuffle</code> method.</p> </div> Clojure Goodness: Formatting With Java Format String 2020-11-02T20:54:17.000Z 2021-01-04T08:13:30.376Z <div class="paragraph"> <p>In Clojure we can format a string using Common Lisp format syntax or the Java format string syntax. In the post we will look at the how we can use the Java format string syntax. We must use the <code>format</code> function in the <code>clojure.core</code> namespace. The method delegates to the standard JDK <code>String#format</code> method. The first argument is a format string followed by one or more arguments that are used in the format string. We can look up the syntax of the format string in the Javadoc for the <a href="" target="_blank" rel="noopener"><code>java.util.Formatter</code> class</a>.</p> </div> Game Development in Java 2020-10-31T11:00:00.000Z 2021-01-04T08:13:30.374Z <div class="sect2"> <div class="paragraph"> <p>In my early days as a software developer I worked at a small game studio. This was back in the days when ActionScript and Flash were still a thing.</p> </div> <div class="paragraph"> <p>At JCore during Corona times we’ve spent part of the JCore Fast Track looking at game development in Unity3D and the Unreal engine. These engines work on C#/JavaScript and C++ respectively.</p> </div> <div class="paragraph"> <p>Nowadays the language I’m most comfortable with is Java. A little while ago I was wondering whether it would be possible to create a game in Java.</p> </div> <a id="more"></a> <div class="paragraph"> <p>Of course almost all languages support some sort of drawing, so technically the answer would be a straight yes. Modern engines and libraries offer support for OpenGL rendering and provide a lot of tools out of the box.</p> </div> <div class="paragraph"> <p>Though there are 3D engines for Java I’ll be focusing on a 2D game, mostly because the complexity of 3D and its assets makes creating anything resembling a 3D game a daunting task.</p> </div> </div> Implementing a https enabled redirect service using Firebase 2020-10-31T07:30:00.000Z 2021-01-04T08:13:30.374Z <div class="paragraph"> <p>More and more web-traffic is moving to https instead of http protocol. Because users are using a modern browser that defaults to https or a browser extension like <a href="" target="_blank" rel="noopener">Https-By-Default</a> . A great development from a security- and privacy perspective. But with some side effects as it pointed out that the redirect service offered by our hosting provider does not fully support https which causes a security warning.</p> </div> How to hack a box - Exploration 2020-10-30T07:00:00.000Z 2021-01-04T08:13:30.374Z <div class="paragraph"> <p>Welcome back to the blog series about how to hack a box! In the <a href="">first blog</a> I gave an introduction into the steps and prerequisites on How to hack a box. In this second post I’ll guide you through the first step, which is exploration. We will execute the steps on an actual box in <a href="" target="_blank" rel="noopener">Hack The Box</a>, called Blocky.</p> </div> How to hack a box - Introduction 2020-10-29T07:00:00.000Z 2021-01-04T08:13:30.374> Introduction to OData 2020-10-28T04:34:00.000Z 2021-01-04T08:13:30.375Z <div class="paragraph"> <p>As developer, you probably have to work with APIs. Either you consume them, or perhaps you build them. Most of the time an API provides some sort of JSON response or perhaps XML. When the implementation is complete, it provides documentation as well, using the OpenAPI specification. This however is not what this blog is about.</p> </div> Automating hosting RevealJS slides on GitLab 2020-10-27T07:30:00.000Z 2021-01-04T08:13:30.373Z <div class="paragraph"> <p><a href="" target="_blank" rel="noopener">RevealJS</a> <a href="" target="_blank" rel="noopener">GitLab</a> comes in, with GitLab pages you can host any static web content you want, so that’s what I will show in this blog, automatically hosting your RevealJS slides on GitLab with every commit of your slides.</p> </div>
|
https://blog.jdriven.com/atom.xml
|
CC-MAIN-2021-04
|
refinedweb
| 1,802
| 65.32
|
I use and love puppet. I moved to a new company and they are adopting chef. So I'm trying to learn chef but am having a hard time piecing it all together because I still think in puppet =)
These are my questions- puppets. Are there any other good chef resources I might be missing in my searches?
Answers to your questions.
Not clear if it's better to setup roles in ruby DSL, JSON, or from the management console? Why are there multiple ways to do the same thing?
There are multiple ways to do the same thing because people have different workflows. You pick the workflow that is best for your environment. Let me explain what the differences are so you can make an informed decision.
The Ruby DSL for Roles exists to make it easier to write roles without knowing the syntax of JSON. It is a simple way to get started with Roles. Once you have made changes, you upload them to the Chef Server with knife.
knife role from file myrole.rb
This converts the role to JSON and stores it on the server. If you have an environment that enforces the Chef Repository where your roles live as the source of truth, this works quite well.
JSON is what the Chef Server stores, so you also edit JSON directly in the mangement console. It does require more fields than the Ruby DSL in order for Knife to recognize it properly to upload. Those details are hidden to some degree via the web UI.
The disadvantage of using the webui/management console for editing roles is they aren't in your local version control system unless you download them from the server. You can do this with knife:
knife role show myrole -Fj
The -Fj tells knife to "display in JSON format." You can redirect the output to a .json file if you like.
-Fj
Can you organize cookbooks into subdirectories? eg- we have custom software that I'd like to write a cookbook for and stick that into: chef-repo/cookbooks/ourcompanystuff/customsoftwarecookbook would this be a good practice?
No. Knife has an expectation of where cookbooks should live because it uses an API to upload cookbooks to the Server. This is set in the knife.rb with cookbook_path. In older versions of Chef, you could specify an array of paths for cookbooks, but this is being deprecated because it required more maintenance and was confusing to users.
cookbook_path
By convention we name customer specific or site specific cookbooks with the name prefixed in the cookbook diretory. For your example, it would be:
chef-repo/cookbooks/ourcompany_customsoftware
There might be multiple different cookbooks for "ourcompany" depending on what you're doing.
Further reference:.
There is no direct relationship or dependency between roles and cookbooks.
Roles have a run list, which specifies the recipes and other roles that should be applied to any node that has that role. Nodes have a run list that can contain roles or recipes. When Chef runs on the node, it will expand the run list for all the roles and recipes it includes, and then download the cookbooks required. In a node run list:
recipe[apache2]
Chef will download the apache2 cookbook for the node so it can apply this recipe.
You might have a cookbook specific for a role in your infrastructure. More commonly you'll have cookbooks that are for setting up certain types of services like apache2, mysql, redis, haproxy, etc. Then you would put those into appropriate roles. If you have custom application specific things that need to happen to fulfill a role, then you could write this into a custom cookbook (like I referenced above).
Is there anything like puppets external node classifier so nodes automatically determine their roles?
"Yes." The Chef Server does node data storage (in JSON) automatically, and the server also automatically indexes all the node data for search.
It seems like you can configure things with knife or within the management console, or editing JSON files? This is super confusing to me why there are so many ways to do things, it's paralyzing! Is there a reason to use one or the other?
The Chef Server has a RESTful API that sends and receives JSON responses. Knife and the management console are user interfaces for interacting with the API from an administration point of view.
You can use the tool you like better, though the management console doesn't have as many features as Knife. Most people that use Chef prefer the command-line interface for the power and flexibility it provides, even folks who are using Chef on Windows. Further, knife is a plugin based tool that you can create new plugins to interact with the Chef Server, or with other parts of your infrastruture.
Chef is a set of libraries and primitives, and an API. It gives you the flexibility to build the configuration management system that works best for your infrastructure.
Further reading:
How can I automatically provision nodes with chef in my dev cluster? With puppet I fire up a VM that connects to the puppermatser?
You'll want to use Knife Bootstrap. This is a built in plugin that comes with knife. You invoke it like this:
knife bootstrap 10.1.1.112 -x root -i ~/.ssh/root_id_rsa -r 'role[webserver]'
This will:
root
--sudo
chef-client
webserver
This assumes that the target system has been provisioned, has an IP address and you can SSH as root. Depending on your local policies and provisioning process, you may need to adjust how this works. The knife bootstrap page on the wiki describes more about how this works.
The knife bootstrap command uses bootstrap "templates" which are platform specific shell scripts that will install Chef in the best known working configuration. Different distributions have different Ruby versions available, unfortunately, so there's different scripts. You can also create your own bootstrap templates. You can specify a different one with the -d or --distro option:
-d
--distro
knife bootstrap [ ... ] -d centos5-gems
Opscode is working on a full stack Chef client installer and bootstrap template that will remove a lot of these issues. It is in beta testing and it will be the way Opscode will recommend installing Chef.
Knife also has plugins for a number of public cloud computing providers such as Amazon EC2 and Rackspace Cloud. There are plugins available for private cloud environments like Eucalyptus and OpenStack. There are also plugins for VMware, Vsphere and others. You can see further information on the wiki.
Are there any other good chef resources I might be missing in my searches?
The Chef wiki is the primary source of documentation. Opscode is working on updating the Wiki documentation across the board to be consistent with the current release of Chef, and to appropriately separate the beginner information from advanced information. This should be completed fairly soon.
Opscode runs Chef Fundamentals training, which is a 3 day classroom based technical training course with lectures and exercises. Public training courses are offered periodically, and the materials for the training are available free of charge by registering with the Open Training program. Registration is required so Opscode can find out what people are interested in, and to contact people that sign up about new releases of the materials, or new public classes.
Opscode Open Training:
I occasionally post tips, tricks and guides about Chef to my blog:.
Opscode Hosted Chef customers can get help and support on the support site:
The Chef user community is an excellent source of additional help:
I hope this helps.
By posting your answer, you agree to the privacy policy and terms of service.
asked
2 years ago
viewed
8348 times
active
10 months ago
|
http://serverfault.com/questions/314990/chef-best-practices-questions
|
CC-MAIN-2014-10
|
refinedweb
| 1,300
| 64.2
|
Subject: Re: [geometry] Index distance predicates names
From: Adam Wulkiewicz (adam.wulkiewicz_at_[hidden])
Date: 2012-08-26 16:56:24
Hi,
I'm testing the r-tree implementation and have problem with some names.
I've been using near() and far() but these are macros defined in
windows.h. Since the r-tree isn't released yet, the simplest way of
fixing it is to change names. But first, I'll explain what are those
predicates.
R-tree allows to store volumetric values (boxes) and find some number of
them nearest to some point. It is possible to define which point of
volumetric object is taken in distance calculation. It may be the
nearest point, the centroid or the furthest point. This corresponds to
functions bgi::near(), bgi::centroid() and bgi::far().
bgi stands for boost::geometry::index namespace.
To complicate things. There is also a method rtree.nearest(Predicate)
and function bgi::nearest(rtree, Predicate). So knn query may look like
this:
tree.nearest(bgi::near(pt), output);
bgi::nearest(tree, bgi::near(pt), output);
tree | bgi::filters::nearest_filtered(bgi::near(pt))
or this:
bgi::nearest(
tree,
bgi::bounded(
bgi::near(pt),
bgi::centroid(10),
bgi::far(20)
), output);
Some names may form non-intuitive query, e.g.:
bgi::nearest(tree, bgi::nearest(pt), output);
What is more, I'd rather avoid furthest() because it is nice antonym of
nearest() and may be used as similar function name.
To the point. Possible names are:
near -> nearest, close, closest
far -> furthest, distant, most_distant
Do you have any preferences or other ideas?
Regards,
Adam
Geometry list run by mateusz at loskot.net
|
https://lists.boost.org/geometry/2012/08/2044.php
|
CC-MAIN-2019-13
|
refinedweb
| 271
| 59.8
|
I want to ask what the
with_metaclass() call means in the definition of a class.
E.g.:
class Foo(with_metaclass(Cls1, Cls2)):
with_metaclass() is a utility class factory function provided by the
six library to make it easier to develop code for both Python 2 and 3.
It creates a base class with the specified meta class for you, compatible with the version of Python you are running the code on.; it effectively creates a new base class by using the metaclass as a factory to generate an empty class:
def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" return meta("NewBase", bases, {})
The
NewBase base class's metaclass is
meta, both on Python 2 and 3..
Similar Questions
|
http://ebanshi.cc/questions/2031887/python-metaclass-understanding-the-with-metaclass
|
CC-MAIN-2017-43
|
refinedweb
| 121
| 56.59
|
Stefano Mazzocchi wrote:
>
> Donald: xmlns: xmlns:
>
> <title>Hello, you've requested me <utils:count/> times.</title>
>
> <p>
> Your shopping cart is currently: <xturbine:shopping-cart/>
> </p>
>
> <p>
> Your data is: <xsql:query>select * from Data</xsql:query>
> </p>
> </page>
>
> and then you XSLT-style it.
Yes, yes, yes... I am a huge proponent of moving to component based
systems, and this is a significant step in that process. The idea of
having "toolboxes" if you will of useful items, and those toolboxes
mapping to applications/frameworks makes a lot of sense, plus of course
makes development feasible.
Of course, as you know, this is really not posible in a constrained
environment (DTD/XML Schema) until XML Schema is more solid, because of
the nightmare of DTD for something that can include all sorts of
permutations of namespaces. Wouldn't you agree?
-Brett
|
http://mail-archives.apache.org/mod_mbox/cocoon-dev/199912.mbox/%3C3857D362.E1E55C09@algx.net%3E
|
CC-MAIN-2014-23
|
refinedweb
| 142
| 61.36
|
Managed I/O Completion Ports (IOCP) is part of a .NET class library named Sonic.Net, which I first released on CodeProject in May 2005. Sonic.Net is a free open source class library that can be used in building highly scalable server side .NET applications. This part-2 of Managed IOCP builds on top of my first Managed IOCP article. So it is a pre-requisite to read the first part of Managed IOCP before you read this part two of Managed IOCP. My first article on Managed IOCP is titled "Managed I/O Completion Ports (IOCP)". I request the readers to read the discussion threads in my first article, as they have a wealth of clarifications and information regarding Managed IOCP and its usage. Especially, the discussion with 'Craig Neuwirt' has brought out a critical issue with my original Managed IOCP implementation and helped me rectify it and make ManagedIOCP better (thanks Craig ).
Before getting into Lock-Free stuff, the Managed IOCP source and demo applications contained in the downloadable Zip of this article are compiled using my Lock-Free Queue class. Removing the conditional compiler constant LOCK_FREE_QUEUE from Sonic.Net project properties will enable the Sonic.Net assembly to be compiled with the .NET synchronized Queue class.
Queue
LOCK_FREE_QUEUE
Coming back to our Lock-Free stuff, I used a synchronized System.Collection.Queue class as the internal object queue for Managed IOCP in the Sonic.Net v1.0 class library. This provides a scope for lock contention between threads that are dispatching objects to Managed IOCP, and also between threads that are retrieving objects from Managed IOCP. I had to use a synchronized queue because the pop and push operations of a queue are not atomic. During a push operation, a thread has to first set the next node of the queue's tail node to point to the new node that holds the object to be enqueued. Next, the thread has to point the tail to the new node as the new node will now be the tail of the queue. These two operations cannot be performed atomically (with a single CPU instruction). This means that when multiple-threads are pushing objects (enqueuing) to the same instance of a queue, there are chances that some of the enqueue operations will be unsuccessful, and more dangerously, without the thread performing the push operation ever coming to know about it. Here is the scenario...
System.Collection.Queue
pop
push
Here comes the disaster. Thread-A thought that it has pointed the current tail's next node to its new node. But before it could point the tail to the new node (to make the new node the new tail), Thread-B has pointed the current tail's next node to its own new node. Oops!!! Thread-A's new node future is now hanging in mid air. The disaster is not yet over. Check out the following sequence of operations in continuation with the above mentioned operations of Thread-A and Thread-B.
After step-9 in the above sequence of events, the new node that is actually enqueued by Thread-A is lost. It is lost because neither the tail's next node nor the tail is pointing to it. It has become an orphaned object. In the C++ world, it would have led to serious memory leaks in the application as there is no way to reach the new node and its contained object, so no one will be able to free it. Fortunately, in the .NET world, the CLR's Garbage Collector will come to our rescue, and will eventually cleanup the orphaned node and its contained object later at some point of time. But the more serious problem here is not with the orphaned object but with the lost enqueue operation without the knowledge of the thread (Thread-A) that is performing the operation. Thread-A would think it has enqueued the object successfully, and would not report any error. This leads to missing objects, which could mean loss of data in the application. Loss of data, that too without notice, is a serious problem for any application.
It should be clear from the above discussion that the following two logically related operations should be synchronized using some locking mechanism, so that only one thread in the process could execute them at any given point of time.
Synchronizing access to common objects using locking may not always be the right approach. It will definitely stop the loss of data and corruption, but when your application is running in a multi-processor environment, it may reduce the performance of your application. This is because in a multi-processor environment, you will experience true parallelism in thread execution. So, when two threads are running in parallel and trying to enqueue (push) objects onto the same queue, then one of the threads has to wait until the other has come out of the locked code region. Since this enqueue operation is a core function that is used very frequently in Managed IOCP based applications, the threads _may_ experience lock contention, and the kernel activity might go up significantly as the OS has to keep switching the thread from running to suspended mode and vice-versa. It is desirable to suspend the thread when there are no objects queued onto the Managed IOCP. But when objects are present, it would be good if each thread is active for the maximum time possible in its given CPU cycle time.
We (Windows developers) have been using lock based synchronization successfully in Windows environment till now. So we can continue using it. But there are other more promising alternative techniques to lock based synchronization, especially when designing highly scalable server side applications. These are called Lock-Free algorithms. These techniques will allow multiple threads to safely use common objects without corrupting the object state or causing any loss of data. These techniques have been under heavy research in the recent past, and are making their way slowly into mainstream application development. The reason of their slower adoption is, it is difficult to prove the correctness of these techniques while implementing on certain data-structures like hashtables. But fortunately, for the Managed IOCP queue that is used heavily by multiple-threads, there are matured and well tested lock-free algorithms.
The Lock-Free queue that I implemented to use in Managed IOCP is built on one of the matured algorithms for designing the Lock-Free queue data structure. As we discussed earlier, we need two physical operations to perform a single enqueue (push) operation on a queue. So what we need to check is that, while we read the then next node of the current tail and assign our new node to it, no other thread should have modified the next node of the current tail. So, the read and exchange of the next node of the current tail should either succeed or fail atomically. The synchronization primitive provided by .NET (supported by hardware and Windows OS), CAS, is a perfect fit for this situation. I discussed about CAS in detail in section 4.2 of my first article on Managed IOCP (read section 1 for details on links to my first article on Managed IOCP).
Also, the loss of data that I discussed in this section is solved using a trailing tail technique. In this technique, after step-3 in above discussed sequence, the current tail's next node will be pointing to the new node created by Thread-A. So when Thread-B starts its enqueue operation, it can check if the current tail's next node is null. If it is not, it means that some other thread has changed the current tail's next node, but it has not yet modified the tail itself. So Thread-B would advance the _trailing_ current tail to point to the tail's own next node as Thread-A would anyway do it when it is given a CPU time slice by the OS. Now, Thread-B could restart its enqueue operation. When Thread-B successfully changes the current tail's next node, it can break out of this next node checking loop and point the tail to its new node, provided some other thread has not already advanced the tail during the next node checking step in the enqueue operation.
null
The code below demonstrates this trailing tail technique used to achieve lock-free enqueue operation:
public void Enqueue(object data)
{
Node tempTail = null;
Node tempTailNext = null;
Node newNode = _nodePool.GetObject() as Node; //new Node(data);
newNode.Data = data;
do
{
tempTail = _tail as Node;
tempTailNext = tempTail.NextNode as Node;
if (tempTail == _tail)
{;
}
else
{
// This condition occurs when we have failed to update
// the tail's next node. And the next time we try to update
// the next node, the next node is pointing to a new node
// updated by other thread. But the other thread has not yet
// re-pointed the tail to its new node.
// So we try to re-point to the tail node to the next node of the
// current tail
//
Interlocked.CompareExchange(ref _tail,tempTailNext,tempTail);
}
}
} while (true);
// If we were able to successfully change
// the next node of the current tail node
// to point to our new node, then re-point
// the tail node also to our new node
//
Interlocked.CompareExchange(ref _tail,newNode,tempTail);
Interlocked.Increment(ref _count);
}
One interesting point to note in the above code is that I used CAS (Interlocked.CompareExchange) on object types. This is a beautiful feature supported by .NET. This form of CAS will compare the object reference value pointed to by the first parameter, with that of the comparand, which is the third parameter, and will make the first variable point to the object specified in the second parameter. The downside of the current Interlocked.CompareExchange on object types is that you cannot use variables of your own reference types with this .NET API. So, I had to use the object data type to define my data members in the Node class and for the head and tail object references in the ManagedIOCP class. As you can observe in the above code for the Enqueue method, this leads to type casting of variables from the object to the Node type.
Interlocked.CompareExchange
object
Node
ManagedIOCP
Enqueue
You can check out the lock-free Dequeue operation in the source code. After reading the above discussion, it would be easy to understand the lock-free Dequeue (pop) operation. I have also provided code comments to help the reader understand the logic behind the code.
Dequeue
I have run the same WinForms based demo application using Managed IOCP compiled with the Lock-Free queue implementation on a Pentium IV 3.0 GHz HT system and a Pentium III 700 MHz single processor system. The results are slightly better compared to the .NET synchronized Queue. I noticed good reduction in lock contention in the console demo application provided with this article, when using Managed IOCP with the Lock-Free queue (using the Performance Monitor application) when compared to using Managed IOCP with the .NET synchronized Queue class. I did not see noticeable benefits in terms of speed. This may be because of the fact that my demo applications are just used as a testing bed for verifying the feature correctness of Managed IOCP and other Sonic.Net classes, and stress testing them to identify any hidden multi-threading bugs. I'm positive that when used in real application scenarios with good processing in the threads, Managed IOCP with Lock-Free queue should perform better.
I believe that despite all the optimizations I discussed regarding the lock-free queue, the performance gained by using it varies based on its usage environment. So I request developers using Managed IOCP to test their application using both the .NET synchronized Queue and my custom implemented Lock-Free queue, to get a feel of the performance of both the queue classes.
Object Pooling is a technique that allows us to re-use existing objects again and again with different states. For example, in the Lock-Free queue data structure, I have a Node object that represents a node in the queue. But the only usage of the Node object is to hold the objects that are pushed onto the queue. After an object is popped out of the queue, the Node object holding it has no active references and will be garbage collected by the CLR at some point of time.
It would be efficient if I can re-use the Node object for other push operations, after its contained object is popped out of the queue. This way, I can reduce a lot of new object allocations, thus reducing the GC activity within the application. This will also increase the overall performance of the application as there would be less number of objects to garbage collect and the CLR will not hinder the execution of the application frequently for garbage collection.
But to maintain the list of freed-up Node objects, we need a data structure that can maintain a queue, which does not require new Node allocations. This special queue would act like a linked list, where we can insert new links at the top and remove links from the bottom (FIFO). This queue is special because when an object, in our case Node, is pushed onto it, it does not create a new Node to hold it. It assumes the objects pushed onto it contain a link member that can be used to link up the next Node in the queue. With this assumption, it can use the objects pushed onto it as Nodes by themselves. For this purpose, I created a type called "PoolableObject" that has a data member that points to an object of the same type (PoolableObject). So if I push an object of "PoolableObject" onto our Object Pool queue, it will just point our new object's link data member to the current top element of the queue, thus making our new object the top of the queue. When you pop out the object from this queue, it will just return the bottom object of the queue, and will set the link data member of the previous element of the bottom element to null, thus making it the bottom most element ready to be popped out.
PoolableObject
The code below shows the definition of the "PoolableObject" type. Any type whose objects need to be pooled can derive from this type.
/// <summary>
/// Poolable object type. One can define new poolable types by deriving
/// from this class.
/// </summary>
public class PoolableObject
{
/// <summary>
/// Default constructor. Poolable types need to have a no-argument
/// constructor for the poolable object factory to easily create
/// new poolable objects when required.
/// </summary>
public PoolableObject()
{
Initialize();
}
/// <summary>
/// Called when a poolable object is being returned from the pool
/// to caller.
/// </summary>
public virtual void Initialize()
{
LinkedObject = null;
}
/// <summary>
/// Called when a poolable object is being returned back to the pool.
/// </summary>
public virtual void UnInitialize()
{
LinkedObject = null;
}
internal object LinkedObject;
}
The above mentioned PoolableObject type is used by a class called ObjectPool that provides us with a mechanism to store objects in a pool. This class provides us with methods to add new objects to the pool and retrieve existing objects from the pool. This ObjectPool class is implemented using the special FIFO Lock-Free queue that we talked about in the beginning of this section. This queue does not allocate Nodes to hold the poolable objects, rather it uses the object queued onto it as a Node by itself. For this reason, we said that we need a type that provides us with the ability to link itself to an object of the same type. Here comes the "PoolableObject" type defined in the above code snippet.
ObjectPool
The above definition of PooledObject is simple. It has a default no-argument constructor for easy creation of poolable objects by a factory class named PoolableObjectFactory (I'll explain this in a moment). It has a virtual Initialize method that can be overridden by the derived classes to perform any initialization. This method is called by ObjectPool class when a new poolable object is created by the poolable object factory and when the ObjectPool class is returning an object from its object pool queue. It has a virtual UnInitialize method that can be overridden by the derived classes to perform any un-initialization. This method is called by ObjectPool when a poolable object is being added to its object pool queue.
PooledObject
PoolableObjectFactory
Initialize
UnInitialize
As I mentioned above, I'm using a factory class, PoolableObjectFactory, to create new objects that are derived from the PoolableObject type. I need this because initially when a new ObjectPool is created, there will not be any objects in its pool. So when an application asks it for an object from its pool, it silently creates a new object and will return it to the caller. But for the ObjectPool to create a new poolable object, it does not know about the type of the object that is derived from the PoolableObject. This is application specific, and only the application that created a new type from the PoolableObject type knows what type of objects it will pool using the ObjectPool class. So, I provided an abstract factory type called PoolableObjectFactory, which can be implemented by developers to create and return the objects of their poolable type. As mentioned above in this section, the poolable types that the developers create should be derived from the abstract poolable type "PoolableObject".
The code below shows the definition of the PoolableObjectFactory type:
/// <summary>
/// Defines a factory interface to be implemented by classes
/// that creates new poolable objects
/// </summary>
public abstract class PoolableObjectFactory
{
/// <summary>
/// Create a new instance of a poolable object
/// </summary>
/// <returns>Instance of user defined
/// PoolableObject derived type</returns>
public abstract PoolableObject CreatePoolableObject();
}
The above section (section 3) discussed most of the details about PoolableObject and PoolableObjectFactory. In this section, I'll show you a practical implementation of the PoolableObject and PoolableObjectFactory types. This section will help you build your own poolable objects in your .NET applications that can be managed and pooled for you by the ObjectPool class.
As I mentioned in my previous section (section 3), the Node type used by the Lock-Free queue is a poolable object. It is derived from the PoolableObject type. It also shows a simple implementation of the Initialize method of the PoolableObject type by derived classes. The code below shows the definition of the Node type.
/// <summary>
/// Internal class used by all other data structures
/// </summary>
class Node : PoolableObject
{
public Node()
{
Init(null);
}
public Node(object data)
{
Init(data);
}
public override void Initialize()
{
Init(null);
}
private void Init(object data)
{
Data = data;
NextNode = null;
}
public object Data;
public object NextNode;
}
In the above definition of the Node class, you can see the overridden method Initialize of the PoolableObject class in bold. I did not override the PoolabelObject::UnInitialize method as the Node class need not do any un-initialization work. Instead, the default one provided by the PoolableObject class is sufficient. Remember that the derived class implementation of UnInitialize should call the base class (PoolableObject) UnInitialize method, as it does an important job of setting its Link data member to null. This is important for the proper functioning of the ObjectPool class.
PoolabelObject::UnInitialize
Link
Once we define a new poolable type, we need to provide an implementation of the abstract PoolableObjectFactory that will be used by the ObjectPool class to create new poolable objects when required. The code below shows an implementation of the PoolableObjectFactory class that I used to create new instances of the poolable Node type.
/// <summary>
/// Factory class to create new instances of the Node type
/// </summary>
class NodePoolFactory : PoolableObjectFactory
{
/// <summary>
/// Creates a new instance of poolable Node type
/// </summary>
/// <returns>New poolable Node object</returns>
public override PoolableObject CreatePoolableObject()
{
return new Node();
}
}
Now we have a type (Node) that is poolable using the ObjectPool class, and a type (NodePoolFactory) that can be used by ObjectPool to create new instances of our poolable Node type when required. Now, to use poolable Node objects, it is as simple as creating an instance of the ObjectPool class and providing it a reference to an instance of the NodePoolFactory class. Below is a code snippet showing the creation of a ObjectPool instance, taken from the Lock-Free queue class.
NodePoolFactory
private ObjectPool _nodePool =
new ObjectPool(new NodePoolFactory());
Once the ObjectPool is instantiated, we can get an object of our poolable object type (Node) from the pool by using the GetObject() instance method of the ObjectPool class. The code below shows how to use the ObjectPool class to get the objects from the pool.
GetObject()
Node newNode = _nodePool.GetObject() as Node;
When we are done with a poolable object, we should give it back to the pool so that it can be re-used later. We can add an object back to the pool by calling the AddToPool() instance method on the ObjectPool class. For instance, in the Lock-Free queue class, once an object is popped out of the Queue, the Node holding that object can be re-used to hold any new object to be enqueued onto the Queue. So, just before leaving the Dequeue operation, we add the Node object to the Node object pool maintained by the Queue class.
AddToPool()
_nodePool.AddToPool(tempHead);
The above diagram shows the design of ManagedIOCP and its relation to the Lock-Free ObjectPool and the Lock-Free Queue.
Thread Pools have been an integral part of applications with a good amount of asynchronous and parallel computing requirements. Generally, server side applications use Thread Pool for a consistent and easy to use programming model for executing tasks in parallel and asynchronously. With Managed IOCP as the core technology, I built a Thread Pool that not only provides basic thread management but few other important features as listed below:
Before getting into the inside implementation of the ManagedIOCP Thread Pool, I'll describe its usage in a .NET application. Firstly, ManagedIOCP executes objects that implement an interface named ITask. The definition of the ITask interface is shown below:
ITask
/// <summary>
/// Interface used by ThreadPool class for executing
/// Tasks dispatched to it
/// </summary>
public interface ITask
{
/// <summary>
/// Executes the corresponding task
/// </summary>
/// <param name="tp">ThreadPool onto which
/// this Task is dispatched</param>
void Execute(ThreadPool tp);
/// <summary>
/// Specifies to the ThreadPool whether to Execute this task based on whether
/// this Task is Active or not. This allows for cancellation of Tasks after
/// they are dispatched to ThreadPool for execution
/// </summary>
bool Active {get;set;}
/// <summary>
/// Indicates the task that its execution has been completed.
/// </summary>
void Done();
}
As shown from the above definition, the Execute method is where the logic for executing the task should be written. Once you have a type implementing the ITask interface with logic in its Execute method, using the ManagedIOCP Thread Pool is as simple as creating an instance of it and dispatching the ITask objects onto it. When a ITask object is chosen by the Thread Pool for execution, it will call the Execute method on the object. The code below shows a dummy implementation of the ITask interface and how to use it with the ManagedIOCP Thread Pool.
Execute
public class MyTask : ITask
{
#region ITask Members
public void Execute(Sonic.Net.ThreadPool tp)
{
// Do Some Processing
// TODO::
// Dispatch more objects to Thread Pool if required
MyTask objTsk = new MyTask();
tp.Dispatch(objTsk);
}
public void Done()
{
// May be you can pool this object, so that it can
// be re-used
// TODO::
}
public bool Active
{
get
{
return _active;
}
set
{
_active = value;
}
}
#endregion
// By default one can choose the ITask object to be active
// or not. In this sample I chose it to be active by default
private bool _active = true;
}
The above code shows a type MyTask that implements the ITask interface. If you observe the code, the Execute method has a ThreadPool object as parameter, so that the object being executed by the Thread Pool has access to the ThreadPool object itself for any further dispatching of objects onto the Thread Pool that is executing the current task object.
MyTask
ThreadPool
Also, the ITask interface has two other important members. The Done method is called by the Thread Pool, when the Execute method on a ITask object is completed. This gives a chance to the ITask object to perform any clean-up or pool itself for re-use (this is a powerful concept, and I'll discuss this shortly in the 'Task Framework' section). The Active property indicates the Thread Pool whether to execute this ITask object (whether to call the Execute method) or not. So if an application, after dispatching an ITask object to the Thread Pool, for some reason decides to cancel the task execution, it can set the task object's Active property to false, thus canceling the task execution, provided the task object has not already been executed by the Thread Pool.
Done
Active
false
The code below shows how to create an instance of the Thread Pool in the first place, and dispatch a MyTask object to it for asynchronous and parallel execution:
// Create a new instance of the ManagedIOCP Thread Pool class
// with 10 maximum threads and 5 concurrent active threads
ThreadPool tp = new ThreadPool(10,5);
// Create a new new instance of MyTask object and dispatch it
// to the Thread Pool for asynchronous and parallel execution
ITask objTask = new MyTask();
tp.Dispatch(objTask);
The ManagedIOCP Thread Pool is implemented as a simple wrapper around the core ManagedIOCP class. When an instance of a ManagedIOCP Thread Pool is created, it internally creates an instance of ManagedIOCP, creates all the maximum number of threads, and will register those threads with the ManagedIOCP instance. When a thread of the Thread Pool retrieves an object from the ManagedIOCP instance of the Thread Pool, it will cast the object to a ITask object and will call the Execute method on it.
If you observe the constructor of the ThreadPool class, it has a second form of constructor that takes in a delegate named ThreadPoolThreadExceptionHandler. When a handler is provided for this parameter, if a Thread Pool thread encounters any exceptions while executing the ITask object, it will call this delegate and will continue processing other objects. In case the handler throws any exception, the exception is ignored. If no handler is provided for this delegate, then the thread will ignore the exception and will still continue processing other objects.
ThreadPoolThreadExceptionHandler
Creating all the maximum threads at once for each Thread Pool instance will not be an overhead on the system. Because, the number of active threads in a ManagedIOCP Thread Pool is controlled by the concurrency limit of the Thread Pool, which is specified during the instantiation of a Thread Pool instance and which can also be set at runtime. There could be situations where the active number of threads retrieve ITask objects from the ManagedIOCP instance of the Thread Pool, and while processing them, might go into wait mode (not-running). This could happen if the Execute method of the ITask object is calling into a Web-Service synchronously, etc. When this happens, if there are any pending ITask objects in its queue, the ManagedIOCP instance of the Thread Pool will wake-up other sleeping threads for processing those objects. While these extra threads are processing the ITask object, the earlier threads that went into sleeping mode while executing their ITask objects could come out of sleeping mode and start running. This will create a state in the Thread Pool where more than the allowed concurrent number of threads will be running at a given point of time.
This above discussed situation can be eliminated by having the max. number of threads in the Thread Pool equivalent to the number of allowed concurrent threads. But this may reduce the scalability of the application. This is because if all running threads are waiting on external resource/triggers/events like web service calls, though the application is idle, it will not be able to service any pending requests.
Having the max. number of threads greater than the allowed concurrent threads in the Thread Pool is always desired to scale the application under loads and utilize the system resources as much as possible and as long as possible. In order to balance out the burst situations and the idle situations, ManagedIOCP used by ThreadPool has built in support for suspending un-wanted IOCPHandles that are registered with it. When a IOCPHandle is coming into wait state, if the number of current active threads are greater than or equal to the number of allowed concurrent threads, then the IOCPHandle is queued onto a suspended queue. This way though the number of max. threads in the ThreadPool is greater than the allowed concurrent threads, the threads that are waiting for processing the requests would be closer to the allowed concurrent threads. This would not stop the actual active threads being greater than the allowed concurrent threads, but would keep the difference at minimal levels. When a new object is dispatched to ManagedIOCP, if the current active thread count is less than the allowed concurrent thread count _and_ if the registered IOCPHandle count is greater than or equal to the allowed concurrent thread count, the ManagedIOCP will try to get a suspended thread (IOCPHandle). If it finds one, the thread is chosen for handling the dispatch by setting its IOCPHandle's wait event. This situation may occur if there are a few objects to be dispatched than the allowed concurrent threads _or_ some of the active threads went into waiting mode. In either case, waking up any unsuspended thread may not be an overhead, and by all means should be able to handle the idle situation discussed in this section.
IOCPHandle
This way Dynamic ManagedIOCP should be able to handle both burst and idle situations that are common in IOCP based ThreadPool designs. Dynamic ManagedIOCP is not enabled by default in the Sonic.Net library. The code related to Dynamic ManagedIOCP is inside the conditional compilation constant DYNAMIC_IOCP. The Dynamic ManagedIOCP can be enabled by specifying the conditional compilation constant named DYNAMIC_IOCP in the Sonic.Net class library project properties.
DYNAMIC_IOCP
Task Framework provides an extensible framework for creating tasks that are to be executed by the ManagedIOCP Thread Pool. It provides abstract base classes with implementation for the Active property and the Done method of the ITask interface. These abstract base classes provide different varieties of tasks, like, waitable task, context bound task and waitable context bound task. Also, each abstract task class is derived from the PoolableObject type, thus providing task pooling. Each abstract task type has an associated abstract factory class to create instances of the corresponding task type. These abstract task factory types maintain a pool of task objects.
All the abstract task classes in the Task Framework are derived from a single abstract base class named Task. This abstract base class implements the Active property and the Done method of the ITask interface and is the one that implements the PoolableObject abstract class. Other abstract task classes derive from this class and provide their own capabilities like waiting on task completion, context binding, etc. All the abstract factory classes for creating different classes of task objects are derived from a single abstract base class named TaskFactory. This abstract base class provides task object pooling. This abstract base class is in-turn derived from PoolableObjectFactory, whose abstract methods have to be implemented by applications that wish to use the Task Framework.
Task
TaskFactory
The diagram below shows the ManagedIOCP ThreadPool Task framework:
The diagram below shows the ManagedIOCP ThreadPool Task Factory framework:
GenericTask abstract class provides a basic implementation of the ITask interface for a task to be executed by the Thread Pool. GenericTask abstract class is derived from the Task abstract class, so that it provides features like canceling the task execution by setting the Active property value to 'false'. GenericTask is an abstract class because it does not implement the Execute method of the ITask interface. It is upto the application using the GenericTask to derive from it and implement the Execute method as required. The code below shows a class that is derived from GenericTask and implements the Execute method:
GenericTask
public class MyGenericTask : GenericTask
{
public override void Execute(ThreadPool tp)
{
// Task execution code goes here
// TODO::
}
}
Once we have the application specific generic task class, we can create an instance of it and dispatch it to the ThreadPool.
MyGenericTask gt = new MyGenericTask();
// tp is an instance of ManagedIOCP ThreadPool class
tp.Dispatch(gt);
We can use TaskFactory and its derived abstract classes to create/acquire instances of the GenericTask class. The advantage is that these abstract factory classes provide object pooling of task objects. The code below shows a class that is derived from GenerictaskFactory and implements the GetObject method. This factory creates/acquires instances of an application specific GenericTask class.
GenerictaskFactory
GetObject
class MyGenericTaskFactory : GenericTaskFactory
{
public override PoolableObject CreatePoolableObject()
{
return new MyGenericTask();
}
}
Once we have the application specific GenericTask class and associated GenericTaskFactory class, we can create/acquire instances of the application specific GenericTask class and dispatch them to the ThreadPool.
GenericTaskFactory
MyGenericTaskFactory gtf = new MyGenericTaskFactory();
MyGenericTask gt = gtf.NewGenericTask(null, null);
// tp is an instance of ManagedIOCP ThreadPool class
tp.Dispatch(gt);
The first null parameter passed to the NewGenericTask method of the GenericTaskFactory class is the ID given to the task. This can be set to a valid non-object for uniquely identifying the task. The second null parameter is any application related object that needs to be associated with the task. This can be used to pass additional information associated with the task, which can be used during its execution.
NewGenericTask
The WaitableTask abstract class provides a task on which the application can wait for a task to be executed by the Thread Pool, after dispatching the task to the Thread Pool. The creation and usage of WaitableTask class is same as that of GenericTask. WaitableTask does not have its own factory class, as it is an extension of GenericTask and provides a waitable mechanism to wait on the completion of the underlying GenericTask. Wait on the WaitableGenericTask supports time-out in milliseconds. If time-out occurs during wait operation, the Wait method on the WaitableGenericTask class will return 'false'. The code below shows how one can wait on the WaitableGenericTask:
WaitableTask
WaitableGenericTask
Wait
MyGenericTaskFactory gtf = new MyGenericTaskFactory();
MyWaitableGenericTask gt = gtf.NewGenericTask(null, null);
// tp is an instance of ManagedIOCP ThreadPool class
tp.Dispatch(gt);
// Wait infinitely on the task to complete
bool bTimeOut = gt.Wait(-1);
The ContextBoundGenericTask abstract class provides a task whose execution is serialized with other tasks within the same context. Context provides a logical locking/unlocking mechanism, which can be used by tasks executing under a context. When a task locks the associated context during execution, other tasks trying to lock the context will be suspended until the task that locked the context unlocks it. The ManagedIOCP Task Framework has an interface named IContext that represents a context. The Task Framework also has a default implementation of the IContext interface named Context. The Context class provides locking and unlocking semantics using the Monitor synchronization object.
ContextBoundGenericTask
IContext
Context
Monitor
The creation and usage of ContextBoundGenericTask class is same as that of the GenericTask. A separate factory class named ContextBoundGenericTaskFactory is provided with the Task Framework. Applications have to derive from the ContextBoundGenericTaskFactory class and implement its CreatePoolableObject method to create/acquire instances of classes derived from the ContextBoundGenericTask class.
ContextBoundGenericTaskFactory
CreatePoolableObject
One additional step in creating the ContextBoundGenericTask derived class is that, the code implemented in the Execute method of the derived class should lock and unlock the context object available in the base ContextBoundGenericClass as a property named Context.
ContextBoundGenericClass
The code below shows how to create and use an application specific ContextBoundGenericTask class:
// Application specific ContextBoundGenericTask class
public class MyContextBoundGenericTask : ContextBoundGenericTask
{
public override void Execute(ThreadPool tp)
{
Context.Lock();
// Task execution code goes here
// TODO::
Context.UnLock();
}
}
// Application specific ContextBoundGenericTaskFactory class
public class MyContextBoundGenericTaskFactory :
ContextBoundGenericTaskFactory
{
public override PoolableObject CreatePoolableObject()
{
return new MyContextBoundGenericTask();
}
}
// Create an instance of the task factory
MyContextBoundGenericTaskFactory ctxGTF =
new MyContextBoundGenericTaskFactory();
// Create a new Context. Each context
// object may have a unique id, which can be
// retrieved using a context id generator
// singleton class provided by Task framework
object ctxId =
ContextIdGenerator.GetInstance().GetNextContextId();
Context ctx = new Context(ctxId);
// Create/Acquire an instance of application
// specific ContextBoundGenericTask object
// and associate the context with it
MyContextBoundGenericTask ctxGT =
ctxGTF.NewContextBoundGenericTask(null, null,ctx);
// Dispatch the task to ThreadPool for execution.
// tp is an instance of ManagedIOCP ThreadPool class
tp.Dispatch(ctxGT);
Below are the details of files included in the article's ZIP file:
Sonic.Net
Sonic.Net
|
--> Assemblies
|
--> Solution Files
|
--> Sonic.Net
|
--> Sonic.Net Console Demo
|
--> Sonic.Net Demo Application
The Assemblies folder contains the Sonic.Net.dll (contains the ThreadPool and ObjectPool classes). uses a file that will be read by the ThreadPool threads. Please change the file path to a valid one on your system. The code below shows the portion.
To summarize, we now have a Sonic.Net library that provides Lock-Free data structures like Queue and ObjectPool, asynchronous and parallel programming infrastructure classes like ManagedIOCP, ThreadPool and a Task Framework. Apart from these classes, there is a small utilities class named StopWatch that comes with the Sonic.Net assembly. The StopWatch class can be used to measure the elapsed time easily in a convenient manner. Check it out in case you are interested. Apart from the test applications I have provided with this class library, I believe that the real test for this type of class library is a good real-world server side application. I request users of this class library to provide any feedback/suggestions to fix bugs and improve it.
StopWatch
I'm working on a version of Sonic.Net for .NET 2.0. I'm moving Managed IOCP to a _Generic_ class with the data to be queued, defined as a template parameter. In this context, I had to use my lock-free queue for queuing objects onto Managed IOCP, as .NET 2.0 does not yet support synchronized Generic collections. I'm creating a lock-free Generic (templated) queue to be used in generic Managed IOCP. As soon as I complete, I will update this article with new code and share my experience on using .NET 2.0 Generics. Also the most exciting part of .NET 2.0 is that it supports Generic (templated) Interlocked.CompareExchange. This means the data members in our Node class and head and tail node object references in our Managed IOCP class can be of Node type rather than object type. This would be efficient and would save some type casting overhead during runtime.
Fixed an issue related also .NET synchronized Queue for holding data objects
tempTailNext = tempTail.NextNode as Node; // tempTailNext is null
...
// *** The current thread get suspended and a consumer remove the current node and move it to the pool
// *** now we have a pointer in to other queue (or in to nowhere) and can still be NULL
....;
// *** We consider that we have updated our node successfully but actually we have updated that somthing
// *** that has nothing to do with our queue.
}
public class QueueTest
{
public static void Go(uint count, uint threadCount)
{
_Count = count;
_Queue = new Queue();
Thread thread;
for (uint index = 0; index < threadCount; index++)
{
thread = new Thread(new ThreadStart(QueueTest.ThreadRoutine));
thread.Start();
}
}
public static void ThreadRoutine()
{
Console.WriteLine(String.Concat("START THREAD ", Thread.CurrentThread.GetHashCode().ToString()));
bool empty = false;
DateTime startTime = DateTime.Now;
for (uint index = 0; index < _Count; index++)
{
_Queue.Enqueue(new Object());
_Queue.Dequeue(ref empty);
}
Console.WriteLine(String.Concat("END THREAD ", Thread.CurrentThread.GetHashCode().ToString(), " (", DateTime.Now.Subtract(startTime).ToString(), ")"));
}
private static uint _Count;
private static Queue _Queue;
}
General News Suggestion Question Bug Answer Joke Praise Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
|
http://www.codeproject.com/Articles/11609/Managed-I-O-Completion-Ports-IOCP-Part-2?fid=215360&df=10000&mpp=25&noise=3&prof=True&sort=Position&view=Thread&spc=Relaxed
|
CC-MAIN-2016-18
|
refinedweb
| 6,715
| 50.97
|
Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
Like everything metaphysical, the harmony between thought and reality is to be found in the grammar of the language.
—Ludwig Wittgenstein
I played with an idea, and grew willful; tossed it into the air; transformed it; let it escape and recaptured it; made it iridescent with fancy, and winged it with paradox.
—Oscar Wilde
Objectives
In this chapter you’ll:
• Mark up data using XML.
• Learn how XML namespaces help provide unique XML element and attribute names.
• Create DTDs and schemas for specifying and validating the structure of an XML document.
• Create and use simple XSL style sheets to render XML document data.
• Retrieve and manipulate XML data programmatically using JavaScript.
|
http://my.safaribooksonline.com/book/-/9780132990455/15dot-xml/ch15
|
CC-MAIN-2013-48
|
refinedweb
| 128
| 55.44
|
Internet Engineering Task Force (IETF) C. Everhart
Request for Comments: 6641 W. Adamson
Category: Standards Track NetApp
ISSN: 2070-1721 J. Zhang
Google
June 2012
Using DNS SRV to Specify a Global File Namespace with NFS Version 4
Abstract. Background ......................................................3
2. Requirements Notation ...........................................3
3. Use of the SRV Resource Record in DNS ...........................3
4. Integration with Use of NFS Version 4 ...........................5
4.1. Globally Useful Names: Conventional Mount Point ............5
4.2. Mount Options ..............................................6
4.3. File System Integration Issues .............................6
4.4. Multicast DNS ..............................................7
5. Where Is This Integration Carried Out? ..........................7
6. Security Considerations .........................................7
7. IANA Considerations .............................................9
8. References ......................................................9
8.1. Normative References .......................................9
8.2. Informative References ....................................10
1. Background
Version 4 of the NFS protocol [RFC3530] introduced the fs_locations
attribute. Use of this attribute was elaborated further in the NFSv4
minor version 1 protocol [RFC5661], which also defined an extended
version of the attribute as fs_locations_info. With the advent of
these attributes, NFS servers can cooperate to build a file namespace
that crosses server boundaries. The fs_locations and
fs_locations_info attributes are used as referrals, so that a file
server may indicate to its client that the file name tree beneath a
given name in the server is not present on itself but is represented
by a file system in some other set of servers. The mechanism is
general, allowing servers to describe any file system as being
reachable by requests to any of a set of servers. Thus, starting
with a single NFSv4 server, using these referrals, an NFSv4 client
could see a large namespace associated with a collection of
interrelated NFSv4 file servers. An organization could use this
capability to construct a uniform file namespace for itself.
An organization might wish to publish the starting point for this
namespace to its clients. In many cases, the organization will want
to publish this starting point to a broader set of possible clients.
At the same time, it is useful to require that clients know only the
smallest amount of information in order to locate the appropriate
namespace. Also, that required information should be constant
through the life of an organization if the clients are not to require
reconfiguration as administrative events change, for instance, a
server's name or address.
2. Requirements Notation
The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT",
"SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this
document are to be interpreted as described in [RFC2119].
3. Use of the SRV Resource Record in DNS
Providing an organization's published file system namespace is a
service, and the DNS [RFC1034][RFC1035] provides methods for
discovery of that service. This standard defines a mapping from a
DNS name to the NFS file system(s) providing the root of the file
system namespace associated with that DNS name; such file systems are
called "domain root" file systems. From such file systems, like
other NFS file systems, an NFS client can use the standard NFS
mechanisms to navigate the rest of the NFS file servers that make up
the file system namespace for the given domain.
Such domain root file systems are mounted at a conventional point in
the NFS client namespace. The mechanism results in a uniform cross-
organizational file namespace, similar to that seen in both AFS
[AFS][RFC5864] and Distributed Computing Environment / Distributed
File System (DCE/DFS) [DFS]. An NFS client need know only the domain
name for an organization in order to locate the file namespace
published by that organization.
The DNS SRV RR file systems for the domain's root. An
NFS client may then interpret any of the exported root file systems
as the root of the file system published by the organization with the
given domain name.
The domain root service is not useful for NFS versions prior to
version 4, as the fs_locations attribute was introduced only in NFSv4
(as described in Section 1).
In order to allow the NFSv4 servers as given to export a variety of
file systems, those file servers MUST export the given domain's root
file systems at "/.domainroot/{Name}" within their pseudo-file
systems, where the "{Name}" is the name of the organization as used
in the SRV RR.
As an example, suppose a client wished to locate the root of the file
system resulting domain names nfs1tr.example.net and nfs2ex.example.net
indicate NFSv4 file servers that export the root of the published
namespace for the example.net domain. In accordance with RFC 2782
[RFC2782], these records are to be interpreted using the Priority and
Weight field values, selecting an appropriate file server with which
to begin a network conversation. The two file servers would export
file systems that would be found at "/.domainroot/example.net" in
their pseudo-file systems, which clients would mount. Clients then
carry out subsequent accesses in accordance with the ordinary NFSv4 file system protocols could make use of the same domain root
abstraction, but it is necessary to use file
system(s) in that name in the special directory. The goal is that
NFSv4 applications will be able to look up an organization's domain
name in the special directory, and the NFSv4 client will be able to
discover the file system that the organization publishes. Entries in
the special directory will be domain names, and they will each appear
to the application as a directory name pointing to the root directory
of the file system published by the organization responsible for that
domain name.
As noted in Section 3, the domain root service is not useful for NFS
versions prior to version 4.
4.1. Globally Useful Names: Conventional Mount Point
In order for the inter-organizational namespace to function as a
global file namespace, the client-side mount point for that namespace
must be the same on different clients. Conventionally, on Portable
Operating System Interface (POSIX) machines, the name "/nfs4/" is
used so that names on one machine will be directly usable on any
machine. Thus, the example.net published file system would be
accessible as
/nfs4/example.net/
on any POSIX client. Using this convention, "/nfs4/" is the name of
the special directory that is populated with domain names, leading to
file servers and file systems that capture the results of SRV record
lookups.
4.2. Mount Options
SRV records are necessarily less complete than the information in the
existing NFSv4 attributes fs_locations [RFC3530] or fs_locations_info
[RFC5661]. For the rootpath field of fs_location, or the fli_fs_root
field of fs_locations_info, NFS servers MUST use the "/.domainroot/
{Name}" string. Thus, the servers listed as targets for the SRV RRs
MUST export the root of the organization's published file system as
the directory "/.domainroot/{Name}" (for the given organization Name)
in their exported NFS namespaces. For example, for organization
example.net, the directory "/.domainroot/example.net" would be used.
Section 11 of the NFSv4.1 document [RFC5661] describes the approach
that an NFS client should take to navigate fs_locations_info
information.
The process of mounting an organization's namespace should permit the
use of what is likely to impose the lowest cost on the server. Thus,
the NFS client SHOULD NOT insist on using a writable copy of the file
system if read-only copies exist, or a zero-age copy rather than a
copy that may be a little older. The organization's file system
representatives can be navigated to provide access to higher-cost
properties such as writability or freshness as necessary, but the
default use when navigating to the base information for an
organization ought to be as low-overhead as possible.
4.3. File System Integration Issues
The result of the DNS search SHOULD appear as a (pseudo-)directory in
the client namespace. namespace cache as a
symbolic link, pointing to the fully qualified name. This will allow
pathnames obtained with, say, getcwd() to include the DNS name that
is most likely to be usable outside the scope of any particular DNS
abbreviation convention.
4.4. Multicast DNS
Location of the NFS domain root by this SRV record is intended to be
performed with unicast by using the, by first discovering
the appropriate file system to mount and then mounting it in the
specified place in the client namespace before returning control to
the application doing a lookup. The result of the DNS lookup should
be cached (obeying Time to Live , rather than the
legitimate Security Extensions file systems).
file system is being sought, and a hostname given in the target of
the DNS SRV RR. Thus, in the example above, two file servers
(nfs1tr.example.net and nfs2ex.example.net) are located as hosting
the root file system for the organization example.net. To
communicate with, for instance, the second of the given file servers,
Generic Security Service Application Program Interface file system file system
IANA has assigned namespace.
Reference (REQUIRED) This document
Port Number (OPTIONAL)
Service Code (REQUIRED for DCCP only)
Known Unauthorized Uses (OPTIONAL)
Assignment Notes (OPTIONAL)5178] Williams, N. and A. Melnikov, "Generic Security Service
Application Program Interface (GSS-API)
Internationalization and Domain-Based Service Names and
Name Type", RFC 5178, May 2008.
[RFC5179] Williams, N., "Generic Security Service Application
Program Interface (GSS-API) Domain-Based Service Names
Mapping for the Kerberos V GSS Mechanism", RFC 5179,
May 2008.
[RFC5661] Shepler, S., Ed., Eisler, M., Ed., and D. Noveck, Ed.,
"Network File System (NFS) Version 4 Minor Version 1
Protocol", RFC 5661, January 2010.
[RFC5864] Allbery, R., "DNS SRV Resource Records for AFS", RFC 5864,
April..
Authors' Addresses
Craig Everhart
NetApp
800 Cranberry Woods Drive, Ste. 300
Cranberry Township, PA 16066
USA
Phone: +1 724 741 5101
W.A. (Andy) Adamson
NetApp
495 East Java Drive
Sunnyvale, CA 94089
USA
Phone: +1 734 665 1204
Jiaying Zhang
Google
604 Arizona Avenue
Santa Monica, CA 90401
USA
Phone: +1 310 309 6884
Previous: RFC 6640 - IETF Meeting Attendees' Frequently Asked (Travel) Questions
Next: RFC 6642 - RTP Control Protocol (RTCP) Extension for a Third-Party Loss Report
|
http://www.faqs.org/rfcs/rfc6641.html
|
CC-MAIN-2020-29
|
refinedweb
| 1,669
| 51.58
|
Routing Messages from Bridges to Destinations in the BizTalk Service Project
Updated: November 21, 2013
One of the obvious reasons for connecting various components of a BizTalk Service project is to route the message from one component to another. There’s another requirement though – you might need to route the message from one source component to more than one destination component based on your business logic, which can also be termed as the routing condition. When there are more than one routing conditions, you also need to set the order in which the routing conditions are honored. And finally, there can be some actions (like assigning values to message headers, adding custom headers, etc.) that you perform on the message before it finally gets routed to the destination. This topic discusses these aspects in detail and also provides instructions how to achieve these in a BizTalk Service project.
We will try to understand the steps in this topic using an example scenario. Assume that an XML message in the following format has to be processed using a XML One-Way Bridge.
<PaymentHistory xmlns: <BaseData> <Amount>10.4</Amount> <CurrencyCode>CurrencyCode_0</CurrencyCode> <EntryDate>1999-05-31</EntryDate> <EntryTime>13:20:00.000-05:00</EntryTime> <PaymentMode>Mode_0</PaymentMode> <StatusCode>StatusCode_0</StatusCode> <PurposeCode>PurposeCode_0</PurposeCode> </BaseData> </PaymentHistory>
The business logic is such that if the payment mode is a credit card, the message must be routed to a one-way external service; if the mode is cash, the message must be routed to a one-way relay endpoint; and if the mode is neither of these, it must be routed to a Service Bus queue.
This is fairly straightforward. You must define the route destination where the incoming message gets routed to after being processed by the bridge. There are some considerations regarding where a message from an XML One-Way Bridge or an XML Request-Reply Bridge can be routed to. For more information about these considerations, see Constraints on Using an XML One-Way Bridge and Constraints on Using an XML Request Reply Bridge.
The following procedure describes how to connect two components of a message flow.
Create a BizTalk Service project, as described in Create a BizTalk Service Project.
Add components to the BizTalk Service project, as described in various topics under Configure Rich Messaging Endpoints on Azure.
Click the Connector component under the Bridges category on the Toolbox.
Take the mouse pointer to the right-end of the component (marked by a red dot when you move the cursor over the component) that will act as the source of the message. The mouse pointer changes to show a small “S” sign denoting that this component will add the source of the message. Click and hold the mouse at the dot, drag it to the left end of the target component (at this point the cursor will change again to show a small “T” denoting the target), and then release the mouse. The two components will now be connected. Note that you can connect one source component to more than one target component.
Going by the example scenario, you must connect the XML One-Way Bridge to a one-way external service, a one-way relay endpoint, and a Service Bus queue.
Apart from connecting two components, the other important aspect of routing is to route the message from one source component to more than one destination component based on your business logic.
Going by the example scenario explained above, the routing condition must be based on the mode of payment, which is denoted by the PaymentMode element in the XML message. To implement this business logic in a BizTalk Service project, we need to create routing filters for each condition. The following procedure describes how to do so.
The following procedure describes how to set the routing conditions in a BizTalk Service project.
Right-click the route connector between XML One-Way Bridge and the one-way external service, and then click Properties. In the Properties pane, for the Filter Condition property, click the ellipsis (…) button to the open the Route Filter Configuration dialog box.
In the dialog box, select the Filter option, and then specify the following filter string:
Note that PaymentMode is the property that you must have specified for extraction in the Enrich stage and this filter condition (which is specified on the connector between XML One-Way Bridge and one-way external service) specifies that the message will be sent to the one-way external service, if this filter condition is met.
Click OK to save the changes and exit.
Similarly, for the connector between XML One-Way Bridge and one-way relay endpoint, specify the filter string as:
If the payment mode is neither cash nor credit card, the message should be routed to a Service Bus queue. To achieve that in your message flow, for the connector between XML One-Way Bridge and Service Bus queue, you must open the Route Filter Configuration dialog box, and then select Match All. This specifies that if neither of the filter conditions matches, this filter condition will be honored and the message will be routed to a Service Bus queue.
In the previous section we set the filters on the route connectors to ensure that the right messages get routed to the right components of a message flow. However, the order of routing is equally important. For example, going by the scenario we discussed earlier, if a message that has PaymentMode set to credit_card is routed to the filter condition that has Match All set, it will get routed to a Service Bus queue instead of the one-way external service endpoint. So, according to the business logic, the Match All condition should be honored last. You can do so by setting the order in which the filter conditions must be honored.
Right-click the XML bridge (XML One-Way Bridge or XML Request-Reply Bridge) and select Properties. In the Properties pane, click the ellipsis (…) button against the Route Ordering Table property.
The Route Ordering Table dialog box displays the default order of honoring the route filters. This default order is the order in which you created the route connectors. To re-order the route filters, select a route filter and then use the up and down arrow buttons to arrange them in the right order. You must repeat this step for all the route filters until you have the correct route order that you want.
Click OK to save the changes and exit.
You might want to add some custom message headers or assign values to standard message headers before sending the message to the message receiver. You can do so using Route action. For more information, see Route Action.
To continue with the example used above, assume that the message has to be sent to the one-way external service with a custom SOAP header (CustomerName) and a value.
Right-click the route connector between the bridge and the one-way external service, and then click Properties. In the Properties pane, for the Route Action property, click the ellipsis (…) button to the open the Route Actions dialog box.
In the Route Actions dialog box, click Add to open the Add Route Action dialog box. In the Add Route Action dialog box, do the following:
Click OK in the Add Route Action dialog box. The dialog boxes should now resemble the following:
So what does this dialog box depict? It means that the bridge would use the value of property P1 (already defined in one of the previous Enrich stages) and assign it to the custom SOAP header, CustomerName with namespace then send it out to the message receiver.
To update or remove a route action, you can select it in the dialog box and then click Edit or Remove respectively. Click OK in the Route Actions dialog box and then click Save to save changes to a Bridge Configuration.
See Also
|
http://msdn.microsoft.com/da-dk/library/498de1a4-3427-4314-a152-8d5a7f026cc0
|
CC-MAIN-2014-35
|
refinedweb
| 1,329
| 58.62
|
18 September 2009 16:47 [Source: ICIS news]
HOUSTON (ICIS news)--US chemical production rose strongly in August, with gains in basic chemicals and pharmaceuticals offsetting declines in agricultural chemicals, consumer products and specialties, the American Chemistry Council (ACC) said on Friday.
Production rose by 0.8% in August, following revised gains of 0.2% in July and 0.5% in June, the ACC said in its weekly economic report .
“The industrial production report removed any lingering doubts about a trough and end to the recession,” the ACC said. “Moreover, the report suggests the economy is recovering faster than expected.”
The gains were particularly strong in basic chemicals, where bulk petrochemicals and organic intermediates were up 2.2% in August from July, the ACC said. Pharmaceuticals rose 1.9%.
However, specialty chemicals production fell 1.3% as strength in coatings failed to offset weakness in adhesives and other specialty segments, the group said.
Plastic resin output remained relatively flat, rising 0.2%.
On a year-over-year basis, production was off 8.5% for basic chemicals and 19.1% for specialties, according to the ACC.
Capacity utilisation increased 0.7 percentage points in August to 71.3% from July. It was down from 74.8% in August 2008, the ACC said.
Meanwhile, a pair of manufacturing surveys indicated positive prospects for future growth. The Empire State Manufacturing Survey, prepared by the New York Federal Reserve, had its general business conditions index increase 6.8 points to 18.9 in August from July, its highest level since late 2007.
Any reading above 0 indicates expanding regional business activity.
In addition, future indexes remained relatively high and close to August levels, suggesting that conditions were expected to improve further in the months ahead, the ACC said. The survey’s future conditions index gained 4.1 points to 52.3, its highest level in several years, according to the ACC.
The ?xml:namespace>
Likewise, the Business Outlook Survey prepared by the Philadelphia Federal Reserve showed current business activity rising by 9.9 points to 14
|
http://www.icis.com/Articles/2009/09/18/9248802/us-aug-chem-production-rises-on-strength-in-basics.html
|
CC-MAIN-2015-18
|
refinedweb
| 342
| 52.87
|
Microsoft Business Connectivity Services (BCS) is a feature of Microsoft Office 2010 and SharePoint 2010 that helps developers and users bring data into SharePoint. Surfacing external data in SharePoint enables users to build composite applications that give them better access to critical information and make their interactions with that information more convenient.
BCS provides three basic mechanisms that you can use to bring external data into SharePoint. First, you can connect to and consume databases via SQL queries. By default, SQL Server is supported. With some work, you can connect to MySQL, Oracle and other database-management systems.
Second, you can consume Web services that expose methods that follow specific patterns for the method prototypes.
Third, you can use the Microsoft .NET Framework and C# or Visual Basic code to connect to data sources. The most common approach is to write a .NET Assembly Connector.
In this article, I’ll show you the third approach: writing a .NET Assembly Connector that consumes an Open Data Protocol (OData) feed.
With the burgeoning proliferation of OData feeds, you may need to consume one of those feeds to enable interesting functionality for your users. BCS doesn’t have a built-in capability to consume OData feeds, but it’s relatively easy to write a .NET Assembly Connector to do so.
This is also a convenient approach for demonstrating how to write a .NET Assembly Connector. Another approach would be to write a custom connector to consume a SQL database, but this is superfluous because BCS can easily consume SQL data sources out of the box. Further, to demonstrate writing a .NET Assembly Connector that consumes a database requires that you install and configure the database appropriately. This is not difficult, but it adds some extra steps and complicates the example. In contrast, writing a .NET Assembly Connector that consumes an existing OData feed could not be simpler.
This example also shows you how to implement Create, Read, Update and Delete (CRUD) operations using OData. You’ll see just how easy this is.
You’ll probably be surprised to see just how little code you need to write in order to create a .NET Assembly Connector that consumes an OData feed. Data-access technologies have come a long way, and OData promises to enable a new level of interoperability between applications that produce and consume data.
Note that SharePoint designer is another approach to model, develop and publish BCS external context types. SharePoint Designer natively supports building business entity models from back-end SQL databases and Web services with relatively flat data structure. Use of SharePoint Designer simplifies (and reduces) BCS development work. However, it does not natively support OData services currently.
OData is a Web protocol for querying and updating data that builds upon existing Web technologies such as HTTP, Atom Publishing Protocol (AtomPub) and JSON. OData is being used to expose and access information from a variety of sources including relational databases, file systems, content management systems and traditional Web sites. For a good introduction to OData, see “Building Rich Internet Apps with the Open Data Protocol” (msdn.microsoft.com/magazine/ff714561), from the June 2010 issue of MSDN Magazine. The article was written by Shane Burgess, one of the program managers in the Data and Modeling Group at Microsoft.
SharePoint Foundation 2010 and SharePoint Server 2010 expose list data as an OData feed. This functionality is enabled by default. If you have a SharePoint site installed at the URL, you can retrieve the set of SharePoint lists for the site by entering into your browser.
If your corporate SharePoint 2010 site includes the My Site feature and your alias is, say, ericwhite, you can see the lists exposed on your My Site by entering into your browser. In either case, you’ll see an atom feed like the one in Figure 1 displayed in the browser.
Figure 1 OData from a SharePoint List
With the .NET Framework, a simple way to consume an OData feed is to use WCF Data Services. You use Visual Studio to add a service reference to the OData feed, and the IDE automatically generates code so you can use strongly typed classes to query and update the feed. I’ll walk you through this process.
For more information about how this works, see the WCF Data Services Developer Center (msdn.microsoft.com/data/bb931106), which has a beginner’s guide and links to resources.
As I mentioned earlier, SharePoint 2010 exposes list data as OData feeds. An easy way to access the feeds is through a .NET Assembly Connector, and I’m going to walk you through the process of building that connector.
This process will create an external content type that you can display and maintain in an external list. This might seem a little bit funny—after you have the example working, you’ll have a SharePoint site that contains two lists with exactly the same data. One of the lists will be a SharePoint list that you create and set up in the usual way. The other list will be an external list that displays the data coming from the OData feed for the first list. If you add or alter records in one of the lists, the changes show up in the other one.
The primary benefit of this approach is that it’s simple to build and run the example. You don’t need to install any infrastructure for the example. All you need is a SharePoint farm for which you have farm administrator access.
If you don’t already have the infrastructure, the easiest way to run the example is to download the 2010 Information Worker Demonstration and Evaluation Virtual Machine (). The virtual machine, or VM, comes complete with an installed, working copy of SharePoint 2010, Visual Studio 2010, Office 2010 and much, much more. The example demonstrated in this article works without modifications in this VM.
If you have your own SharePoint 2010 development environment, it’s easy to modify this example appropriately (I’ll indicate where as I go along). However, if you’re just getting started with SharePoint development and want to try out a few examples, the VM is the way to go.
The first step in building this example is to become familiar with using OData to manipulate data in a SharePoint list. In this example, you’re connecting to a customer relationship management (CRM) system that exposes a customer list using OData.
First, create a SharePoint list that contains a few records that represent customers.
Now, log into the VM as administrator and start Visual Studio 2010. Create a new Windows Console Application. For building these OData samples, it doesn’t matter whether you build for .NET Framework 4 or .NET Framework 3.5. However, when building the .NET Assembly Connector later, you’ll need to target .NET Framework 3.5 because it’s the only version currently supported by SharePoint 2010. To have Visual Studio generate classes with good namespace names, name this project Contoso.
Later in this article, I’ll discuss namespace names for both OData and BCS .NET Assembly Connectors. There are specific things you can do to generate namespace names properly, and in this case, the namespace name will make the most sense if you name the project Contoso.
On the Visual Studio menu, click Project, then click Add Service Reference. Enter the OData service URL of the SharePoint site in the Add Service Reference dialog box. If you’re using the demo VM, the service URL is.
If you’re connecting to a SharePoint site at a different URL, you’ll need to adjust the service URL as appropriate.
Click Go. Visual Studio will attempt to go to the location and download metadata from the SharePoint site. If successful, it will display the service name in the Services list in the Add Service Reference dialog box. Because you’re simulating a CRM system, enter Crm into the Namespace field. Click OK. It’s interesting to examine the generated code. Click the Show All Files button in the Solution Explorer window, then expand the Crm namespace, expand Reference.datasvcmap and open Reference.cs. It’ll look something like this (comments removed for clarity):
namespace Contoso.Crm {
public partial class TeamSiteDataContext :
global::System.Data.Services.Client.DataServiceContext {
...
Because of how you named the project and the service reference namespace, the namespace for the generated classes is Contoso.Crm. The fully qualified name of the class for the Customers list is Contoso.Crm.Customers, which makes sense.
Also note the generated name for the data context. In this case, it’s TeamSiteDataContext. The generated name of this class is based on the name of the SharePoint site that you connect to. In the case of the demo VM, the name of the default site that you connect to is Team Site. If your environment is different, note the name of the data context class so that you can alter code in examples appropriately.
Open Program.cs and update it with the code shown in Figure 2. If you’re not using the demo VM, adjust the OData service URL accordingly. Compile and run the program to see the results of the query. As you can see, it doesn’t take a lot of code to retrieve data from a list using OData.
Figure 2 Updated Code for Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using Contoso.Crm;
class Program {
static void Main(string[] args) {
TeamSiteDataContext dc =
new TeamSiteDataContext(new Uri(
""));
dc.Credentials = CredentialCache.DefaultNetworkCredentials;
var customers =
from c in dc.Customers
select new {
CustomerID = c.CustomerID,
CustomerName = c.CustomerName,
Age = c.Age,
};
foreach (var c in customers)
Console.WriteLine(c);
}
}
Now let’s try inserting a customer. Your code will need to create a new CustomersItem and initialize its values. Then it calls the TeamSiteDataContext.AddToCustomers method, passing the CustomersItem object as a parameter. Finally, to commit changes you’ll call the TeamSiteDataContext.SaveChanges.
In Program.cs, replace the customers variable declaration and foreach loop with the following code:
CustomersItem cust = new CustomersItem();
cust.CustomerID = "JANE08";
cust.CustomerName = "Jane";
cust.Age = 22;
dc.AddToCustomers(cust);
dc.SaveChanges();
To update a customer, you’ll query the Customers list, retrieving the specific customer to update. Then update properties as appropriate. Call the TeamSiteDataContext.UpdateObject method. Finally, call the TeamSiteDataContext.SaveChanges to commit changes:
CustomersItem cust = dc.Customers
.Where(c => c.CustomerID == "BOB01")
.FirstOrDefault();
if (cust != null) {
cust.CustomerName = "Robert";
dc.UpdateObject(cust);
dc.SaveChanges();
}
To delete a customer, query the Customers list, retrieving the specific customer to delete. Call the TeamSiteDataContext.DeleteObject method. Call the TeamSiteDataContext.SaveChanges to commit changes:
CustomersItem cust = dc.Customers
.Where(c => c.CustomerID == "BILL02")
.FirstOrDefault();
if (cust != null) {
dc.DeleteObject(cust);
dc.SaveChanges();
}
As you can see, altering a SharePoint list using OData is simple.
In the process of building the .NET Assembly Connector, you define a class that represents the entity that you’ll expose as an external content type. In this example, you define a Customer class that represents an item in the Customers list. Some methods, such as the method to create a customer, take an instance of this class as an argument. Other methods, such as the method to return all customers in the list, return a collection of instances of this class.
You’ll also configure a BCS model that describes this class in an XML dialect. The infrastructure underlying BCS will use the information in the XML definition of the BCS model so that the external content type is usable from within SharePoint 2010.
If there’s one key point you should take away from this article, it’s this: You must make the model match the actual defined class exactly.
There are tools that help you make the BCS model definition match the actual class. However, the key point is that through one approach or another, you need to carefully validate that the model matches the actual class.
In a more typical BCS implementation, you’ll define many of these classes and model all of them in the BCS model definition. The bulk of the work when implementing a complex BCS solution is to make the model match the classes.
Now let’s build the connector. For this example you’ll just build a read-only .NET Assembly Connector, but once you’ve seen the basics, it should be straightforward to add the rest of the CRUD functionality.
The code download for this article includes the code and the BCS model for CRUD functionality; it works without modification in the demo VM.
Log into your SharePoint development computer as administrator. You must have farm administrator rights to build and deploy a .NET Assembly Connector.
Start Visual Studio 2010. Create a new project. Create a new SharePoint 2010 Business Data Connectivity (BDC) Model application. As before, you must target the .NET Framework 3.5. Name the project Contoso and click OK. Again, we’ll use the project name Contoso, which will be used in the namespace.
In the SharePoint Customization Wizard you can enter a local site URL of a SharePoint site for debugging. In this wizard on the demo VM, the URL is correctly set by default to. Change this URL if you’re working with a SharePoint site at a different address. The wizard also lets you know that this project will be deployed as a farm solution. Click Finish. Wait a bit for the wizard to run.
Rename the BDC model nodes in the Solution Explorer from BdcModel1 to ContosoBdcModel.
Next, open the BDC Explorer pane (by default right next to the Solution Explorer). Rename the three BdcModel1 nodes to ContosoBdcModel. In the BDC Explorer, you can’t directly rename each node in the tree control. Instead, you need to select each node and then modify the name in the Properties pane (see Figure 3).
Figure 3 Changing Model Names
The next step is to rename the entity and specify the identifier for the entity. Select Entity1 in the BDC Designer. After selecting the entity, you can change its name in the Properties pane. Change its name to Customers, and change its namespace to Contoso.Crm.
In the BDC Designer, click on Identifier1, and change its name to CustomerID. You also need to design the entity in the BDC Explorer. This part needs to be done precisely. If there’s a mismatch between the BDC model and the actual class that you’ll be using, the results are undefined, and error messages are not always illuminating. In some cases, your only clue to what is wrong is that the list Web Part for the external content type won’t load.
Expand the nodes in the BDC Explorer until you can see the Identifier1 node under the id parameter of the ReadItem method. Change its name to CustomerID. Expand the tree until you can see the Entity1 node under the returParameter for the ReadItem method. Change the name of the entity to Customers, and change the type name to Contoso.Crm.Customers, ContosoBdcModel.
You’re going to completely redefine the Customer entity, so delete the Identifier1 and Message nodes from the Customers entity.
Right-click on Customers and click Add Type Descriptor. Rename the name of the new type descriptor to CustomerID. By default, the type of a new type descriptor is set to System.String, which is what you want for this example. In the Properties pane, scroll down until you see the Identifier field. Use the drop-down list to change its value to CustomerID.
Again, right-click on Customers and click Add Type Descriptor. Rename to CustomerName. Its type is System.String, which is correct.
Add another type descriptor, rename to Age, and change its type to System.Int32. After making these changes, the BDC Explorer pane will look like Figure 4. Expand the ReadList node, expand the returnParameter node and rename Entity1List to CustomersList. The type name is set to the following:
System.Collections.Generic.IEnumerable`1[[Contoso.BdcModel1.Entity1, ContosoBdcModel]]
Figure 4 The Completed Customers Entity
This syntax, consisting of the back tick followed by the one (`1) is the syntax that represents a generic class with one type parameter. The type that follows in the double square brackets consists of a fully qualified type, as well as the model name of the BDC model that contains the type. Change the type name to:
System.Collections.Generic.IEnumerable`1[[Contoso.Crm.Customer, ContosoBdcModel]]
This corresponds to a type of IEnumerable<Contoso.Crm.Customer>, where the Customer type is found in the ContosoBdcModel.
Delete the Entity1 node that’s a child of the CustomersList node. Copy the Customers entity that you recently configured as a child type descriptor of the returnParameter of the ReadItem method.
Select the CustomersList node that’s under the returnParameter of the ReadList method, and paste the Customers entity.
Return to the Solution Explorer window, and edit the Feature1.Template.xml file. Add a SiteUrl property with a value of the URL of the SharePoint site:
<?xml version="1.0" encoding="utf-8" ?>
<Feature xmlns="">
<Properties>
<Property Key="GloballyAvailable" Value="true" />
<Property Key="SiteUrl" Value="" />
</Properties>
</Feature>
Rename Entity1.cs to Customers.cs. Replace the contents of Customers.cs with the following code, which defines the Customer entity for the assembly connector:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Contoso.Crm {
public partial class Customer {
public string CustomerID { get; set; }
public string CustomerName { get; set; }
public int Age { get; set; }
}
}
Replace the code in CustomersService.cs with the code in Figure 5, which defines the methods that retrieve a single item and retrieve a collection of items.
Figure 5 CustomersService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using Contoso.Crm;
namespace Contoso.Crm {
public class CustomersService {
public static Customer ReadItem(string id) {
TeamSiteDataContext dc = new TeamSiteDataContext(
new Uri(""));
dc.Credentials = CredentialCache.DefaultNetworkCredentials;
var customers =
from c in dc.Customers
where c.CustomerID == id
select new Customer() {
CustomerID = c.CustomerID,
CustomerName = c.CustomerName,
Age = (int)c.Age,
};
return customers.FirstOrDefault();
}
public static IEnumerable<Customer> ReadList() {
TeamSiteDataContext dc = new TeamSiteDataContext(
new Uri(""));
dc.Credentials = CredentialCache.DefaultNetworkCredentials;
var customers =
from c in dc.Customers
select new Customer() {
CustomerID = c.CustomerID,
CustomerName = c.CustomerName,
Age = (int)c.Age,
};
return customers;
}
}
}
Following the procedures that I described at the beginning of this article, add a service reference to the site, specifying a namespace of Crm. Click OK. Build the solution by clicking Build | Build Contoso. Now deploy the solution by clicking Build | Deploy Contoso.
Give permissions for all authenticated users to access this external content type. Open Central Administration, then click Manage Service Applications. Click Business Data Connectivity Service. Click on the down arrow next to the external content type that you just added, and then click Set Permissions. Click the Browse button just below the text box. Click All Users, then click All Authenticated Users. Click the Add button, then click OK.
Back in the Set Object Permissions window, click the Add button, and then set permissions for Edit, Execute, Selectable In Clients and Set Permissions. Click OK.
Browse to the SharePoint site. Create a new External List. Specify CustomersExt for the name of the list. Click on the external content type browser. In the External Content Type Picker, click on the external content type you just created. If you’re using the demo VM, the content type you just created will be the only external content type in the list. Click OK.
Click the Create button, wait a bit and, if all goes well, you’ll see a new external list that contains the same data as the Customers list.
If you add a record to the regular list, you’ll see it show up in the external list. You can play around with the data a bit. Add, delete or change some records in the regular SharePoint list and see the data show up in the external list.
As you’ve seen, it’s pretty easy to use WCF Data Services to query and modify an OData feed. It’s also a straightforward process to create an external content type via a .NET Assembly Connector. You can connect to just about any data source using a .NET Assembly Connector.
This was just a simple example employing a readily accessible data source, but the pattern is easily extended to any data source with an OData feed. To learn more about BCS customization, see the MSDN Library page “Business Connectivity Services How-tos and Walkthroughs” (msdn.microsoft.com/library/ee557949). There’s also a trove of information about OData at the MSDN Data Developer Center (msdn.microsoft.com/data/bb931106) and the Open Data Protocol site (odata.org).
Eric White is an independent software developer and author with 25 years of experience developing enterprise applications on a variety of platforms. He currently specializes in Microsoft Office technologies, including Open XML, SharePoint and Office client development. You can follow him on Twitter at twitter.com/EricWhiteDev or on his blog at ericwhite.com/blog.
Thanks to the following technical experts for reviewing this article: Ying Xiong
More MSDN Magazine Blog entries >
Browse All MSDN Magazines
Receive the MSDN Flash e-mail newsletter every other week, with news and information personalized to your interests and areas of focus.
|
http://msdn.microsoft.com/en-us/magazine/hh148142.aspx
|
CC-MAIN-2014-52
|
refinedweb
| 3,574
| 59.09
|
On Sat, 22 Dec 2001, Jake Burkholder wrote: > Apparently, On Sat, Dec 22, 2001 at 06:48:26PM +1100, > Bruce Evans said words to the effect of; > > 19 Dec 2001 16:01:26 -0000 > > @@ -936,18 +1058,18 @@ > > struct thread *td; > > { > > - struct kse *ke = td->td_kse; > > - struct ksegrp *kg = td->td_ksegrp; > > + struct ksegrp *kg; > > > > - if (td) { > > - ke->ke_cpticks++; > > - kg->kg_estcpu = ESTCPULIM(kg->kg_estcpu + 1); > > - if ((kg->kg_estcpu % INVERSE_ESTCPU_WEIGHT) == 0) { > > - resetpriority(td->td_ksegrp); > > - if (kg->kg_pri.pri_level >= PUSER) > > - kg->kg_pri.pri_level = kg->kg_pri.pri_user; > > - } > > - } else { > > + if (td == NULL) > > panic("schedclock"); > > - } > > + td->td_kse->ke_cpticks++; > > + kg = td->td_ksegrp; > > +#ifdef NEW_SCHED > > + kg->kg_estcpu += niceweights[kg->kg_nice - PRIO_MIN]; > > +#else > > + kg->kg_estcpu++; > > +#endif > > + resetpriority(kg); > > + if (kg->kg_pri.pri_level >= PUSER) > > + kg->kg_pri.pri_level = kg->kg_pri.pri_user; > > } > > I'm curious why you removed the ESTCPULIM and INVERSE_ESTCPU_WEIGHT > calculations even in the OLD_SCHED case. Do these turn out to have > no effect in general?
ESTCPULIM basically breaks scheduling if it is are hit (clipping to it prevents accumulation of hog points that would cause cpu hogs to be run less). This is a problem in practice. I use dynamic limits even in the !NEW_SCHED case. I forgot that I did this or I would have included more context to show it (see below). kg->kg_estcpu is allowed to grow without explicit limit and scaled to fit in the priority range. This requires fixing sorcerer's-apprentice growth of kg_estcpu in fork() and exit(). kg_estcpu has natural limits but they are quite large (a constant multiple of the load average). INVERSE_ESTCPU_WEIGHT is not used because it goes with static scaling, and "% INVERSE_ESTCPU_WEIGHT" optimization (which depends on the internals of resetpriority()) is not so easy to do. Here are the corresponding changes for resetpriority(): %%% 22 Dec 2001 07:34:15 -0000 @@ -844,15 +949,32 @@ register struct ksegrp *kg; { + u_int estcpu; register unsigned int newpriority; mtx_lock_spin(&sched_lock); if (kg->kg_pri.pri_class == PRI_TIMESHARE) { - newpriority = PUSER + kg->kg_estcpu / INVERSE_ESTCPU_WEIGHT + + estcpu = kg->kg_estcpu; + if (estcpu > estcpumax) + estcpu = estcpumax; +#ifdef NEW_SCHED + newpriority = PUSER + + (((u_int64_t)estcpu * estcpumul) >> ESTCPU_SHIFT); +#else + newpriority = PUSER + + (((u_int64_t)estcpu * estcpumul) >> ESTCPU_SHIFT) + NICE_WEIGHT * (kg->kg_nice - PRIO_MIN); - newpriority = min(max(newpriority, PRI_MIN_TIMESHARE), - PRI_MAX_TIMESHARE); +#endif + if (newpriority < PUSER) + newpriority = PUSER; + if (newpriority > PRI_MAX_TIMESHARE) { + Debugger("newpriority botch"); + newpriority = PRI_MAX_TIMESHARE; + } kg->kg_pri.pri_user = newpriority; - } - maybe_resched(kg); + maybe_resched(kg, newpriority); + } else + /* XXX doing anything here is dubious. */ + /* XXX was: need_resched(). */ + maybe_resched(kg, kg->kg_pri.pri_user); mtx_unlock_spin(&sched_lock); } %%% > > Most of the changes here are to fix style bugs. In the NEW_SCHED case, > > the relative weights for each priority are determined by the niceweights[] > > table. kg->kg_estcpu is limited only by INT_MAX and priorities are > > assigned according to relative values of kg->kg_estcpu (code for this is > > not shown). The NEW_SCHED case has not been tried since before SMPng > > broke scheduling some more by compressing the priority ranges. > > It is relatively easy to uncompress the priority ranges if that is > desirable. What range is best? The original algorithm works best with something close to the old range of 50-127 (PUSER = 50, MAXPRI = 127) for positively niced processes alone. This gives unniced processes a priority range of 50-127 and permits nice -20'ed processes to have a much larger (numerically) base priority than unniced ones while still allowing room for their priority to grow (range 90-127). Negatively niced processes were handled dubiously at best (they ran into the kernel priorities). Brian Feldman reduced the priority range for unniced processes to 68-127 and you reduced it some more to 180-223. The main problem with the reduced rangesis that the algorithm gives approximately an exponential dependency of the cpu cycles allocated to a process on the process's niceness. The base for the exponential is invisible and hard to change, so decreasing the range by a factor of 78/44 significantly reduces the effects of niceness. I think my nicewights[] algorithm can handle this. It supports almost any dependency of cycles on niceness. However, I don't know how it can be made to work right for the entire priority range. An exponential dependency would grow too fast for the range 0-255 if it grows fast enough for the user range 180-233. I used the following program to generate (old) niceweights[] tables. Defining EXP gives an exponential table with niceness 0 haveing 32 times as much priority as niceness 20. The default approximates the old -current behaviour (which isn't actually exponential). %%% #include <math.h> main() { int i; for (i = 0; i <= 40; i++) { if (i % 8 == 0) printf("\t"); #ifdef EXP printf("%d,", (int)floor(2 * 3 * pow(2.0, i / 4.0) + 0.5)); #else if (i == 40) printf("65536\n"); else printf("%d,", 2 * 2 * 2 * 3 * 3 * 5 * 7 / (40 - i)); #endif if (i % 8 == 7) printf("\n"); else printf(" "); } } %%% Bruce To Unsubscribe: send mail to [EMAIL PROTECTED] with "unsubscribe freebsd-current" in the body of the message
|
https://www.mail-archive.com/freebsd-current@freebsd.org/msg33199.html
|
CC-MAIN-2018-13
|
refinedweb
| 807
| 53.31
|
Dart padLeft and padRight examples
Introduction :
In this tutorial, we will learn how to use padLeft and padRight methods in dart with different examples. Both of these methods are used to pad a string on the left or right.
padLeft :
This method is defined as below :
String padLeft(int w,[String padding = ' '])
It takes two parameters. The first parameter w is the width of the final string. It pads the string on the left if it is shorter than the given width w.
This method returns one new string. If the width is smaller or equal to the length of the string, it will return the same string. If the value is negative, it will consider this value as zero.
We can also add the different character as the padding. Make sure that the padding character has length 1. For characters like and \u{10002}, it will produce a different result.
Example of padLeft without blank space as the pad character :
import 'dart:io'; void main() { String mainString, finalString; int finalLength; print("Enter a string : "); mainString = stdin.readLineSync(); print("Enter the final length : "); finalLength = int.parse(stdin.readLineSync()); finalString = mainString.padLeft(finalLength); print("Final string :${finalString} with length ${finalString.length}"); }
In this example, we are reading the string and the final length from the user and printing out the final string by padding blank spaces to the left. We are also printing the length of the string after padding is added to the left.
Examples :
Enter a string : hello Enter the final length : 10 Final string : hello with length 10 Enter a string : hello Enter the final length : 15 Final string : hello with length 15
As you can see here, the final length of the string is equal to the length we have entered.
Example of padLeft with a character :
We can also use padLeft with any other character as the padding character. For example :
void main() { String mainString = "hello"; String finalString1 = mainString.padLeft(10,"*"); String finalString2 = mainString.padLeft(10,"\u{10002}"); print("Final string 1 :${finalString1} with length ${finalString1.length}"); print("Final string 2 :${finalString2} with length ${finalString2.length}"); }
It will print the below output :
Final string 1 :*****hello with length 10 Final string 2 :𐀂𐀂𐀂𐀂𐀂hello with length 15
As I have mentioned before, the second example behaves differently with \u{10002}.
padRight :
padRight is similar to padLeft. The only difference is that it pads the characters to the right of a string. It is defined as below :
String padRight(int w,[String padding = ' '])
It takes the width was the first parameter and padding as the second parameter. The second parameter is optional. It pads the string on the right and returns the modified string.
For example :
void main() { String mainString = "hello"; String finalString1 = mainString.padRight(10); String finalString2 = mainString.padRight(10, "*"); String finalString3 = mainString.padRight(10, "\u{10002}"); print("Final string 1 :${finalString1} with length ${finalString1.length}"); print("Final string 2 :${finalString2} with length ${finalString2.length}"); print("Final string 3 :${finalString3} with length ${finalString3.length}"); }
It will print the below output :
Final string 1 :hello with length 10 Final string 2 :hello***** with length 10 Final string 3 :hello𐀂𐀂𐀂𐀂𐀂 with length 15
The first string pads only blank spaces to the right, the second string pads * to the right and the third-string prints a different length, just like the above padLeft example.
Try to go through the examples above and drop one comment below if you have any queries.
|
https://www.codevscolor.com/dart-padleft-padright-example/
|
CC-MAIN-2020-10
|
refinedweb
| 572
| 65.32
|
Odoo Help
Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps:
CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc.
How to get current language in model?
Hi! I'm inheriting class and I want to get there language of current logged in user
class hr_employee(osv.osv):
_name = "hr.employee" _inherit = "hr.employee" _columns = { 'code': fields.char('Code', size=11, select=True) }
How can I do so?
Hi
from pre-defined method
create and
write you can get lang of current user after override that method
for example:
def create(cr,uid,vals,context=None): lang=self.pool.get('res.users').browse(cr,uid,uid).lang.id vals.update({'lang_field':lang}) return (hr_employee,super).create(cr,uid,vals,context)
thanks Sandeep
About This Community
Odoo Training Center
Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now
hi look in file i18n you can create your translation otherwise : you Have Translation in your Form mode developer
I think about it, but I dont know all cases of this field.
Log in Developer Mode. a dropdown at the top left, you will add a translation
|
https://www.odoo.com/forum/help-1/question/how-to-get-current-language-in-model-17460
|
CC-MAIN-2017-51
|
refinedweb
| 204
| 51.24
|
Next() call not being delayed
I have an indicator with a period of 12 being initialized in my strategy.
I am compressing 60 minutes into hour long bars.
Based off of what I read on the wiki - the first next() call should not occur until 12 hours have passed in the data, correct? Yet my next() call is being triggered with only one item in self.data. Is there something I misunderstood with how compression works?
edit: Just tried to remove compression and I still have the same issue. Here is my init function, using most of the boilerplate in oandatest.py
I tried removing compression and this issue still occurs. Below is my strategy init function:
def __init__(self): # To control operation entries self.orderid = list() self.order = None self.counttostop = 0 self.datastatus = 0 # Create SMA on 2nd data self.sma = bt.indicators.MovAv.SMA(self.data, period=self.p.smaperiod) self.atr = bt.indicators.ATR(self.data, period=20) self.highest = bt.indicators.MaxN(self.data, period=12) self.lowest = bt.indicators.MinN(self.data, period=12) self.margin = 0.0025 print('--------------------------------------------------') print('Strategy Created') print('--------------------------------------------------')
Removed for edit
- backtrader administrators last edited by
That code for sure is not enough to tell why
nextis called. But if you are using the
oandatestsample, this sample calls
nextfrom
prenext, because the point is seeing all received data and not waiting for the indicators.
@backtrader Thank you, fixed.
|
https://community.backtrader.com/topic/438/next-call-not-being-delayed/3
|
CC-MAIN-2022-40
|
refinedweb
| 239
| 52.26
|
What is the output of this code snippet?
[python]
def concat(*args, sep="/"):
return sep.join(args)
print(concat("A", "B", "C", sep=","))
[/python]
String concatenation is the process of creating a string by appending string arguments. The given function takes an arbitrary number of string arguments as specified by the
*args keyword. The parameter
sep declares the separator string to clue together two strings. The separator argument is a keyword argument because of the
*args argument can have an arbitrary number of arguments. The keyword argument helps to differentiate whether the last parameter is part of
*args or the
sep argument.
The function
concatenation is a wrapper for the
join function to concatenate strings. The
join function is defined in the string object
sep. It concatenates an arbitrary number of strings using the separator to clue them together. Both functions achieve the same thing, but the first may be more convenient because the separator is a normal argument.
Yet, you will find yourself using the
join function on a regular basis without writing your own wrapper functions. So you can as well learn its proper use now.
Are you a master coder?
Test your skills now!
Related Video
Solution
A,B,C
|
https://blog.finxter.com/daily-python-puzzle-arbitrary-argument-listsstring-concatenation-join-function/
|
CC-MAIN-2020-50
|
refinedweb
| 203
| 58.99
|
Xtreme Visual Basic Talk
>
Visual Basic .NET (2002-2015), including Express editions)
> .NET Communications
PDA
.NET Communications
Pages :
[
1
]
2
3
4
5
6
Sending Email
Winsock
Run-time error '40006' on chat program
Display IP info
UDPClient Timeout
SMS from Excel using VBA
System.Net.Sockets namespace??
help in ip
WMS viewer in VB.net
Serial Ports RS422
need help
Real Time Communication
my Chat server
.NET Web Interface
Can VB.Net manage and view data packets?
RS232 Serial Control NET
Deleting a remote file through FTP
help with using packets
Problems in moving web projects
SOAP,Web-service,INVOKE
Remote Images Possible?
Visual Basic IIS Object
share files
winsock help
vb.net - Finding ip with port
ras ftp
Parabolic Flight Experiment
Bluetooth programming?
how to write a program to authenticate user on all availaible computers on a lan
multiple chatting required
.NET USB programming
Help Sending Email
IRC integration?
winsockvb file transfer
Any Good VB.Net Tutorials On System.Net.Sockets
Set a Static IP using VB.net
Connecting To A Socks4 Proxy
Another CID program
Uninstall Novell Client
NAT Design and Implementation
FTP Uploading...
Get local IP from LocalEndPoint
how to start getting information for this project
bot help
logging on to a server with name and pass
Data Sending and recieving to COM Port
HTTP post method using VB.Net
multicast sockets
How do I check the winsock state in VB.NET?
SetIfEntry
Wireless SendString over IP addresses
LongToIP - IPToLong
Bus Analyser Code?
Send string over network
IP - No Winsck
Opening a webpage and copying its contents
Playing audio input data from a usb port
Computers in network
Mscomm AT commands
TAPI 3.x HANDSET lifting?
Getting input frequencys from Microphone....
Modem not responding
send mail with .net and smtp login
TAPI Problem in VB.NET
Optimum Poll timeout...
send/receive from webpage (possible?)
what is the easiest way
Sending Messages?
username & password with webclient??
Server recieves incorrect data for binary file transfer, how to correct?
Seriel Port -> Customer Display
MSComm OnComm event values
opening outlook within custom application
query remote machine registry
Using certificates with VB.NET
How to create remote notification like MSN mail/user login notification?
Port detection
Way to locate an internal modem and send commands?
Event driven serial communication
If a certian web page is open...
Developing telephonic communication application in vb.net
ITC ( internet transfer protocol ) Basics...
Ftp
Best approach for communication between 2 apps
Automatic defect Internet Connection
dial up connection list
Getting Network Ip's [Read Thread For Extencice Description]
getting the local IP
UDP Broadcasts
Useing cookies with system.net.WebClient
smtp server
System.NullReferenceException Error Message
basic server
Sending Emails
AddressList length problem?
Problem with serial communications in VB.net <Program Hangs when recieving data>
system.web.mail not found ?
Open connection
Open Internetconnection
Making Games Work Online
socket comunication
Newbie winsock question
IRC type app with server & client as one
Connecting over a network
need help with output
Upload file to SERVER
bytes send and received from internet connectiong
Webrequest Question
Please HELP me
simple question
Error, sometimes can't upload files
Soap Problem
html page source cut short
Need help with project: Phone Dialer type program
OO winsock withevents array
Looking for available ports of the PC
Instant Messenging Program
How do I add application to XP Firewall port list using code?
winsock in vb.net?
Unresponsive WebRequest
VB.NET class to send e-mail
Network connections
Obtaining data from a device through the HyperTerminal
Downloading WebPage
Shell to bat file that does Mode Com1
Is there a how to POP3 for .NET ?
.Net Sockets
Hosting
.Net Sockets
.Net Sockets. Some Progress.........
A simple but yet blaffing bug in my VB.NET client program! Help!
Send Email
Send e-mail by VB .NET Windows application
.net unblockable sockets help!
File transfer Client/Server Winsock ?? :S
This would be a nice sockettype to use...
Using cookies when downloading files
How to get Download File name
VB Mail question for you SMTP people.
Is there any way to say "No" to all the incoming cookies?
Frustrating attachment error
How to send/receive a picture file to server using Base64?
How to Screen Scraping login page have redirect link?
Security Topic about Email
Smartphone 2003 SDK problem
Sending E-Mails From a Windows Service
How do I ping a server?
.net to .net
Programming to Download Image
Creating a Folder via ASP.NET
tcpclient ipaddress
program hangs on connection
Transfer images
.NET Communications Example
quick question on winsock and net.sockets
How can i stream audio over the 'net?
Scanning LAN for computers
LAN Messenger Client
TCPListener/Client - STOP!
Dropping data with event drive MSCOMM?
Sending SMS
mscomm
VB.NET: Receive string from the module and use it to the form
Sockets: How to send to specific clients
IPEndPoint problem
sending email using yahoo & hotmail
Indexing website
Receiving email with VB.NET
HTTP Error 401 (Consuming a web service)
HttpWebRequest
sending a structure of integers over a networkstream
IRC questions
TCPClient Buffer Size Problem?
sockets
tcplistener help
Spawn process on a remote machine
ServiceController on Remote Machine
.net remoting help
Port monitoring
Connection state ?
Server on a website
Infrared Help
Untrappable error, Asynchronous sockets
DNS question??
Shared resources in workgroup
Reading Exchange server emails
Which Socket Class should be used??
No HTTP headers
Multiple Connection torcher please help!!
Help with Communication
Help with DLC Control [attached]
Net. Sockets sending a mouse click or a keypress
Chck Internet Connection
get owner for open port
Programming digital I/O-card
webrequest ((getting the size of the file to download
Grabbing certain HTML from a webpage via code
Get File Size .net (Internet File)
VB.NET: Connect and Disconnect using System.Net.Sockets
Automated Remote Computer Management
Downloading pictures
Explain sockets?
inpout32 with XP
How to see SOAP message VB.NET is sending?
how to use an IP in a string with IPEndPoint
Gator Style Drag and Drop
Error on httpserver
how to make a socket raise events???
VB.net + network
P2P in VB.NET
mail from vb.net app using mscorlib
Interfacing Winfax with VB.Net App
Multithreading With Sockets
Listen Event
Simple TCP/IP Client App (similar to IMAP)
Create Dial up connection
UDP Client
rest of code not called after a winsock function
FileClose
Sockets & SocketType in VB.net
Async sockets v select()
My Networking Class
AR send
Access an FTP Site - Receipe problem!
Interesting Internet control problem
Problem with uploading method
new to .net
Username for anonymous user?
Getting VB.NET to email you...
Download File
Wifi data transfer from PC to PDA with vb.net
.NET Receive Buffer
get attachments from echange server
Exporting Data to Excel from VB
ByteArray -> String [im stuck]
Detect Execution from remote
simple socket app
VB.Net Post values and submit to Iternet Form
threads
Can i use TCP to talk to multiple PC's
Help for a new Network project
Upload fiels from Client to Server: How To?
Remoting Objects as Parameters
Not quite sure what to call this... {Serial port or USB}
EZ Archive Ads Plugin for
vBulletin
Computer Help Forum
|
http://www.xtremevbtalk.com/archive/index.php/f-99.html
|
CC-MAIN-2018-34
|
refinedweb
| 1,183
| 59.3
|
I am trying to replace an entire description string contained in an XML file. I would like to replace that string with a variable. I am using a SED command within a Groovy script.
I have the following code. I am expecting the string "foo" to replace the description text but it doesn't.
Instead the following line causes the XML to change to:
Description="sDescription"
What am I doing wrong?
def sDescription = "foo"
def sedCommand = 'sed -i \'s/Description="[^"]*"/Description="'$sDescription'"/g\' package.appxmanifest' as String
In Groovy variable/expression substitution inside of strings (interpolation) only works with certain types of string literal syntax. Single quote syntax (
'content') is not one of them. However, if you replace the outer single quotes with double quotes (
"content") then you should get the interpolation effect you are looking for:
def sDescription = "foo" def sedCommand = "sed -i 's/Description=\"[^\"]*\"/Description=\"$sDescription\"/g\' package.appxmanifest" as String
This should give you the string that contains the command you wish to run. Please note how I changed the special character escaping (
\) within the string to reflect the change in string delimiters.
Aside: As noted by @tim_yates, Why would you want to invoke a separate ad hoc process to do this substitution when Groovy contains excellent XML manipulation facilities built into the language?
|
https://codedump.io/share/mS3gHp2jNBGJ/1/replacing-string-with-variable-with-groovy-and-sed-command
|
CC-MAIN-2018-09
|
refinedweb
| 217
| 55.54
|
17 October 2011
By clicking Submit, you accept the Adobe Terms of Use.
The article is designed for all levels of Flash users working with files containing TLF text. General knowledge of the Flash workspace and a basic understanding of working with ActionScript 3 is required.
Intermediate
Adobe Flash Professional CS5 introduced a new type of text field to Flash called TLF text. TLF text has several advantages over Classic text, such as advanced formatting options, better font compression and rendering, and support for complexly formatted languages. In order to support TLF text, Adobe Flash Player was updated to change how it loads the related runtime shared libraries (RSLs) and the content you define in the SWF file.
In this article you'll learn about the changes to Flash Player and the best options for publishing files containing TLF text. You'll review key concepts and then follow the instructions to build a sample project to help you visualize how it all fits together. The steps guide you through creating a simple modular banner using a loader SWF file and content SWF files, each of which contains TLF text (click Figure 1 to see an example). Along the way, you'll learn how to build a custom RSL preloader, correctly load content SWF files, and work with ActionScript and FlashVars across multiple SWF files.
Special thanks to Jeff Kamerer at Adobe Systems for his help and suggestions. Be sure to check out Jeff's blog post, Using a custom preloader loop with TLF text, for more related information.
For best results in your projects that use TLF text, it's important to have a solid understanding of what TLF text is and how it works in Flash Player. This section covers key concepts related to TLF text and runtime shared libraries.
The Text Layout Framework (TLF) is a new and more powerful option for displaying text content in Flash. You can use the Property inspector to choose the TLF Text option in Flash while the Text tool is selected (see Figure 2).
TLF text is an authortime representation of the Text Layout Framework (TLF), which is an ActionScript 3 library built on top of the Flash Text Engine (FTE) classes. Essentially it's an extension of the core ActionScript language which adds a wide range of features to the text rendering engine.
New text features include the following:
The fact that TLF is an ActionScript framework "under the hood" means that you can work with TLF text in both a visual mode during authortime in Flash or in ActionScript at runtime. Authortime TLF text provides an enhanced visual interface for working with TLF (see Figure 3).
Flash supplies the TLF library at authortime. A runtime shared library is used to supply the functionality at runtime.
For more information on TLF text basics, see the following resources:
The TLF ActionScript classes are distributed in the form of a runtime shared library (RSL) contained in a SWZ file. By using an external RSL for the ActionScript library, the RSL can be cached locally on end users' machines and reused by all subsequent SWF files. In order for Flash Player to display TLF text, it first tries to load the RSL from the user's local cache, then from adobe.com, and then finally looks for it on the server hosting the SWF file. The RSL is always loaded in Flash Player before the content loads. This can create a delay if the RSL isn't already cached on the user's local computer.
You basically have four options for handling the potential delay of RSL loading. Three of these options involve using a preloader assigned to the file in the Advanced ActionScript 3 Settings (see Figure 4).
Selecting the runtime shared library (RSL) option from the Default linkage menu enables you to choose the preloader options from the fields below it. Your options include the following:
Tip: The source files for the Adobe preloader SWF are located in the Flash application folder on your computer (Adobe Flash CS5.5/Common/Configuration/ActionScript 3.0/rsls/).
Most people probably use the default Adobe preloader option without ever knowing it is there. For most use cases, that's fine, but there are a few exceptions.
The following are considered best practices for working with RSLs:
Preloading RSLs introduces a new timing scheme to control how your Flash content loads in Flash Player. This is generally not a problem but it does create some issues with loading SWF files inside other SWF files, like in a banner system or other kind of modular application.
The primary issues when loading a SWF with an ActionScript 3 Loader object are as follows:
Not to worry—these issues are easy to work around if you know how to do it.
Flash Professional CS5.5 introduces a handful of new ActionScript APIs to handle the needs of SWFs loading RSLs. The new ProLoader and ProLoaderInfo classes should be used as an alternative to the Loader and LoaderInfo classes when loading SWF files containing TLF. The ProLoader and ProLoaderInfo classes provide the same API and functionality as the Loader and LoaderInfo classes, but the Proloader has the ability to manage the preloading of the RSLs and provides the expected behavior when cross-scripting and working with events. The ProLoader is built to make these issues transparent to the end user—and when loading SWF files across security domains, the ProLoader minimizes the occurrences of similar issues. The LoaderContext class was also updated to support the ProLoader class. You'll work with the new parameters property in the next section of this article to learn a convenient way to pass FlashVars parameters to the root timeline of any loaded SWF.
The new ActionScript APIs require Flash Player 10.2 or later to function properly.
For more information on working with the ProLoader class, see Using the ProLoader and ProLoaderInfo classes in the ActionScript 3 Developer's Guide.
If you're still working in Flash Professional CS5, the best strategies involve merging the RSL into the SWF to sidestep the Loader object issues or using the SafeLoader sample files provided on the following TechNote: Loading child SWFs with TLF content generates errors.
In this section you'll learn how to work with RSL preloaders and Flash Professional CS5.5 ActionScript in a banner structure. The banner is a very simple application composed of a loader SWF file and multiple child content SWF files. The loader SWF file loads the content SWF based on a URL supplied in FlashVars, passes the content SWF a reference to the FlashVars for text content, and then calls a transition method on the SWF to fade the content into view. Along the way you'll explore what works and what doesn't work when using TLF text.
There are several key concepts you'll focus on while creating the source files:
parametersproperty of the LoaderContext class to pass FlashVars parameters to the child SWF files
First you'll prepare the source files that make up the sample project. You can use the supplied images in the ZIP file to follow along with the steps below.
By the end of the project, you'll create the following source files:
Follow these steps to get started:
You'll work on the FlashVars and ActionScript code in the next sections, but first you'll start by creating the FLA files.
Since you're building a web-based project, you'll create a custom RSL preloader for this exercise. The custom preloader animation can be built in two different ways:
For this example, you'll create a separate SWF file as a demonstration of the easiest way to customize the animation (see Figure 5).
Follow these steps to set up your custom preloader FLA file:
gotoAndPlay("loop")action on the last frame to allow the animation to loop without returning to Frame 1.
Tip: Be sure to leave 15 frames of empty space on the Timeline before the animation appears. Otherwise you'll see the animation appear briefly when your SWF file loads.
The banner SWF file acts as a loader for the content SWF files. This file is empty except for a TLF text field showing a title. Beyond loading the content SWF files, the banner SWF file can be used to hold any text, content, or functionality that would be used repeatedly across content SWF files. In this case, the title text will appear the same way across any content SWF file loaded. You could also place user interface controls (such as navigation buttons) in the banner FLA or shared functionality like click through areas.
Follow these steps to set up the banner FLA:
Tip: The loader SWF file can share its embedded fonts with the content SWF file. That means that you don't have to embed the Arial Bold again in each SWF file.
Follow these steps to assign the custom preloader SWF file to the banner SWF file:
In the last set of steps, you simply assigned your CustomPreloader.swf file in place of the default Adobe SWF file.
The content FLA files are very simple. They contain a background image and a large TLF text field that gets populated with data supplied in the FlashVars parameters. For simplicity's sake, the images will be scenic pictures and the text will be the name of the location (see Figure 6).
Follow these steps to set up the content FLA files:
Tip: You can set the RSL preloader preferences for the child SWF files too, but theoretically you wouldn't expect a delay since the parent SWF file has already loaded the RSL.
At this point you've created all of the FLA files that will be used in the project. Next you'll set up the HTML page.
The FlashVars parameter is an optional tag that can be added to the HTML markup that embeds the SWF file on the page. You can use it to pass variables to the SWF file at startup, similar to the way URL string variables can be appended to a URL to pass variables to that URL.
The FlashVars parameter looks like this:
<param name="FlashVars" value="&firstname=Dan&lastname=Carr&" />
Notice that the value attribute contains a list of name value pairs separated by ampersands.
Using FlashVars to supply text and URLs to the SWF is a great way to make the application modular. If you're editing by hand, you can manually make changes in a text editor without republishing the SWF files. If you're writing your HTML dynamically, you can change the content and text on the fly on the server. By separating the text values from the content, you could localize the content to different languages or provide dynamic variations of the text per user, and other similar strategies.
Follow these steps to publish the HTML page:
Follow these steps to add the FlashVars parameters:
After making these changes, the object tags in Banner.html should look like this:
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="720" height="300" id="Banner" align="middle"> " /> <!--[if !IE]>--> <object type="application/x-shockwave-flash" data=" Banner" width="720" height="300"> " />
For more information on FlashVars, see the following resources:
Using FlashVars with ActionScript 3 (Peter deHaan)
Use FlashVars to pass variables to SWF files
In this section you'll add functionality to the banner FLA by creating an ActionScript class and assigning it as the Document class of the banner.fla file. This is the equivalent of writing ActionScript code on Frame 1 of the main Timeline, but as you'll see when you get to the code for the content SWF files, you can reuse Document classes across FLA files.
In the next steps you'll create an ActionScript class called Banner.as that can do the following:
Tip: Review the completed files in the supplied banner_project_completed.zip file and use them as a reference as you work through the next sections of this tutorial.
Follow these steps to create the ActionScript class:
package { import fl.display.ProLoader; import flash.display.MovieClip; import flash.events.Event; import flash.net.URLRequest; import flash.system.LoaderContext;
public class Banner extends MovieClip {
//-------------------- // Variables public var pageLoader:ProLoader; public var pageURL:String = "Page1.swf";
//-------------------- // Constructor public function Banner() { // Get page_url FlashVars var url:String = this.loaderInfo.parameters["page_url"]; if( url ){ pageURL = url; } }
// Pass the FlashVars to the ProLoader var lc:LoaderContext = new LoaderContext(); lc.parameters = this.loaderInfo.parameters;
// Create the loader pageLoader = new ProLoader(); pageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onSWFLoaded); pageLoader.load( new URLRequest(pageURL), lc ); addChild(pageLoader); // Bring text to front setChildIndex(state_txt, numChildren - 1);
//-------------------- // Events private function onSWFLoaded( event:Event ):void { // Cross-script with child SWF var content:MovieClip = pageLoader.content as MovieClip; content.transition(); }
Tip: Notice that the code in Step 9 assigns the data types of the content SWF file to MovieClip instead of its Document class type, Page. Use this approach as your simplest solution when cross-scripting from one SWF file to another. The Document class for each SWF file includes auto-generated code for TLF support. If the loader SWF file imports the Page class for data typing, the loader SWF file's version of Page will be used in the content SWF files instead of their own version. The result is that the content SWF files don't have access to the auto-generated TLF code and therefore appear without text formatting.
Follow these steps to assign the Banner class to the Banner FLA file:
In this section you'll create a single Document class for all three child page SWF files. This demonstrates the benefits of using an ActionScript class instead of repeating the same code in each FLA. This workflow also opens up the possibilities of working on your scripts in Adobe Flash Builder or another ActionScript text editor.
In the next steps you'll create an ActionScript class called Page.as that can do the following:
Follow these steps to create the child page ActionScript class:
package { import fl.transitions.Tween; import fl.transitions.easing.Strong; import flash.display.MovieClip; import flash.events.Event;
public class Page extends MovieClip {
//-------------------- // Variables public var pageTween:Tween; public var pageName:Array = "San Francisco, CA";
//-------------------- // Constructor public function Page() { addEventListener(Event.ADDED_TO_STAGE, onAddedToStage); }
//-------------------- // Events private function onAddedToStage( event:Event ):void { // Get page_names FlashVars passed to us from the ProLoader var page_name:String = this.loaderInfo.parameters["page_name"]; if(page_name) { // Split the string to an array pageName = page_name; } name_txt.text = pageName; }
//-------------------- // Methods // Fade in public function transition():void { if( pageTween ) { pageTween.stop(); } pageTween = new Tween(this, "alpha", Strong.easeOut, 0, 1, 2, true); }
That wraps it up for the development tasks to finish the project. Check your work against the completed sample files for accuracy.
For more information on working with ActionScript 3, refer to the following resources:
The last task of the tutorial is to test your work. In a real-world workflow it is important to perform tests along the way many times as you change the files. And be sure to test often when writing ActionScript. It's much easier to identify where issues are, when they occur.
You can use the following approaches for testing the project:
Tip: You can also use the advanced features of Flash Builder to edit and debug the ActionScript code.
The Flash Debugger can be used to find problems in ActionScript when errors occur. When you test the file in the Debugger, it will pause at the point where the code breaks and show you the state of the variables and function call stack. This provides a very handy way of seeing problems that are otherwise difficult to pin point.
Follow these steps to test the project in the debugger:
For more information on debugging ActionScript 3, read my article, Understanding ActionScript 3 debugging in Flash.
The Bandwidth Profiler is a utility attached to the SWF window when you publish the SWF using the Control > Test Movie command (see Figure 8).
Follow these steps to test the RSL preloader animation:
You can also test the project in a browser to see the FlashVars parameters load the content instead of the default parameters.
Follow these steps to test in a browser:
Tip: If you see an ActionScript runtime error when you launch the SWF files from your desktop or within a browser, it may be that you don't have Flash Player 10.2 or later installed on your computer. Make sure you have the latest Flash Player version installed before testing.
That's it! You now have a simple modular banner structure capable of dynamically loading content SWF files, passing data to them, and cross-scripting with them.
The sample project described in this tutorial demonstrates how to work with TLF RSLs in Flash Professional CS5.5. It also provides the foundation structure for building modular Flash applications. You could take it a step further by adding localization features (after all, TLF is designed to render languages that were not possible using Classic text). Take a look at my article, Formatting text for localized Flash projects, for more information.
Another way you could extend the sample project involves adding a custom preloader loop animation to Banner.swf in place of the external preloader SWF file. The benefit of this approach is that you can assign event handlers to the main Timeline of the banner SWF file and show a progress bar animation instead of an indeterminate animation.
To research further, check out Using a custom preloader loop with TLF text by Jeff Kamerer.
Here is also some Flash documentation related to TLF and RSLs:
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.
|
https://www.adobe.com/devnet/flash/articles/preloading-tlf-rsl.html
|
CC-MAIN-2016-07
|
refinedweb
| 2,986
| 60.55
|
Novell has continued to invest in open source software by joining Eclipse. They support Eclipse as a way to deliver a common tooling strategy for Novell developers going forward and to provide a consistent platform for building, testing and debugging applications across the Novell product line.
Novell to Join Eclipse
Novell to Join Eclipse (8 messages)
- Posted by: Dion Almaer
- Posted on: January 22 2004 14:59 EST
Threaded Messages (8)
- Novell to Join Eclipse by Mike Diehl on January 22 2004 16:24 EST
- What? by Kevin Lewis on January 22 2004 17:16 EST
- What? by Michael Mayr on January 22 2004 05:47 EST
- What? by Mike Diehl on January 23 2004 08:02 EST
- Eclipse - could evolve into a Mono IDE by Jochen Krause on January 22 2004 19:09 EST
- Eclipse - could evolve into a Mono IDE by Frans Thamura on January 22 2004 10:33 EST
- So what? by Magnus Alvestad on January 23 2004 04:25 EST
- Ditto! by Denis Baranov on January 23 2004 14:51 EST
Novell to Join Eclipse[ Go to top ]
And no mention whatsoever of the Mono Project in the article. This is another cold shoulder for the proposed .NET open source competitor to Java, and doesn't bode too well for it. Why mention this on a Java site? I guess because it's gotten some ink on TSS over the last couple of days.
- Posted by: Mike Diehl
- Posted on: January 22 2004 16:24 EST
- in response to Dion Almaer
What?[ Go to top ]
I don't understand what you're talking about. What is the relation between Novell and Mono? Why should it have been mentioned? It seems to me this article is a valid candidate for TSS because Eclipse is a widely used Java-oriented IDE.
- Posted by: Kevin Lewis
- Posted on: January 22 2004 17:16 EST
- in response to Mike Diehl
--Kevin
What?[ Go to top ]
Novell owns Ximian. Ximian is the driving force behind Mono which tries to port .NET to Linux. That's all. I don't see any connection with this news either. Some persons seem to read a lot between the lines, while I like to stick to the facts... Nice to see all these companies move to eclipse. I hope there will be an increasing demand for java and eclipse experts ;-)
- Posted by: Michael Mayr
- Posted on: January 22 2004 17:47 EST
- in response to Kevin Lewis
What?[ Go to top ]
A little bit of free association on my part. But since the most active thread on this forum in the last week was partially centered on Mono (see "Opinion: Porting between Java and C#") and Mono is frequently mentioned on TSS, albeit weakly, as the .NET answer to competing with Java on Linux, I made the comment that I did. In other words, it was an insight into the state of a possible competitor to Java on Linux
- Posted by: Mike Diehl
- Posted on: January 23 2004 08:02 EST
- in response to Kevin Lewis
There. That explains that.
Eclipse - could evolve into a Mono IDE[ Go to top ]
It looks like it is Novells strategy to have a common IDE for many of their offerings. This does not exclude Mono, even if it is not mentioned here. I think it is a great movement of Novell to join Eclipse and hopefully contribute to the evolvement of this environment.
- Posted by: Jochen Krause
- Posted on: January 22 2004 19:09 EST
- in response to Mike Diehl
Jochen
Eclipse - could evolve into a Mono IDE[ Go to top ]
Friend,
- Posted by: Frans Thamura
- Posted on: January 22 2004 22:33 EST
- in response to Jochen Krause
This is brand war, now we are in mindset world, Java team do it wel, this make Java stronger. Mono team want to collaborate with Java, :) Mono team must work with Microsoft for this, but.. :) with Eclipse. We know .NET is competitor of Java, and .NEt will more valuable if can run on top of free thing, such as Linux, Ximians do it for Linux, by creating Mono.
So, is there a benefit for Mono, if Novell join Java? Can we say like this. Is Novell is a leader? so he can create something that control the world? Sun did, Sun is Java creator and fasilitator, now Java is community product, we own it.
When will they (Novell, Ximians) do it for us.
So what?[ Go to top ]
I don't get it. What is the point of 'joining eclipse'? I mean, anyone can contribute to the codebase, member or not. Anyone can write plugins, member or not. From what I've seen, technical decisions are made by the active developers (mostly from IBM). The members aren't even contributing financially.
- Posted by: Magnus Alvestad
- Posted on: January 23 2004 04:25 EST
- in response to Dion Almaer
-Magnus
Ditto![ Go to top ]
/** @see BorlandEclipseSupport */
- Posted by: Denis Baranov
- Posted on: January 23 2004 14:51 EST
- in response to Magnus Alvestad
public class NovellEclipseSupport implements SupportEclipseInterface {
public void supportEclipse() {
// todo: do we really need this?
throw new NotImplementedException();
}
}
|
http://www.theserverside.com/discussions/thread.tss?thread_id=23489
|
CC-MAIN-2014-52
|
refinedweb
| 860
| 72.16
|
Quark D2000 I2C Interfacing: Add a Light Sensor and an LCDJanuary 12, 2017 by Raymond Genovese
Get acquainted with using I2C with the Quark D2000 development board by interfacing an ambient light sensor and an LCD.
Get acquainted with using I2C with the Quark D2000 development board by interfacing an ambient light sensor and an LCD.
Previously, we presented a general overview of the Quark D2000 development board. Subsequently, we explored the use of the board’s GPIO and PWM.
In this project, we will explore using I2C with the D2000 board by interfacing an ambient light sensor and a COG (chip-on-glass) LCD.
Since our last report, a new version of the board’s software interface has been released (ISSM_2016.1.067) and some of the documentation has been updated. Be sure to get the resources linked below:
- Using GPIO and PWM on the Quark D2000 development board
- Main Quark D2000 documentation page (links to User Guides, Design Notes, schematic and more)
- Intel Quark Microcontrollers forum
- Intel System Studio forum
- Where to get the Quark D2000 Development Board (1) (2)
Software files for all of the programs in the article can be downloaded by clicking the link bar below:
Basic I2C Programming
To illustrate the most basic use of the D2000 board’s I2C interface, we can compare the procedure to that used with the ubiquitous Arduino Uno. That is, we will interface a BH1750FVI ambient light sensor, using the module shown below, with each board.
The BH1750 ambient light sensor module (left panels) and hookup connections (right panel)
This inexpensive module has been around for a while and is available from several sources (e.g., 1, 2). It’s chosen as an example because the programming to use the board is short and straightforward. Connecting the module is also straightforward (see right panel of the figure above) and it can be used with both 3.3V and 5V systems.
First, connect the board to the UNO and run the included program, BH1750.ino. You should see lux values scrolling on the serial monitor. Looking at the program listing, notice that we first #include wire.h
To initialize the sensor in initBH1750() we use the statements:
(1) Wire.beginTransmission(BH1750addr);
(2) Wire.write(BHmodedata);
and, then (3) Wire.endTransmission()
The statements; 1) set the address of transmission to the sensor using the variable BH1750addr, 2) cue writing the initialization code in the variable BHmodedata to the sensor, and, 3) actually write the data to the sensor.
In the loop() section, we read the sensor using the statements:
(1) Wire.requestFrom(BH1750addr, BYTES2READ);
(2) BHlxdata[0] = (byte)Wire.read(); BHlxdata[1] = (byte)Wire.read();
These statements; 1) send a request to the device to read two bytes of data (the lux value), and 2) read two bytes from the sensor and store them in variables. The program then converts the bytes read to a lux value and prints the value to the serial monitor.
BH1750.c is the analogous program for the D2000 board. After you connect the sensor module, you can compile and run this program by first creating a new project for the D2000 board (make sure you specify QMSI 1.1) in System Studio using an existing template (“Hello World” works fine). Rename it as desired and then copy and paste BH1750.c over the existing code (main.c) and you are ready to Build and Run the program. All of the included D2000 programs will work in this same manner.
To get a sense for how I2C can work on the D2000, we can compare the two programs.
First, instead of including wire.h, we will include qm_i2c.h. This header file and the associated .c file contain the source code for the I2C routines. It is a very good idea to become familiar with these two files if you want to use and understand I2C on the board. You will find them among your installation directories - \IntelSWTools\ISSM_2016.1.067\firmware\bsp\1.1\drivers and IntelSWTools\ISSM_2016.1.067\firmware\bsp\1.1\drivers\include
The function wireBegin() contains the necessary setup calls to use the I2C and the code is listed below.
/* Enable I2C 0 */ clk_periph_enable(CLK_PERIPH_CLK | CLK_PERIPH_I2C_M0_REGISTER); /* set IO pins for SDA and SCL */ qm_pmux_select(QM_PIN_ID_6, QM_PMUX_FN_2); qm_pmux_select(QM_PIN_ID_7, QM_PMUX_FN_2); /* Configure I2C */ I2Ccfg.address_mode = QM_I2C_7_BIT; I2Ccfg.mode = QM_I2C_MASTER; I2Ccfg.speed = QM_I2C_SPEED_STD; /* set the configuration through the structure and return if failure */ if (qm_i2c_set_config(QM_I2C_0, &I2Ccfg)) { QM_PUTS("Error: I2C_0 config\n"); return (errno); } else { return (0); }
First, we enable clocking for I2C. Next, we select the desired function for the I/O pins which will be used for the SDA and SCL I2C lines. In this regard, you can download a handy illustration of the identification of each of the board’s I/O pins and their multiplexed functions.
In the global variables section, we defined a structure with the line: qm_i2c_config_t I2Ccfg.
Our next step is to configure parameters of the I2C using this structure. Specifically, we set the addressing mode to 7-bit, the role to master, and the speed to standard. Finally, we set this configuration by calling the system function, qm_i2c_set_config() with our configuration structure as an argument.
The code lines above make use of definitions that appear in qm_i2c.h. For example; QM_I2C_SPEED_STD set the speed to 100 Kbps, whereas QM_I2C_SPEED_FAST sets the speed to 400 Kbps, and QM_I2C_SPEED_FAST_PLUS sets the speed to 1 Mbps.
Our function initBH1750() reads the sensor values. The integral component of the function is a call to the system function qm_i2c_master_write().
uint8_t BHmodedata[1] = {0x10}; /* BH1750 initialization code for 1 lux resolution */ if (qm_i2c_master_write(QM_I2C_0, BH1750addr, BHmodedata, sizeof(BHmodedata), true, &I2Cstatus)) { return (errno); /* error code (errn) */ }
We defined an array (BHmodedata[]) to hold the data that we want to send and we call the function with arguments for:
- the I2C number (there is only one I2C interface on the board)
- the address of the sensor module (BH1750addr as defined in the global variables section)
- a pointer to the data array (BHmodedata)
- the number of bytes to send (sizeof(BHmodedata))
- stop bit specification (true = send a stop bit)
- the address of a variable to receive the status (&I2Cstatus – defined in the globals section)
Again, see the system file qm_i2c.h for more detailed information on the calls and arguments.
The rest of the program converts the bytes read to a lux value and prints the value to a serial port through System Studio (see the Getting Started guide for instructions on setting up a FTDI serial cable).
Add an I2C LCD
Newhaven NHD-C0220BiZ-FSW-FBW-3V3M LCD
While using an FTDI cable for serial output is convenient, a simple LCD is a necessity for many stand-alone projects. Once we are familiar with basic I2C programming, we can add an LCD without too much difficulty.
I chose a Newhaven NHD-C0220BiZ-FSW-FBW-3V3M available from these sources [1, 2].
The unit is a 3.3 volt, Chip-on-Glass (COG) LCD with a crisp 2 x 20 display. The I2C address is 0x3c (right-shifted 0x78). You will definitely want to get the data sheet for the display as well as the data sheet for the controller, which is an ST7036i.
In addition to the display, only a few other components are required to interface to the D2000 and the schematic below (based on the schematic in the C022BiZ datasheet) shows the entire circuit.
Complete schematic for interfacing the C0220BiZ to the D2000. Click to enlarge.
A couple of points about the schematic are noteworthy. I used 10K pullup resistors on the SDA and SCL lines and the value is recommended by Newhaven (e.g., see here).
I also used jumpers with both pull-up resistors so that a shorting block connector can be positioned to either include (connector on) or exclude (connector off) them from the I2C lines – convenient if you already have pull-up resistors installed somewhere else.
The values for C1 and C2 are recommended in the C022BiZ datasheet and C3 is the usual bypass capacitor. GPIO5 is connected to the reset pin (RST, active low) on the LCD, allowing the software to reset the LCD.
Note that the spacing between the LCD interface pins is 2.0 mm, whereas pin spacing for the holes in common breadboards and perfboard is 2.54 mm (0.100 in). There are several ways of resolving the difference and the way that I chose was to use an adaptor board like that pictured below.
Adapter board for mounting the LCD
The adaptor was designed for XBee products but it has the capability that we need. First, cut the board right down the middle. This will give you two boards suitable for our purpose. Then, you can solder the LCD leads and also a common 2.54 mm spacing header directly to the board. The latter header is breadboard friendly. The adaptor is available here and there are similar ones, like this one, that also looks like it will work.
Since the LCD has only 8 pins and the adapter accommodates 10 pins, you can use the extra two holes to run leads from the anode and cathode pins for the backlight which are on the side of the LCD.
Once the LCD is wired up and attached to the D2000, it is time to test it out. The included program, C0220BiZdemo.c will do just that. After displaying a simple welcome message, it will cycle through the character set. It is useful to check that you have everything wired and connected correctly.
LCD Library
To facilitate using the LCD, I decided to write a small library that is suitable for general use in a variety of projects. That code is included in the software download as C0220BiZ_Lib.h and C0220BiZ_Lib.c. You can examine those files for the details on each of the library functions that are described briefly below.
void LCD_reset(void) — Hardware reset of the C0220BiZ
int LCD_init(void) — Initialize the C0220BiZ
int LCD_clr(void) — Clear the C022BiZ screen
int LCD_home(void) — Set DDRAM address to 0x00
int LCD_display(uint8_t arg) — Turn display on or off
int LCD_cursor(uint8_t arg) — Turn cursor and blink on or off
int LCD_write(const void * message) — Write the character string (null terminated) at the current DDRAM location
int LCD_writexy(uint8_t x, uint8_t y, const void * message) — Write the character string (null terminated) x (column) and the y (line)
int LCD_writedat(uint8_t datum) — Write a single byte to DDRAM (current location)
int LCD_writedatxy(uint8_t x, uint8_t y, uint8_t datum) — Write a single byte at x (column) and y (line)
int LCD_gotoxy(uint8_t x, uint8_t y) — Set DDRAM address to x (column) and y (line)
int LCD_contrast(uint8_t arg) — Set contrast, 0 (low) - 15 (high)
int LCD_ICC(uint8_t addr, uint8_t * chrcode, uint8_t length) — Write custom character data to CGRAM, addr=CGRAM character address 0-7, chrcode= the 8 byte character code array, length = number of bytes in array (normally 8)
To include the library in a project, simply copy C0220BiZ_Lib.h and C0220BiZ_Lib.c into the project folder. Subsequently, use the line, #include "C0220BiZ_Lib.h" in your main.c, and the functions will be visible for use.
The included program, LCDdemo.c, demonstrates the library functions. Along with the library files, examination of this code will further explain the use of the functions. The library is somewhat rudimentary and can certainly be extended and embellished.
An example of the LCD’s custom characters capability, from LCDdemo.c
Closing Thoughts
In this project, we introduced using the I2C interface on the the Quark D2000 development board. We used the simple example of a BH1750 ambient light sensor, contrasting its use with that in the familiar Arduino world. From there, we were able to easily interface an LCD and develop a library of routines for its use.
If you come from the Arduino world, you might, at first, find using I2C on the D2000 board to be much different. With a little experience, however, you may see that, at least at a fundamental level, the basic procedures are not so different. In fact, you'll likely find that the D2000's routines offer more flexibility.
In part 2 of this project, we will conclude our exploration of I2C interfacing on the D2000 board and add a color sensor and a program to identify an object's color. We will also touch on using asynchronous I2C by revisiting the BH1750 ambient light sensor.
|
https://www.allaboutcircuits.com/projects/quark-d2000-development-board-i2c-interfacing-add-light-sensor-lcd/
|
CC-MAIN-2021-25
|
refinedweb
| 2,085
| 62.27
|
This page describes how to build and use XULRunner with the Python extension on Windows and while generally useful it is written based on experiences with accessibility projects. See also XULRunner.
With the Python extensions enabled XULRunner provides python script access to the DOM and XPCOM in addition to the usual Java Script. This gives access to Python features and modules and builds on Mark Hammond's pyXPCOM work from Active State. XPCOM components can also be created in Python.
Currently (Mar 07) Python is not enabled by default so a custom build of Mozilla is needed. This page provides instructions in the hope of eliminating much trial and error. You should also read the the developer documentation on source code and building as wells as PyXPCOM
XULRunner with Python promises to be a good platform for accessibility projects and both Jambu Alternative Input and the IAccessible2 test tool are using it. Of particular interested is access to MSAA and IAccessible2 via the Python comtypes package.
Development Machine Setup
First a word of warning that ZoneAlarm has exhibited memory leaks that cause build machines to crash with rather spurious errors. You may want to uninstall it you suspect this to be a problem. You will also want to disable any virus scanner resident monitoring as that will slow builds.
Ensure the PC is running XP with all the latest Service Packs and patches applied.
Microsoft C++ compiler is required and whilst the current free version is Visual Studio 8 Express (MSVC8) you will almost certainly want to use Visual Studio .NET 2003 (MSVC71) which is not longer officially available. The issue is that XULRunner must be built with the same version of C as Python and with Python 2.5 that is MSVC71. Both must use the same version of the C runtime library MSVCRT?.DLL or crashes will ensue. The alternative is to build Python with MSVC8 as well asMozilla, but that may be problematic. It might also be possible to use the Open Source MinGW compiler with the correct MSVC run time but that is apparently not recommended. Apply any Service Packs and for MSVC71 SP 1 is available. The matching platform SDK is also needed and for MSVC71 that is .NET Framework SDK 1.1.
The latest Mozilla Build system is easy to use. Install the included Python distro using python25\python-2.5.msi. It doesn't need to be installed for the build but will be useful later when installing Python packages which look for entries in the Windows' registry.
Building
The batch file start-msvc71.bat is used to launch the build console (MSys from the MinGw project ). If you plan to checkout often into empty folders you could modify it to set the CVSROOT environment variable.
set CVSROOT=:pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot
Having created a mozilla project directory (e.g. C:\projects\mozilla or /c/projects/mozilla in msys) create the following .mozconfig file. Note this is complete and does not require the checkout of any other project specific .mozconfig files as sometimes shown. It effectively specifies a release build that is not particularly suitable for debugging XULRunner itself. It uses the trunk (or latest) code in CVS so may be unstable.
mk_add_options MOZ_OBJDIR=@TOPSRCDIR@/../obj-xulrunner mk_add_options MOZ_CO_PROJECT=xulrunner ac_add_options --enable-application=xulrunner ac_add_options --enable-extensions=python,default ac_add_options --disable-javaxpcom ac_add_options --disable-activex ac_add_options --disable-activex-scripting ac_add_options --disable-tests ac_add_options --enable-optimize
To check out all the required source code and build it the first time with no local client.mk file, execute
cd /c/projects cvs -d :pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot co mozilla/client.mk cd mozilla make -f client.mk
For subsequent updates from CVS followed by a build, use
cd /c/projects/mozilla make -f client.mk
which will also checkout client.mk itself
For build only, without checkouts, use
make -f client.mk build
and see client.mk for other options.
The built XULRunner can then be found as c:\projects\obj-xulrunner\dist\bin\xulrunner.exe.
Using Python in XUL applications
Add the following to your prefs.js during development
pref("browser.dom.window.dump.enabled", true); pref("javascript.options.showInConsole", true); pref("javascript.options.strict", true); pref("nglayout.debug.disable_xul_cache", true); pref("nglayout.debug.disable_xul_fastload", true);
HTML <script> tags specify that Python is used with type="application/x-python" attribute. DOM scripting is pretty much as with Java Script. For example
def onLoad(): btnTest = document.getElementById("btnTest") btnTest.addEventListener('command', onTest, False) def onTest(): window.alert('Button activated') window.addEventListener('load', onLoad, False)
One possible gotcha is that the default python path used to find modules that are imported explicitly includes the xulrunner executable directory and the directory that is current when XULRunner launches. However it does not include any path related to the XUL application being run. Some work around will need to be found.
Unhandled exceptions are displayed in the JavaScript Error Console which can be opened using xulrunner -jsconsole. One solution is to put try .... except: print_exc() round any event handler to print tracebacks to stdout and use a python console to catch that output. The JSconsole can also be open and used from code, for example (in Javascript)
function openJavaScriptConsole() { var wwatch = Components.classes["@mozilla.org/embedcomp/window-watcher;1"] .getService(Components.interfaces.nsIWindowWatcher); wwatch.openWindow(null, "chrome://global/content/console.xul", "_blank", "chrome,dialog=no,all", null); } // dump to the js console (xulrunner -jsconsole) function jsdump(str) { Components.classes['@mozilla.org/consoleservice;1'] .getService(Components.interfaces.nsIConsoleService) .logStringMessage(str); } function jserror(str) { Components.utils.reportError(str); }
A final tip is to use task manager to check for a zombie xulrunner process after a crash. A zombie will keep old code open and cause confusion when you make changes and run xulrunner again.
Deploying
Python must be installed on the target machine. Perhaps eventually a XULRunner with a minimal Python installation can be generated with something like py2exe or pyInstaller. Untill then simply deploy the dist\bin folder and the XUL application. Don't copy any .pyo files that exist for python modules in the application or errors will occur on the target machine.
It is possible to test for python in a batch file using something like
rem Check Python 2.5 installed reg query "HKLM\SOFTWARE\Python\PythonCore\2.5" > nul 2>&1 || reg query "HKCU\SOFTWARE\Python\PythonCore\2.5" > nul 2>&1 if errorlevel 1 ( echo Python 2.5 was not found. Please install it. echo Exiting... pause exit /b 1 ) start "XULRunner with Python" "%moz_bin%\xulrunner.exe" -app application.ini %opts% exit /b 0
See XULRunner:Deploying_XULRunner_1.8 for general information.
Sample
A sample XULRunner application with these Python features is available. This includes the pyXPCOM tests and a basic Python console from Alex Badea
|
https://developer.mozilla.org/en-US/docs/Building_XULRunner_with_Python$revision/168291
|
CC-MAIN-2014-23
|
refinedweb
| 1,136
| 51.14
|
Jul 6, 2007
We're changing a lot of the systems that interoperate to provide the Library's web sites. This edition of IT Infrastructure News is a summary of those interrelated projects. Every one of these projects is complex and we can't describe every detail in a news message. So as always, let us know your questions or areas of deeper interest and we'll get back to you.
We operate a number of web servers but the majority of the content we think of as "the Library's
Web Site" is served from a machine called Cooper. Everyone who edits content on the site
knows this, and sees the published results of their changes on its web service alter ego. There's a similar
server to Cooper named Coach located in the Funk ACES Library building that continually copies
content from Cooper and exists solely as an emergency spare.
Unfortunately, those two machines are showing their age (we bought them in Feb 2002) and have become increasingly unreliable. They're also running old versions of the Linux operating system and other software components. Obviously the Library's web site is a critical system, and we're not happy when it fails or can't keep up with the times.
Because of this, we've recently had to make a decision to reprioritize their migration. We
have a pre-production version of Cooper running new versions of the Linux OS, PHP 5, Apache 2.2,
mod_perl 2.0 etc. The new server is completely virtual hardware in our VMware cluster, using
SAN storage (as described in
the inaugural 5/1/2007 issue of this
newsletter). As a result of this virtualization, we will be completely retiring the Coach
server.
The new server is currently being tested to discover and fix whatever compatibility issues result from the significant software upgrades. We expect this new server to be ready to start serving the content for in the next couple weeks. This migration will not affect web page addresses (URLs), nor the method you use to edit pages. Cooper also serves the encrypted web site content for. Because of the complexities of testing and moving that site, most of which is accessed via NetID logins through "Bluestem", we plan to migrate that content to the new server more gradually.
Last fall we
recommended the creation of a
CMS implementation group. Despite that, such a team was never created. In its
absence, the Systems Office and now the IT Infrastructure & Software Development unit has
continued to work on the customization and stabilization of the OpenCms system to prepare it for
our site. This is a complex project for a complex situation, but we've made significant
progress.
Since the base system has been in active development while we work, we have been running versions 6.2.3 and 7.0 release candidates 1 & 2. OpenCms Version 7.0 final was released this week, which is what we intend to use for the production system.
We still have a lot of work to do on the system, but we plan to have it ready for a limited number of editors to start using the production system before the fall semester begins. Further development and customization will continue as the system gets used for real live pages.
We'll get more details about the CMS system and project out soon.. In our case, the insertion of this additional
layer also can help reduce the impact of change on users while our content transitions to a CMS
environment. It will also allow us to bring some loose ends under the
namespace.
Examples of this name space improvement could be:
The front-end reverse proxy server will be deployed to full production use shortly after the Cooper migration occurs and we're sure it has worked.
|
http://www.library.illinois.edu/it/ims/news/Web_Platforms.html
|
CC-MAIN-2016-36
|
refinedweb
| 640
| 62.07
|
>>)."
I prefer Subjective-C (Score:5, Funny)
But that's just my opinion.
Agreed. (Score:5, Funny)
C's philosophy doesn't integrate well with Ayn Rand's.
Re:Agreed. (Score:4, Funny)
C's philosophy doesn't integrate well with Ayn Rand's.
Like hell it doesn't.
With C and Ayn Rand - you're on your own.
No pussy footing around with pee-pee holding concepts like "garbage collection", "array bounds checking", "welfare", "free health care".
Those are all for fucking wimps who need something to protect their incompetent asses.
Re:Agreed. (Score:5, Insightful)
So strange... I find Ayn Rand completely guilty of the very same romantic notions that got the founders of Communism (she so despised) into so much hot water. Perhaps its true what they say about choosing your enemies well. Both presumed that the underlying greatness and magnificence of the human spirit either as a society or as a specific productive individual would prove the guiding light for humanity. In fact humanity has shown precious few guiding lights and for the most part, we are little descended from our primate ancestors. This isn't to say that we aren't capable of transcendence, simply that you can't depend on that to build a social or philosophical framework.
Design the system that demands human transcendence, inspires greatness, and puts strict limits to personal power and responsibly accounts for the grosser of human foibles and frailties, and you'll have a winner. We had that system in the form of checks and balances, until the "Randian" among us began to systematically dismantle those very defenses against our poorer natures, beginning in the 80s. Up until then, we had the time and means to look at the future we wanted as a society, not just a few social (read financial) elites, and strive towards that future wisely and with due consideration. Now we're in a kettle of fish. Those elite have proven to be every bit as ignorant, self obsessed/serving and foolish as everyone else and they've squandered the future on extra McMansions, expensive cars and yachts, and the virtual hijacking of our society.
C is a great language. You can't any closer to bare metal without slugging assembly around, and as we move to more and more intelligent particles infiltrating everything from household appliances to ubiquitous sensors in the roads we drive on, you better believe that C will bring consciousness to the dross matter that surrounds us. I can only hope, that we can put aside our prejudices (not only racial, but societal), and begin to replace belief systems with educated inquiry, and treat the future with our intelligence rather than our primate predilections. It is the only hope I can see for a future worth living in.
Re:Agreed. (Score:5, Funny)
Re:Agreed. (Score:5, Insightful)
By all means, there's nothing wrong with primates... fine animals. They just tend to form hierarchies along lines off dominance, commit acts of violence on one another including infants, they're greedy, scheming, back-stabbing, self serving Machiavellian bastards (to paraphrase one of the world's leading authorities [wordpress.com] on primate research.
So we aren't as bad as baboons and we aren't as good as bonobos. We fall neatly on the primate continuum of behavior (good and bad.) The problem is that we have nukes. A pissing contest among humans could end in a 20 mile wide blue glass ashtray. All I'm saying is that as good as being a primate has gotten us so far, its perhaps time to begin rising above the worst of our inclinations while rising above them still makes a difference.
Re:Agreed. (Score:5, Funny)
'C' - The language of technocrats (Score:3)
What we need now is another tenuosly linked meme...In my copy of 1984 there is a reference to a fictional document that describes the different languages spoken by various groups. One of those languages is 'C' - the language of technocrats. So it follo
Re:Agreed. (Score:5, Funny)
But it's bottoms-up
Yes, Forth programming does tend to go a lot smoother when you drain a glass each time you have to look up the stack effect of a word.
Re: (Score:3)
Forth is a bit like darts. I paradoxically get better at darts the more I drink. Thus I'm very fond of darts, like I'm very fond of forth.
Somehow I feel that if I did forth for a day job, my liver would be destroyed.?
Because the same instruction leads to the same piece of code, every time. When you do "dup +", you can know what code it creates. It won't be different when done a different place. You can follow the program, step by step, and know what the CPU does.
Re:Agreed. (Score:5, Funny)
"all illegal immigrants should be sent back to whence they came. america for americans."
Wasn't that Sitting Bull motto?
Re:Agreed. (Score:5, Funny)
Re:OH I GOT MODDED DOWN??? (Score:5, Funny)
It's about mentioning this "god" fantasy thing
It's no fantasy.
God started out as a C coder, got bored and tried to rebuild the project in a self-built language similar to Brainfuck [wikipedia.org], now called DNA. The signs are everywhere - in fact GCC is still being used in places, notably to produce Alanine.
Of course, it's an old project, abandoned long ago. There's cruft, commented out code and dependencies everywhere, The APIs are wildly inconsistent, the whole thing is a virus and worm magnet. Even fork bombs are rarely trapped.
The documentation is archaic and unreadable, rewritten from the original by ancient geeks.Modern coders can only guess at what it means, and according to Nietzsche, the guy who wrote it left the company long ago.
About the only thing going for it is a very effective, if slightly weird, bootstrapping process.
sorry (Score:4, Funny)
sorry but html and javascript is the future.. it must be true because all the kids just out of college say so.
Re:sorry (Score:5, Insightful)
That'd be like saying letters are no longer required because we'll all be using words and sentences from now on.
Re:sorry (Score:5, Insightful)
That'd be like saying letters are no longer required because we'll all be using words and sentences from now on.
That's what the Chinese did!.
Re: (Score:3)
Most individual Chinese characters do have their own individual meaning(s).
It used to be (thousands of years ago) that characters were essentially words, but these days multiple-character-words are more in fashion. The classical Chinese is still legible to those with a bit of training, and still sees some use in modern contexts.
You are indeed correct that the characters are often constructed with other "basic characters" that contributes a meaning and sound, but that's at a "sub-character" level, not really
Re: (Score:3)
Korean uses a phonetic system now.
Re: (Score:3)
C Programming Language (Score:4, Insightful)
However the real story is that C, a raw machine independent assembler-like language, with no pretense to be object oriented or sophisticated, has beaten all three of the object oriented heavy weights
This sounds like it was written by someone who doesn't understand C. You can write object orientated code in C. You don't always need the language to hold your hand. And C is NOT assembler-like language. Not even close.
And as far as sophisticated code, I guess the author doesn't consider operating systems or most system programming to be sophisticated.
Re:C Programming Language (Score:5, Insightful)
Is this a touchy subject for you, AC?
The author didn't say anything about sophisticated code, they said that C isn't a particularly sophisticated language. And it's not. C doesn't have very many bells and whistles -- it's just a very good, general-purpose language. The fact that the language itself is unsophisticated is what makes it good for writing the kind of code people write in C.
Secondly, C is not an object oriented language. I can write object oriented code in assembly language if I want, but that doesn't make assembly language object oriented.
Re: (Score:2)
> You can write object orientated code in C.
You technically could...but why would you? If you want to write object oriented C, there's C++. What's the benefit?
Re:C Programming Language (Score:4, Interesting)
Subject: Re: [RFC] Convert builin-mailinfo.c to use The Better String Library.
Newsgroups: gmane.comp.version-control.git
Date: 2007-09-06 17:50:28 GMT (2 years, 14 weeks, 16 hours and 36 minutes ago)
- - -
Re:C Programming Language (Score:5, Interesting)
From: Linus Torvalds Subject: Re: [RFC] Convert builin-mailinfo.c to use The Better String Library. Newsgroups: gmane.comp.version-control.git Date: 2007-09-06 17:50:28 GMT (2 years, 14 weeks, 16 hours and 36 minutes ago)
....
And, for a view somewhat less harsh about C++, but still not a case of "C++ roolz, C droolz!", see The Old Man and the C [opensolaris.org], the abstract of which says
Re:C Programming Language (Score:5, Insightful)
And--I know I'm going to be stoned for this--Linus =/= God.
Re: (Score:3, Insightful)
- inefficient abstracted programming models where two years down the road you notice that some abstraction wasn't very efficient, but now all your code depends on all the nice object models around it, and you cannot fix it without rewriting your app.
This is no different in C...
The same problem is much worse in C. Because you will have grafted a crappy half-OO hack onto it that has accreted stupid numbers of macros, casts and other abuses. And it will be hell to change. Speaking from experience.
Re:C Programming Language (Score:5, Interesting)
For all his brilliance, Linus is stupid about some things. One of them is his near complete lack of understanding of C++. He obviously has zero skill in it, but he has plenty of skill at getting up on his pulpit and flaming people who do.
Re:C Programming Language (Score:4, Insightful)
And yet he's replying to someone that seems to want to use C++ for the sake of using C++...
Re:C Programming Language (Score:5, Insightful)
Linus is a pretty smart kernel programmer & architect who programs almost exclusively in C. It's no surprise that he doesn't even want to grok C++.
Re: (Score:3)
Re: (Score:3)
The first "real" OO language was Simula 67, and in fact it's a direct ancestor of C++ - if you look at Simula, you suddenly realize that the first version of C++ was more or less C with Simula OOP constructs grafted on top (this is where "virtual" came from, by the way).
Re: (Score:3)
You technically could...but why would you? If you want to write object oriented C, there's C++. What's the benefit?
C++ is a more expressive language than C. That's not necessarily better, though--I could define an extension to C where the + operator works between a string and an integer as follows:
mystr + myint is defined such that it returns a string of the same length as mystr, but where each element of the return value is myint less than the equivalent char in mystr. So "dddd" + 2 returns "bbbb", "zzzz
Re:C Programming Language (Score:4, Interesting)
Creating unusual object structures:
I once played around with a state machine framework that was object oriented c. It had a virtual table at the top of one base class and at the bottom of a different one. Using the same layout in the virtual table allowed multiple inheritance without any special effort and without any wasted space. It's the only object structure I've ever played with that I couldn't implement with C++ classes and inheritance (I guess a *really* good C++ compiler might be able to optimize to that structure)
Virtual Static members and member functions:
There are occasionally times when I need polymorphic behavior, but the behavior itself isn't instance specific. As a contrived example, imagine needing to query an instance of an object for the total number of peer objects that are in existence (I'm probably managing a count during construction/destruction). I need to call some member that is class specific, but that member will only need to use static members to execute. As it is this ends up being declared virtual and the this pointer is (needlessly) passed in.
Those are the only two instances I've run across where I actually wrote code up to the point of noticing that I couldn't do that in C++ (I'm actually still shocked ten years later that there's no such thing as a pure virtual static function).
Re:C Programming Language (Score:5, Interesting)
You will often see comments to the effect that C is like assembler or that you can do anything in C it just lacks some syntactic sugar. But that is very wrong. Yes, you can to some degree emulate object oriented programming in C. But how would you go about changing your memory allocation (malloc) to use a copying garbage collector? Or do lazy evaluation Haskell style? How do you implement zero-cost exception handling? (longjmp is NOT zero-cost because it requires setjmp).
These concepts are easy for a compiler that compiles directly to assembly language. Often less mature compilers will compile to C as an intermediate language, but in that case the compiler will not be able to generate the most efficient code. For example, a compiler that uses C as intermediate step can implement exceptions using setjmp/longjmp but this adds extra code at every function call. A compiler that goes directly to assembler can implement exception unrolling using static knowledge about the stack instead for a so called zero-cost exception handling solution.
Similarly, a compiler using C as intermediate will be forced to use a conservative garbage collector such as the Boehm GC. Using more efficient solutions such as a copying garbage collector is simply not possible without knowledge of the stack layout.
Re: (Score:3, Insightful)
You can write object orientated code in C.
The OP never said you couldn't, they said: "no pretense to be object oriented" (Emphasis mine.)
And as far as sophisticated code, I guess the author doesn't consider operating systems or most system programming to be sophisticated.
Again that's not what the OP said, they said C has: "no pretense to be
... sophisticated" They're saying C itself is not sophisticated, that has nothing to do with the code written in C. Sand is not a sophisticated medium, but I've seen sand sculptures that are definitely sophisticated.
However, you are 100% correct in challenging the "assembler-like" comment.
Re:C Programming Language (Score:5, Insightful)
Code is a way of expressing human thought (language) in a way that binary machines can interpret and perform. There has been a forever search for a language that best captures the grace and power of abstract human thinking elegantly.
One of those searches lead to Object Oriented Programming. An OO language breaks the organization of THINGS in a very natural way for western thinkers. The thought here is that by creating logical constructs representing an OBJECT which has both its own unique qualities and abilities, while at the same time inheriting qualities and capabilities from the family of OBJECT from whence it was derived, that you can perform wonderful things with a minimum of code and that if you were careful in designing your application that it should be easily adaptable and extensible to the vagaries of life. Of course this power doesn't come free, and there is operational code to support its behavior, so tiny problems or very small code may well demand C, while a large application is best implemented in a framework that gives you the logical freedom of an OO environment.
I see you nodding, is that you understanding or falling asleep... sorry if the monologue uses big words, they're part of the concepts. Anyway, languages have intrinsic power depending on their features and capabilities. Arguably, LISP is the most powerful language one can program in today. It is also one of the more syntactically challenging, and demands a fairly healthy understanding of what a machine is fundamentally capable of doing to use to its full potential. There is a spectacular free course available at MIT online, go here [oreillynet.com] to read more about it, and decide if its something you might be interested in. While you're at it, you might want to read up in functional languages (for the more action oriented among us) or just spend a while over at Wikipedia learning about computer languages and how we got here. Definitely read a book on algorithms. Understanding how we take every day problems and reduce them to logical constructs, and how very smart people have optimized the process of managing those problems is a very cool exercise... and it'll grow your brain a notch or two (help you look at problems newly.) Master abstraction and reduction, and you've got a bright future wherever you go.
Re: (Score:3)
Re:C Programming Language (Score:5, Insightful)
An OO language breaks the organization of THINGS in a very natural way for western thinkers.
Yes. And that right there is a subtle trap.
The first problem is that the "tree of subclasses" organisation, while on the surface seeming natural, is not in fact an accurate description of real taxonomies found either in nature or in large software projects. Especially so if the "software" includes business data. It turns out there are an awful lot of platypuses in the real world, things which simply don't fit neatly into the tree.
For example, a classic "toy" example often used in the OO analysis world is a database of employees. Lets see, we have managers, and we have workers. Great, we can subclass those! We'll have an abstract Person class, then personWorker and personManager who are subclasses of Person. Instantiate Jack Smith as an instance of class personWorker. Problem sol - um. Wait. Jack just got promoted from a worker to a manager. Crap. Can our OO system of choice handle dynamically changing an object's class during its lifetime? No, it enforces strict classing, so it can't. Oops. No problem, we'll delete Jack and recreate... oh. His entire work history was attached to that object, linked by opaque reference and not by name or staff ID, and now it's all gone forever. Double crap. Oh well. He's left the company anyway, and now he's come back as a private contractor. We'll just make him a new personContractor. Easy. Yeah, wait, now we're dealing with him also over in the billing system as a personSupplier. But wait, there's more, he just bought some stuff from us, so he's also a personCustomer! Now he's three classes at once! The universe has gone crazy!
Most real OO systems "solve" this problem by either not doing inheritance here at all - therefore completely invalidating the "OO is about inheritance" line - or duplicating the data in multiple objects - thereby invalidating the "OO is about modelling the business domain directly" line. But at this point we're really starting to lose most of the advantages of OO entirely.
But there's a second, even more subtle problem: although OO usually uses "class" as a synonym for "type", it turns out that subclasses are NOT at all the same thing mathematically as a subtype. (Because you can override the behaviour of a class, meaning its behaviour is now not a strict subset of its superclass, but can also be a superset.) In fact there's no really sensible definition of "subtype" at all - Liskov substitutability requires that you define a context within which you want to limit your idea of "equality", and over the scope and lifetime of a sufficiently large software system, that context is going to change radically. So there goes all your type safety. Add in runtime reflection (which was a fundamental principle of Smalltalk, the first OO system, but seems to be an optional add-on recently tossed haphazardly back into the modern variety) and things get even more confused.
And finally, even the idea of typing can become a third subtle trap. Even if you could (which you can't in the real world) restrict your software system to a neat tree of subclasses corresponding exactly to strict subtypes in a glorious Platonic universe - if you look at your code carefully, you find out that your class/type structure, no matter how strict and clever you make it, doesn't actually tell you anything about the behaviour of your objects. It only tells you the calling signature. That you've defined an addOne method in all your IncrementableByOne class structures doesn't mean that any of those subclasses actually have to implement int addOne(int X) as returning X plus one - just that they receive and emit an integer. So after all your compile-time declarations, you've gained a whole lot of not much at all, and you have to implement a whole testing harness apparatus to do by hand what your compiler initially promised it will do.
tl;dr: Just like (insert a political philosophy you dislike), OO is a big idea, a seductive idea, but not actually a correct idea. And attempting to apply thoughtlessly will cause pain.;
Re: (Score:3)
You don't need to get to functions pointers if you don't need polymorphism. It's like making (in C++) all methods virtual just for fun. You can have static OOP in C:
typedef struct FileClass;
int FileClass_open(FileClass* this, char* fileName);
int FileClass_close(FileClass* this);
int FileClass_read(FileClass* this, void* in, size_t size, size_t* actualSize);
int FileClass_write(FileClass* this, void* out, size_t size, size_t* actualSize);
typedef struct {
} FileCla
Re:I guess you don't understand languages either (Score:5, Insightful)
So, you think that is object-orientation? Oh boy.
From wikipedia [wikipedia.org]: "Object-oriented programming (OOP) is a programming paradigm using "objects" - data structures consisting of data fields and methods together with their interactions - to design applications and computer programs."
The GP's method certainly qualifies. Just because it doesn't include all the sugary syntax or features that are included in your favorite so-called "OOP language" doesn't mean that you can't do object-oriented programming in C.
Re: (Score:3)
Doesn't sound like you know what OOD is. That method qualifies, and you also get inheritance and polymorphism. Perhaps you shouldn't be so smug next time?
It's not being smug when it's about pointing the folly of reinventing the wheel, poorly, out of a square block and claim that it is a wheel. You guys are the MadTV Stuarts of software development (ma, look what I can do.... with structs and pointers to callback functions.)
One could say that programming in assembly using nothing but unconditional jumps and cond jumps is just the same as structured programming because, after all, structured programming will get translated to its assembly/machine language ju
Re: (Score:3)
I think that falls under "you don't always need the language to hold your hand."
Re:I guess you don't understand languages either (Score:5, Insightful)
Re: : (Score:3)
Enforecement of public private can be done: simply have your base object struct have a void pointer field called private and declare and allocate a private data struct as static in the
.c implementation of the class. Voila, private fields and methods as:I guess you don't understand languages either (Score:4, Insightful)
Oh, but it is. C is actually very, very close to assembly language, with only the most unimportant CPU-specific details abstracted away. The primitive types in C are almost always natively supported by the CPU in assembly language, with few exceptions. Instead of having to manage your own stack, it mostly manages it for you, but it still leaves plenty of room for shenanigans, particularly because it doesn't enforce the number of arguments any more than asm does. And if you use varargs, you pretty much are doing direct accesses to the stack using indexed addressing. Simple asm.
Accesses to a struct are just a tiny bit of syntactic sugar on top of an indexed load/store. Goto is a jmp, setjmp and longjmp just set a register and then perform a jump to that address The if/then commands have near exact ASM equivalents (albeit with a couple of extra jump instructions thrown in), and even while loops are just a couple of instructions (not counting whatever calculations must be performed to determine which path to take).
C abstracts away some stack management details, register quantity limits, etc., but it really is little more than portable assembly language, by design. It was intended for systems-level programming, and does that job well, in part because it is such a thin layer compared with most other languages.
Re:I guess you don't understand languages either (Score:5, Informative)
Considering that C++ was originally implemented as a preprocessor for C, there's an existence proof that says you are wrong.
Re:C Programming Language (Score:4, Funny)
In American English, one says and writes "oriented". In British English, the word "orientated" is used for the same purpose. Something I had to learn when I left the USA.
So the British book was "Murder on the Orientat Express"?
Java and C duking it out (Score:5, Interesting)
Java's apparent decline seems to be because of the financial slump. Where the number of new enterprise projects using Java has reduced. Most of this work was deferred and is starting to pick up again (at least as far as I can see). Some of the apparent 'decline' in languages is due to the introduction of new languages. The absolute number of projects using any language may be increasing but with new languages being introduced the proportion for any one language becomes diluted.
That said, C deserves to be right up there because it is still completely relevant as a 'lingua franca' (common language) for talking to hardware or operating systems. It also has the same benefits of Java in that the language is small and the convention is to place complexity in the libraries rather than as arbitrarily added keywords. This is not very exciting for many Slashdotters but for regular joes it allows them to get things done while working on huge, long-term projects (where the set of staff that start the project aren't necessarily those that finish it) where being able to follow other people's code is critical. This doesn't make for good press or excitement in the blogosphere or conference circuit but these two stalwarts pretty much let you solve any problem in any computing environment (portability matters!).
Re:Java and C duking it out (Score:4, Funny)
Java's apparent decline seems to be because of the financial slump. Where the number of new enterprise projects using Java has reduced. Most of this work was deferred and is starting to pick up again (at least as far as I can see)
I'm sure Oracle's mongolian horde of lawyers factors in there somewhere, too.
Re: (Score:3)
Maybe they didn't change away from it, since that would involve trashing already invested time and money, but there's certainly a non-zero number of developers who went another direction at the start of a new project because of it.
Re: (Score:3):Objective-C not required to create iOS Apps (Score:4, Insightful)
C in combination with some form of assembly still holds the absolute first position in terms of how much its actually deployed. Every mainstream OS its core, bootloader,
C++ holds its second spot without problem simply due to the fact that it's compatible with C and it does offer native object extensions.
The top 5 will probably be completed by Visual Basic, C# and Java for enterprise applications. They're perfectly fine languages for such goals and they do their job well.
After that it becomes tricky, most likely a couple of web languages like PHP and Perl in combination with a few of the old gems like Ada and FORTRAN. Ada is used in the aircraft industry on a regular basis and FORTRAN is the corner stone of weather prediction. Two rather interesting languages (not really programming languages though) would most likely also show up on there: VHDL and Verilog.
Anyway, I would just wish people would stop linking to the TIOBE index cause it actually has 0 value compared to real research into the subject. I'd rather see them do a study trying to correlate suicide statistics in the programming community with the programming language that was being used at the time, that might actually give more information about how good a language is than a couple of search engine hits.
Re:TIOBE is 'real research'. Just misunderstood. (Score:4, Insightful)
If you look at the description of how they compute the index, it's essentially useless for any practical purpose. So why even bother debating it?
Bravo that C is still relevant. (Score:5, Insightful)
Re: (Score:3)
yes, those 2 needs for performance are: cloud and mobile.
Both have energy issues, so efficient code means more battery life or less electricity bill. Nowadays, no-one cares about the old desktop area, so native code is coming back.
"machine independent assembler-like language"?!? (Score:3)
What? What idiot posted that garbage? Oh, timothy...
Understood.
There are several problems with that article (Score:2)
1) The one stated in the summary - the C++ vs. Objective C graph is on a very small Y axis that exaggerates the differences.
2) They've included Javascript, apparently in it's seldom-used server-side form, to intimate its popularity is going down (AFAICT they don't bother to mention this differentiation).
3) In their 2011 vs 2012 table, they indicate a language's change in table rank using arrows - one point in change equals one arrow. Visually that makes it look like some languages (e.g. Visual Basic
.NET) a
Re: (Score:3)
Shifting market or shifting paradigm (Score:3)
Ever tried looking for jobs using C? (Score:5, Interesting)
I don't get it. If you try searching for jobs programming in C, you'll find that almost everything that matches the search is Objective C, C++, or C# (or, on some poorly run job sites,a C++ or C# job where the punctuation got lost and it's displayed as C). Sometimes a job will say C/C++. C is rare as hen's teeth except for embedded development and there aren't *that* many jobs in embedded development.
I just went to monster.com and searched for C. What I found starting at the top was:
-- C++ job that lost the punctuation
-- Objective-C
-- C# job that lost the punctuation
-- C/C++
-- Objective-C
-- C/C++, C#
-- C/C++
-- Objective-C
etc. The first C job was item 14 (and is embedded). The next C job, ignoring the false hits on such things as A B C, was item 24 (also embedded), and C wasn't the main skill required. So how in the world can C be number one?:Ever tried looking for jobs using C? (Score:4, Interesting)?
TIOBE is good for generating bullshit headlines and boastful articles about misleading statistics.
The definition [tiobe.com] is pretty simple. They search for: +"<language> programming", then they try to look for false positives to get a "confidence" factor, and then use that to scale the resulting number of hits. They also include some search term qualifiers for certain languages, but I didn't see any listed for C.
This is really, really poor for a language with many false positives like C, because there are so many false positive results returned, but they are only looking at the first 100 results. The first results will have the fewest number of false positives, while the later results will almost all be false positives. What they are doing is assuming a linear relationship where instead it is most likely an exponential dropoff.
The fact that C is now on top is almost for sure due to the rise of false postives due to Objective-C gaining popularity.
C lives! (Score:2)
Wherefore art thou Dennis Ritchie?
We need a new language (Score:2)
And nothing of value was said (Score:3)
And that's not something to be settled by a popularity contest.
Survey is skewed by iOS developers (Score:3)
This survey is skewed by iOS developers trowelling out tons of appstore apps of questionable utility.
May Not Be a Fair Comparison (Score:3)
Therefore, the survey might include usage such as mine, which could tag every app I ever wrote as a 'C' app. FWIW
Re:fp (Score:4, Insightful)
Here's a crazy brief explanation:
The big draw to OO is that it (ostensibly) makes it easier and/or faster to write applications. This doesn't mean that you can make programs with an OO language that you couldn't with an imperative or structured language, only that certain tasks may be easier to implement.
That said, OO isn't always the best option. OO languages are typically a lot more complex and produce slower executables than plain C, so there is a trade-off that can be important in certain situations. As with anything, pick the best tool for the job.
For myself, when I first learned programming (via some books), I learned C before moving to C++. I absolutely hated C++ and didn't see the point of OO programming, due in large part because of the way the book presented it. At the start, the author had you write a C program, and throughout the course of the book, you would change it into a C++ program full of OO goodness. The final C++ program wound up having 50% more lines of code for the exact same functionality, and that was the point where I gave up on it. It was a pretty bad first impression.
So maybe you're reading from the wrong book?
Re:fp (Score:5, Interesting)
I'm guessing this was because the authors were exhibiting uselessly "object-oriented" toy programs to illustrate language features. You'd probably have had a different first impression if you'd started with Cocoa and Objective-C. While it hadn't been updated in years and consequently seems to have disappeared down the memory hole, one of Apple's old Cocoa tutorials was something to the effect of "Build a Text Editor in 15 Minutes", where they showed how you could build a TextEdit-like rich text editor with Cocoa in a couple pages of code.
In fact, it's pretty easy figure out how to do this starting from the Xcode "document-based application" template, as there's not much more to it than replacing the label control in the document window with a Text View and implementing a couple methods in the document class to get and set its contents.: (Score:3)
OO is *always* the best choice, depending on your definition of OO.
Believing this is a tremendously bad mistake to make. There are plenty of other high-level programming paradigms that for some tasks can be vastly superior to OO--e.g. straight functional programming in ML or Dylan, or logic programming in Prolog, or explicitly stack-based programming in Forth or Postscript. There is no "one size fits all" when it comes to programming.
Re:fp (Score:5, Insightful)
It's like the static vs dynamic linking debate that you sometimes hear. There's no real valid answer to that one either, it's a best guess on what'll lead to the best performance. With dynamic linking you don't need to load all the libraries at the start, on the other hand with static linking you don't need to call up the linker each time a library is loaded, and so on... My main advice: stay out of it. There's no real valid answer to these sort of things.
Re: (Score:3)
Re: (Score:3)");
Re:fp (Score:4, Funny)");
cancel.color("00f");
This is terrible pseudocode butyou get the idea. instead of having to code buttons from scratch, you sub class them and only add what you need. typing on a tablet so I hope I haven't been unclear.
OK:
typedef struct button {
long long color[3];
void (*onClick)(int);
} Button;
Button okay;
Button cancel;
okay.onClick =
cancel.onClick =
okay.color[2] = 0xffffffff;
cancel.color[2] = 0xffffffff;
The C version is probably smaller and faster than your version.
Re: (Score:3): (Score:3)
The C standard requires the compiler initialize all stack-allocated memory to zero.
Not only the standard does not require it, but virtually all real-world implementations don't do that, either.
In professional practice, I always memset everything I allocate to 0 for the entire block of memory I have allocated
That's a bad habit. There's no guarantee in the standard that setting all chars to 0 will correspond to a default value of a type, or even some valid, representation of pretty much any other type. For locals, you'd do better by writing an explicit initializer ={0} - this works with any type, and will implicitly initialize all remaining fields to their default values.
Re:fp (Score:5, Insightful)
What the fuck? Why the fuck would I subclass a button just to make it blue? That's just data, and damned trivial data at that. If your button object doesn't already have some mechanism for dealing with that data, it sucks and I'm using a different object, not yours.
Instead of having to code buttons from scratch, you sub class them...
No no no no NO. Goddamnit NO. Fucking Java. Motherfucking Javascript. They've ruined a generation of programmers.
Subclassing is the LAST thing you should be doing. The very last. First you should be using the customization features built in to the object, and using them directly on an instance of that object. Set the blue color on the Button class and be done with it. If that's not sufficient, use object composition. Most of the time, your object is NOT a Button. It's a something that needs to have a button. Only as a last possible resort do you subclass Button, and you'd damn well better be writing an object that still is-a Button. If you're not, you've done it WRONG.
Re:fp (Score:5, Insightful)
Except that if you read his code, he's not actually subclassing Button, he's instantiating it. He's certainly saying it wrong, though.
Re: (Score:3)
YES! Now, explain to me how you got past "C, a raw machine independent assembler-like language"?
Assembler-like? C? C used to be the hot new language that held your hand and did everything for you, unlike assembler. Now C is assembler-like?
Re:fp (Score:5, Insightful)
the idea of object oriented vs. non object oriented languages has always thrown me off.
Everyone else will attempt to explain OO using OO terms to a non-OO programmer. Thats like trying to teach my dog to sail a boat by speaking Japanese. I'll try a different tack. You know what a computed goto is, right (other than pure unadulterated evil, right?) What if your compiler enforced the hell out of good commenting and error bound checking to let you do computed goto's safely (er, more or less)? Well that is barely scratching the surface of OO. Syntactic sugar mounded on top of syntactic sugar. You know that quote about turtles all they way down, well fundamentally no matter the paradigm its Turing machines all they way down... more or less.
but really slashdot, what is the big draw to OO
When your professor was a little baby skript kiddie wannabe on his TRS-80 Coco-2 running OS/9 and BASIC09 and liking it, object orientation was the silver bullet among the crowd who could not bother to read "the mythical man month" by Brooks. So now you suffer thru OO because it was "cool" back when parachute pants were also cool, and leggings. Much as we're now raising a crop of wannabe skript kiddies who look up to the functional programming and agile methods people who have also never read "the mythical man month" by Brooks, so your kids / my grandkids are going to have to learn functional programming as The_One_True_Paradigm_And_all_disbelievers_should_be_burned_at_the_stake. And I'll still be writing device driver code on PIC microcontrollers in raw assembly, and it'll work great and I'll be liking it.
There's a really nice wiki article you probably need to read. The world is a lot bigger than "OO" "non-OO". [wikipedia.org]
Re: (Score:3)
OK, with you so far...
But you're still trying to teach your dog to sail using sailing terms!
Now if on the other hand your dog was Japanese...
Re:fp (Score:4, Funny)
OK, with you so far...
But you're still trying to teach your dog to sail using sailing terms!
Now if on the other hand your dog was Japanese...
Ah, but is he sailing on a starboard tack or a port tack? And should he tack or jibe the boat? And should he attach the sheets to the tack or the clew of the sail?
Re: (Score:3)
Object-oriented code is a way of collecting functions and the data types they operate on into collections. Instead of having hundreds of functions that all operate on a particular data type, you group them together into a class—a collection of functions—so that you, the programmer, can easily see the relationship between them.
That's the best-case, well-behaved upside of OO, yes. But it has an evil twin called "object-oriented analysis".
Object-oriented analysis is a way of taking your company's essential business data - the data you need to trade and survive, which has been around since before punched cards and which will be around when mind-mapped DNA moon crystals are obsolete - and then wrapping that data together with hard-coded functions hacked up in some quirky, platform-specific language invented five minutes ago and for w
Re: (Score:3)
We got the Web? That's your argument?
Object oriented programming is a nice organizational technique for larger programs and code reuse. It works well, if used properly, not least because it imposes a namespace system. Most OO systems also give you some neat automatic features like inheritance.
OO is not a silver bullet, not everything needs to be OO, and nobody, ever, should start learning programming with OO. If you make absolutely everything an object you're either an idiot or a Java programmer (no com
Re: (Score:2)
Java is only slow for programmers who don't understand what they're doing.
Or those who have to do anything complex and CPU-intensive.
Re: (Score:3)
BS!
I have written fast programs in both Java and C# that are maybe 10% slower than pedal to the metal C or C++.
Good for you: for i = 1 to 100 is pretty fast in any language.
Now try doing complex signal processing in Java.
Re: (Score:3)
I didn't know they retired the C preprocessor.
Re: (Score:3)
Re: (Score:3)
I think that if there's only 5 obj-c jobs in the Denver area, it probably means it's not a very useful skill.
What it means to me is that Denver is not quite the hotbed of development activity that you seem to believe it is.
You are aware that Denver metro is second in the number of tech jobs in the country, losing out only to silicon valley?
That's news to me. The last time I was looking to hire someone in Denver, I had about fifty applications for the gig. As for Denver being "second only to silicon va
|
http://developers.slashdot.org/story/12/07/08/2228220/objective-c-overtakes-c-but-c-is-number-one?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+Slashdot%2Fslashdot%2Fto+%28%28Title%29Slashdot+%28rdf%29%29
|
CC-MAIN-2013-20
|
refinedweb
| 7,481
| 61.87
|
This is my first entry into #iDevBlogADay. It all started very innocently with a suggestion from Miguel, but the ball got rolling pretty quickly. The idea is to have one independent iPhone game developer write a blog entry each day of the week. At first we thought we would be hard-pressed to get 7 developers, but it’s starting to seem we might have multiples per day!
Check out the new sidebar with all the #iDevBlogADay blogs. We’re also putting together a common RSS feed if you want to subscribe to that instead.
Writing is addictive, so don’t be surprised if this once-a-week minimum turns into multiple-times-a-week.
Every developer who’s been working on a team for a while is able to tell the author of a piece of code just by looking at it. Sometimes it’s even fun to do a forensic investigation and figure out not just the original author, but who else modified the source code afterwards.
What I find interesting is that I can do the same thing with my own code… as it changes over time. Every new language I learn, every book I read, every bit of code I see, every open-source project I browse, every pair-programming session, every conversation with a fellow developer leaves a mark behind. It slightly changes how I think of things, and realigns my values and priorities as a programmer. And those new values translate into different ways to write code, different architectures, and different coding styles.
It never happens overnight. I can’t recall a single case where I changed my values in a short period of time, causing dramatic changes to my coding style. Instead, it’s the accumulation of lots of little changes here and there that slowly shifts things around. It’s like the movement of the Earth’s magnetic pole: very slow, but changes radically over time (although maybe just a tad bit faster).
Why Talk About Coding Styles
Coding style in itself is purely a personal thing, and therefore, very uninteresting to talk about. However, in its current form, my coding style goes against the grain of most general modern “good practices”. A few weeks ago I released some sample source code and it caused a bit of a stir because it was so unconventional. That’s when I realized it might be worth talking about it after all (along with George bugging me about it), and especially the reasons why it is the way it is.
Before I even start, I want to stress that I’m not advocating this approach for everybody, and I’m certainly not saying it’s the perfect way to go. I know that in a couple of years from now, I’ll look back at the code I’m writing today and it will feel quaint and obsolete, just like the code I wrote during Power of Two Games looks today. All I’m saying is that this is the style that fits me best today.
Motivation
This is my current situation which shapes my thinking and coding style:
- All my code is written in C and C++ (except for a bit of ObjC and assembly).
- It’s all for real-time games on iPhone, PCs, or modern consoles, so performance and resource management are very important.
- I always try to write important code through Test-Driven Development.
- I’m the only programmer (and only designer).
- Build times in my codebase are very fast.
And above all, I love simplicity. I try to achieve simplicity by considering every bit of code and thinking whether it’s absolutely necessary. I get rid of anything that’s not essential, or that’s not benefitting the project by at least two or three times as much as it’s complicating it.
How I Write Today
So, what does my code look like these days? Something like this (this is taken from a prototype I wrote with Miguel of Mystery Coconut fame):
namespace DiverMode { enum Enum { Normal, Shocked, Inmune, }; } struct DiverState { DiverState() : mode(DiverMode::Normal) , pos(0,0) , dir(0) , o2(1) , boostTime(0) , timeLeftInShock(0) , timeLeftImmune(0) {} DiverMode::Enum mode; Vec2 pos; float dir; float o2; float boostTime; float timeLeftInShock; float timeLeftImmune; }; namespace DiverUtils { void Update(float dt, const Vec2& tiltInput, GameState& state); void Shock(DiverState& diver); void StartSprint(DiverState& diver); void StopSprint(DiverState& diver); }
The first thing that stands out is that I’m using a struct and putting related functions in a namespace. It may seem that’s just a convoluted way of writing a class with member functions, but there’s more to it than that.
By keeping the data in a struct instead of a class, I’m gaining several advantages:
- I’m showing all the data there is and how big it is. Nothing is hidden.
- I’m making it clear that it’s free of pointers and temporary variables.
- I’m allowing this data to be placed anywhere in memory.
The fact that the functions are part of a namespace is not really defensible; it’s pure personal preference. It would have been no different than if I had prefixed them with DriverUtils_ or anything else, I just think it looks clearner. I do prefer the functions to be separate and not member functions though. It makes it easier to organize functions that work on multiple bits of data at once. Otherwise you’re stuck deciding whether to make them members of one structure or another. It also makes it easier to break up data structures into separate structures later on and minimize the amount of changes to the code.
Probably one of the biggest influences on me starting down this path was the famous article by Scott Meyers How Non Member Functions Improve Encapsulation. I remember being shocked the first time I read it (after having read religiously Effective C++ and More Effective C++). That reasoning combined with all the other changes over the years, eventually led to my current approach.
Since everything is in a structure and everything is public, there’s very little built-in defenses against misuse and screw-ups. That’s fine because that’s not a priority for me. Right now I’m the only programmer, and if I work with someone else, I expect them to have a similar level of experience than me. Some codebases written with a defensive programming approach have an amazing amount of code (and therefore complexity) dedicated to babysitting programmers. No thanks. I do make extensive use of asserts and unit tests to allow me to quickly make large refactorings though.
Another thing to note that might not be immediately obvious from the example above is that all functions are very simple and shallow. They take a set of input parameters, and maybe an output parameter or just a return value. They simply transform the input data into the output data, without making extensive calls to other functions in turn. That’s one of the basic approaches of data-oriented design.
Because everything is laid out in memory in a very simple and clear way, it means that serialization is a piece of cake. I can fwrite and fread data and have instant, free serialization (you only need to do some extra work if you change formats and try to support older ones). Not only that, but it’s great for saving the game state in memory and restoring it later (which I’m using heavily in my current project). All it takes is this line of code:
oldGameState = currentGameState
This style is a dream come true for Test-Driven Development (TDD). No more worrying about mocks, and test injections, or anything like that. Give the function some input data, and see what the output is. Done! That simple.
One final aspect of this code that might be surprising to some is how concrete it is. This is not some generic game entity that hold some generic components, with connections defined in XML and bound together through templates. It’s a dumb, POD Diver structure. Diver as in the guy going swimming underwater. This prototype had fish as well, and there was a Fish structure, and a large array of sequential, homogeneous Fish data. The main loop wasn’t generic at all either: It was a sequence of UpdateDivers(), UpdateFish(), etc. Rendering was done in the same, explicit way, making it extra simple to minimize render calls and state changes. When you work with a system like this, you never, ever want to go back to a generic one where you have very little idea about the order in which things get updated or rendered.
Beyond The Sample
To be fair, this sample code is very, very simple. The update function for a reasonable game element is probably larger than a few lines of code and will need to do a significant amount of work (check path nodes, cast rays, respond to collisions, etc). In that case, if it makes sense, the data contained in the structure can be split up. Or maybe the first update function generates some different output data that gets fed into later functions. For example, we can update all the different game entities, and as an output, get a list of ray cast operations they want to perform, do them all in a later step, and then feed the results back to the entities either later this frame or next frame if we don’t mind the added latency.
There’s also the question of code reuse. It’s very easy to reuse some low level functions, but what happens when you want to apply the same operation to a Diver and to a Fish? Since they’re not using inheritance, you can’t use polymorphism. I’ll cover that in a later blog post, but the quick preview is that you extract any common data that both structs have and work on that data in a homogeneous way.
What do you think of this approach? In which ways do you think it falls short, and in which ways do you like it better than your current style?
Pingback: Games from Within | Managing Data Relationships()
Pingback: Games from Within | Remote Game Editing()
|
http://gamesfromwithin.com/the-always-evolving-coding-style
|
CC-MAIN-2017-47
|
refinedweb
| 1,717
| 59.84
|
want to create a datasource in the startup servlet? The application server should be able to create the named datasource once and you should be able to accss uit from any servlet/jsp/ejb etc. There is no reason to do it in a Servlet and then get this datasource via a reference to this start up servlet (tbh I am not even sure if you can get a reference to a servlet like you do with a normal java class).
Cheers
The purpose is to only do the JNDI lookup once instead of in several places. This is based on information I got out of a performance improvement article for servlets with reference to datasources. I found other articles similarly recommending the same thing but with no example code. My application is already working retrieving the JNDI datasource object in each servlet but I thought this tip sounding like it would be worth checking out. As I said above, the information was probably intended for someone beyond intermediate in skill because a lot was left to work out on your own, like calling the non-static class. I also made an assumption based on the example classes name (ControllerServlet) that it was a load-on-startup servlet. However, even if that assumption is incorrect it's still pretty clear that only one instance of that class would exist and in order to use it's methods one would have to retrieve the instance of the class rather than creating a new instance.
In any case I have found out that the other example I was trying to meld with this one was specifically for resin which explains why I'm getting the naming context error since WebSphere isn't set up to use a config container. Most of the singleton examples I've referred to which are able to return an instance of themselves also create their own instance to pass back to the calling method. The question I was asking was how one would have an already instantiated class return itself.
It may not be possible but since I can't contact the author of the original article I thought I'd test the waters here at E-E. Thanks for the feedback. I think I'll leave this up for awhile to see if anyone has other ideas. If I figure something out in the meantime I'll post it here for posterity and close the question.
Cheers
This can only be done if other objects register themselves with the class in question, so the class notifies them when it is loaded.
What I suggest is to write a standard java class that starts up when the application server starts up. In this class you do the jndi look up you need and obtain the datasource. Then have a static method that returns this instance to the callers something like
public class MyJNDIReturner
{
private static Datasource ds = null;
private static MyJNDIReturner myObject = null;
private MyJNDIReturner()
{
// Do the lookup and assign the datasource
}
public static MyJNDIReturner getInstance() {
if (myObject == null)
{
myObject = new MyJNDIReturner();
}
return myObject;
}
public Datasource getDatasource()
{
return ds;
}
}
and from your servlets you can do
MyJNDIReturner r = MyJNDIReturner.getInstance
Datasource ds = r.getDatasource();
Of course the doce might need some modifications and/or optimizations. It is only here to give you an idea of how you should go on. For more info you might want to sdo a google search for "Service locator pattern"
With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.
I mean
code :)
Sorry...I can post here every couple of days until I have a chance to test the solution. I haven't had a chance to test the solution and before I award 350 points it seems I should have the opportunity to do so.
How fequently do I need to update this question to prevent it being closed? This is not an abandoned issue...it's a reprioritized project and unfortunately I simply haven't had a chance to work on this project let alone try the proposed solution. I want to award the points fairly and if the solution hasn't been tested I don't feel it's fair to arbitrarily assign just because someone has offered an unproven solution. Since you aren't losing anything by leaving the question open, providing I keep updating it, I don't see how this is a problem.
I will update as frequently as necessary to keep the question from being closed, just let me know how frequently that needs to be. I don't think I've ever abandoned a question here other than ones that never received any expert's response and I've been a member for awhile. Check my history.
Also, since the only person to have proposed any solution is yourself there would appear to be a bit of a conflict of interest if you decided to close the question and award the points to yourself. :o)
Thank you.
Sorry again. I've been so busy on other development projects I still haven't revisited this specific issue but I have had some more experience with singleton classes and based on what I've learned I understand your suggestion better and I'm confident it will work.
Thanks again for being so patient.
Paul
|
https://www.experts-exchange.com/questions/21923787/Return-instance-of-load-on-startup-servlet.html
|
CC-MAIN-2018-09
|
refinedweb
| 914
| 67.18
|
I am very new at programming in general, but I tend to pick up things by following examples...
Anyways, I have been in charge of tweaking a bot written in python and I feel that it is time to convert it over to C++ if the thing is to keep up with the demands it is needed for.
I searched google.com and I found a couple things to turn python into C++.
Right now I am working on converting a sample python program to a C++ sample program and when I goto compile it, I get errors...
Here is the Original Sample Code
And after some trial and error, this is where I am at:
// this is a test
#include <iostream.h>
int x = -1;
while (x) // loop until 0 spam
{
cout << "\nHow much spam?"; cin >> x ;
if (x)
{
cout << "We have:" << endl;
for (i=0; i<x; i++)
{
cout << "spam" << " ";
if (i == x-2) // (don't forget the beans!)
{
cout << "baked beans and" << " ";
}
}
}
else
{
cout << "Enjoy!" << endl;
}
}
// all done!
Now I am getting the error 'Declaration terminated incorrectly' in this line:
while (x) // loop until 0 spam
and everything I have seen using goole.com tells me it is correct.
Can somebody shed some light on the subject for me please?
|
http://forums.devshed.com/programming-42/loop-error-66333.html
|
CC-MAIN-2014-41
|
refinedweb
| 213
| 80.82
|
Introduction to Python pathlib
One of the first things many beginner Python tutorials teach is how to read or write files using patterns like
with open('file.txt') as f: f.read()
And then walk directories with libraries such as
os:
import os g = os.walk('.') next(g)
Which will go recursively through results depth first, leaving to you, the programmer, the joy of writing your own algorithm for searching files or listing files of a certain type.
Other calls such as
os.rename or to
os.path.join have the developer
manipulate paths manually with string concatenation and
os.sep.
Not much fun.
Neither of these approaches is wrong. But they’re cumbersome and code can get thorny quickly.
Today we’re going to take a look at
pathlib which was introduced in Python 3.4
and simplifies our work with files tremendously.
We’ll showcase pathlib’s most popular features.
Let’s start with the basics: Reading and writing text files.
We’re going to use
read_text and
write_text on our Path instance.
Let’s throw in some yaml for the fun of it.
from pathlib import Path import yaml path = Path('tmp/file.yaml') contents = path.read_text() yaml_content = yaml.load(contents) # yaml_content # {'name': 'Radu', 'lastname': 'P', 'uses': 'linux', 'twitter': 'wooptoo'} yaml_content['name'] = 'Rad' path.write_text(yaml.dump(yaml_content))
What if we want to rename our file? We’ll reuse the
path from the previous example.
path = Path('tmp/file.yaml') new_path = path.with_name('myfile.yaml') # PosixPath('tmp/myfile.yaml') path.rename(new_path) path.exists() # False new_path.exists() # True
Our file was renamed in a few easy steps, in a nice object oriented fashion.
path.with_suffix('.txt') is very similar, and will just change our file’s extension
and keep the initial file name.
PosixPath represents our path instance, which enables us to do all sorts
of operations, like creating a new directory, checking for existence,
checking for file type, getting size, checking for user, group, permissions, etc.
Basically everything we would previously do with the
os.path module.
Let’s fetch all our yaml files now with
glob:
from pathlib import Path tmp = Path('tmp') g = tmp.glob('*.yaml') list(g) # [PosixPath('tmp/myfile4.yaml'), # PosixPath('tmp/myfile3.yaml'), # PosixPath('tmp/myfile2.yaml'), # PosixPath('tmp/myfile.yaml')]
And we can take it from there.
glob and
rglob are super handy for this kind of stuff.
Of course Python had the
glob module before, but having it under pathlib’s umbrella is extremely handy.
Next we can iterate through sub-directories using rglob with patterns like
./
Or we can just use
iterdir which is nicer.
tmp = Path('tmp') dgen = tmp.iterdir() list(dgen) # [PosixPath('tmp/snappysnaps'), # PosixPath('tmp/cameraphotos'), # PosixPath('tmp/yamlfiles')]
And one last thing which I’m going to touch upon is traversing folders, and even creating new paths.
tmp = Path('tmp') new_path = tmp / 'pictures' / 'camera' # PosixPath('tmp/pictures/camera') new_path.mkdir(parents=True) new_path.exists() # True
This wizardry is done by overloading the
/ operator of the Path instance.
In Python 3 this is the private
__truediv__ method.
p = Path('tmp') p / 'myfile.txt' == p.__truediv__('myfile.txt') # True
In a nutshell these are the most common cases
which you’ll use on a daily basis if you work with files a lot.
We’ve managed to replace three different libraries (os, glob and open/read) with
pathlib which gives us a neat developer interface.
Since pathlib is now part of the Python standard library there’s absolutely no reason to not use it for new projects. More on the library can be read in the manual page.
|
http://wooptoo.com/blog/python-pathlib/
|
CC-MAIN-2018-47
|
refinedweb
| 602
| 60.01
|
transparently proxies functions, objects
Unobtrusive transparent proxies with very little setup. Doesn't require re-writing existing code. You can just drop it right in!
Runs anywhere there's javascript (browser & node).
--> (layer) --> (function/object)
// add a simple proxy without modifying any existing code!varx = x * 100;y = y * 100;nextx y;var that = this;layersetthat add addBig;// existing code...return x + y;add2 2; // 400
And that's it, all instances of calling
add() in your existing code now go through
addBig() then
add()
You don't re-write your code! Or have to call
addBig() directly.
(Note: this won't work in node.js because
add is private, see here.)
For some fun stuff you can do with layer, check out intercept.js.
layer.set(context, function to proxy, proxy function)
Context being scope or this, read more about it here.
In the browser when you set 'null' as the context, it'll default to global (browser only).
layer.unset(func) or following the example:
layer.unset(add)
For those times when you want turn skip a layer...
func.skip() or following out add example
add.skip(2, 2)
layer.replace(context, function to replace, new function)
At anytime you may stop early by not calling
And either call your callback (async) or return (sync);
node:
npm install layer
browser:
use
layer.min.js
(You can't proxy private variables!)
Because they're private. Not a big deal, and it's obvious enough. But keep in mind that in a node.js, the root of the module all your var's are effectively private (so the readme example above will not work).
Work around would be
exports.add and the context being 'exports' would work.
Or if add was in an object
var obj = { add: ... }, context being 'obj'.
(Basically, it works like normal except for private variables.)
Some more examples:
var somelib = require'somelib';layersetsomelib somelibfunc proxyFn
{}layersetCatprototype Catprototypemeow proxyFn
|
https://www.npmjs.com/package/layer
|
CC-MAIN-2015-32
|
refinedweb
| 322
| 61.53
|
Build admin-style views with minimal code
Project description
Build admin-style views with minimal code.
- Project site:
- Source code:
- Requires Python 3.7 or later and Django 2.2 or later
Overview
Django admin is great for creating quick CRUD views for admin users, but is not suitable for end users.
Fastview is inspired by Django admin - write code to manage objects in a few lines, using groups of standard generic views which can be supplemented, overridden or replaced as necessary, and styled and tied into the rest of your site.
Fastview adds a layer of access control to make it straightforward to manage who can access each view, and provides default templates to get you up and running quickly.
It supports inline formsets, with an optional customisable JavaScript library to manage the UI.
Note: this is an alpha release; expect feature and API changes in future versions. Check upgrade notes for instructions when upgrading.
Quickstart
Install using pip:
pip install django-fastview
Add to INSTALLED_APPS:
INSTALLED_APPS = [ ... "fastview", ]
Use view groups to build a set of CRUD views in one go, or use the views independently:
# views.py class BlogViewGroup(ModelViewGroup): model = Blog publish = MyPublishView # Django view class permissions = { "index": Public(), "detail": Public(), "create": Login(), # Allow any logged in user to create a post "update": Staff() | Owner("owner"), # Allow staff or post owners to edit "delete": Django("delete"), # Only users with the delete permission "publish": Staff() & ~Owner("owner"), # Staff can publish but not their own } # urls.py urlpatterns = [ # ... url(r'^blog/', BlogViewGroup().include(namespace="blog")), ]
For more details see the main documentation.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
|
https://pypi.org/project/django-fastview/
|
CC-MAIN-2021-04
|
refinedweb
| 292
| 61.36
|
How Reddit ranking algorithms work
This is a follow up post to How Hacker News ranking algorithm works. This time around I will examine how Reddit’s story and comment rankings!).
The default story algorithm called the hot ranking is implemented like this:
# Rewritten code from /r2/r2/lib/db/_sorts.pyx
from datetime import datetime, timedelta
from math import log
epoch = datetime(1970, 1, 1)
def epoch_seconds(date):
td = date - epoch
return td.days * 86400 + td.seconds + (float(td.microseconds) / 1000000)
def score(ups, downs):
return ups - downs
def hot(ups, downs, date):
s = score(ups, downs)
order = log(max(abs(s), 1), 10)
sign = 1 if s > 0 else -1 if s < 0 else 0
seconds = epoch_seconds(date) - 1134028003
return round(sign * order + seconds / 45000, 7)
In mathematical notation the hot algorithm looks like this:
Effects of submission time
Here is a visualization of the score for a story that has same amount of up and downvotes, but different submission time:
The logarithm scale
Reddit’s hot ranking uses the logarithm function to weight the first votes higher than the rest. Generally this applies:
- The first 10 upvotes have the same weight as the next 100 upvotes which have the same weight as the next 1000 etc…
Here is a visualization:
Without using the logarithm scale the score would look like this:
Effects of downvotes
Reddit is one of the few sites that has downvotes. As you can read in the code a story’s “score” is defined to be: :)
Conclusion of Reddit’s story ranking
- Submission time is a very important parameter, generally newer stories will rank higher than older
- The first 10 upvotes count as high as the next 100. E.g. a story that has 10 upvotes and a story that has 50 upvotes will have a similar ranking
- Controversial stories that get similar amounts of upvotes and downvotes will get a low ranking compared to stories that mainly get upvotes
How Reddit’s comment ranking works
Randall Munroe of xkcd is the idea guy behind Reddit’s best ranking. He has written a great blog post about it:!
Digging into the comment ranking code
The confidence sort algorithm is implemented in _sorts.pyx, I have rewritten their Pyrex implementation into pure Python (do also note that I have removed their caching optimization):!
Application outside of ranking
Like Evan Miller notes Wilson’s score interval has applications outside of ranking. He lists 3 examples:
- Detect spam/abuse: What percentage of people who see this item will mark it as spam?
- Create a “best of” list: What percentage of people who see this item will mark it as “best of”?
- Create a “Most emailed” list: What percentage of people who see this page will click “Email”?).
Conclusion
I hope you have found this useful and leave comments if you have any questions or remarks.
Happy hacking as always!
|
https://medium.com/hacking-and-gonzo/how-reddit-ranking-algorithms-work-ef111e33d0d9?TIL
|
CC-MAIN-2016-30
|
refinedweb
| 482
| 54.36
|
Class CVwEnvironment is the environment used by VW.
Contains global constants and settings which change the behaviour of Vowpal Wabbit.
It is used while parsing input, and also while learning.
One CVwEnvironment object should be bound to the CStreamingVwFile or CStreamingVwCacheFile, and the pointer to it propagated upwards to CStreamingVwFeatures and finally to CVowpalWabbit.
Definition at line 39 of file VwEnvironment.h.
Default constructor Should initialize with reasonable default values
Definition at line 19 of file VwEnvironment.cpp.
Destructor
Definition at line 51 of file VwEnvironment.
Return the mask used
Definition at line 75 of file VwEnvironment.h.
Return maximum label encountered
Definition at line 87 of file VwEnvironment.h.
Return minimum label encountered
Definition at line 81 of file VwEnvironment 114 of file VwEnvironment.h.
Return number of bits used for weight vector
Definition at line 63 of file VwEnvironment.h.
If the SGSerializable is a class template then TRUE will be returned and GENERIC is set to the type of the generic.
Definition at line 268 of file SGObject.cpp.
Return length of weight vector
Definition at line 99 of file VwEnvironment.
Return number of threads used for learning
Definition at line 93 of file VwEnvironment mask used while accessing features
Definition at line 69 of file VwEnvironment.h.
Set number of bits used for the weight vector
Definition at line 57 of file VwEnvironment.h.
Set a new stride value. Also changes thread_mask.
Definition at line 69 of file VwEnvironment.
Whether adaptive learning is used.
Definition at line 145 of file VwEnvironment.h.
Learning rate.
Definition at line 140 of file VwEnvironment.h.
Decay rate of eta per pass.
Definition at line 142 of file VwEnvironment.h.
Whether exact norm is used for adaptive learning.
Definition at line 147 of file VwEnvironment.h.
Example number.
Definition at line 167 of file VwEnvironment.h.
Which namespaces to ignore.
Definition at line 191 of file VwEnvironment.h.
Whether some namespaces are ignored.
Definition at line 189 of file VwEnvironment.h.
Initial value of t.
Definition at line 162 of file VwEnvironment.h.
Initial value of all elements in weight vector.
Definition at line 154 of file VwEnvironment.h.
io
Definition at line 514 of file SGObject.h.
Level of L1 regularization.
Definition at line 149 of file VwEnvironment.
Mask used for hashing.
Definition at line 128 of file VwEnvironment.h.
Largest label seen.
Definition at line 137 of file VwEnvironment.h.
Smallest label seen.
Definition at line 135 of file VwEnvironment.h.
ngrams to generate
Definition at line 184 of file VwEnvironment.h.
log_2 of the number of features
Definition at line 124 of file VwEnvironment.h.
Number of passes.
Definition at line 181 of file VwEnvironment.h.
Pairs of features to cross for quadratic updates.
Definition at line 194 of file VwEnvironment.h.
parallel
Definition at line 517 of file SGObject.h.
Number of passes complete.
Definition at line 179 of file VwEnvironment.h.
t power value while updating
Definition at line 164 of file VwEnvironment.h.
Whether to use random weights.
Definition at line 152 of file VwEnvironment.h.
Skips in ngrams.
Definition at line 186 of file VwEnvironment.h.
Number of elements in weight vector per feature.
Definition at line 132 of file VwEnvironment.h.
Sum of losses.
Definition at line 177 of file VwEnvironment.h.
Value of t.
Definition at line 160 of file VwEnvironment.h.
log_2 of the number of threads
Definition at line 126 of file VwEnvironment.h.
Mask used by regressor for learning.
Definition at line 130 of file VwEnvironment.h.
Total number of features.
Definition at line 175 of file VwEnvironment.h.
Sum of updates.
Definition at line 157 of file VwEnvironment.h.
Length of version string.
Definition at line 199 of file VwEnvironment.h.
version
Definition at line 520 of file SGObject.h.
VW version.
Definition at line 197 of file VwEnvironment.h.
Weighted examples.
Definition at line 169 of file VwEnvironment.h.
Weighted labels.
Definition at line 173 of file VwEnvironment.h.
Weighted unlabelled examples.
Definition at line 171 of file VwEnvironment.h.
|
http://www.shogun-toolbox.org/doc/en/3.0.0/classshogun_1_1CVwEnvironment.html
|
CC-MAIN-2014-52
|
refinedweb
| 674
| 54.9
|
MPI_Group_range_excl - Produces a group by excluding ranges of processes from an existing group
#include <mpi.h> int MPI_Group_range_excl(MPI_Group g, int n, int ranges[][3], MPI_Group *png)
group - group (handle) n - number of elements in array ranges (integer) ranges - a one-dimensional array of integer triplets of the form (first rank, last rank, stride), indicating the ranks in g of processes to be excluded from the output group png .
png - new group derived from above, preserving the order in group (handle)
Each of the ranks to exclude must be a valid rank in the group and all elements must be distinct or the function is erroneous. When a group is no longer being used, it should be freed with MPI_Group_free ._ARG - Invalid argument. Some argument is invalid and is not identified by a specific error class. This is typically a NULL pointer or other such error.
MPI_Group_free.
grexcl.c
|
http://huge-man-linux.net/man3/MPI_Group_range_excl.html
|
CC-MAIN-2017-13
|
refinedweb
| 149
| 59.03
|
Circular buffer in assembly of TMS320C6713
I have a filter (FIR) with 40 coefficients which take up 80 bytes total (2 bytes each). I am trying to implement a circular buffer for this filter but the size of the buffer must be a power of 2. The closest power of 2 I can use is 128 so that all the coefficients are included. After accessing the 40 coefficients though the pointer will go out of bounds. What can I do to solve this? Thanks in advance!
See also questions close to this topic
- Trouble with getting pointer to function
I am trying to get pointer to function with use C code like:
void (*ptrFunc)(void) = &any_func;
and I expect get assembler code like:
lea eax, dword ptr ds:any_func mov dword ptr ds:ptrFunc, eax
but gcc produce:
mov eax, dword ptr ds:any_func mov dword ptr ds:ptrFunc, eax
How can I fix it?
- mmap not work in assembler
i was write 2 same code in asm and c++.
ASM
PROT_READ equ 1 ; Page can be read. */ PROT_WRITE equ 2 ; Page can be written. */ PROT_EXEC equ 4 ; Page can be executed. */ PROT_NONE equ 0 ; Page can not be accessed. */ MAP_SHARED equ 1 MAP_PRIVATE equ 2 MAP_FIXED equ 10h MAP_TYPE equ 0Fh MAP_FILE equ 0 MAP_ANON equ 20h MAP_ANONYMOUS equ MAP_ANON MAP_32BIT equ 40h MAP_NORESERVE equ 4000h MAP_GROWSDOWN equ 0100h MAP_DENYWRITE equ 0800h MAP_EXECUTABLE equ 1000h MAP_LOCKED equ 2000h MAP_POPULATE equ 8000h MAP_NONBLOCK equ 10000h MAP_STACK equ 20000h MAP_HUGETLB equ 40000h .code _start: main proc mov rdi, 0 mov rsi, 4095 mov rdx, PROT_WRITE or PROT_READ mov rcx, MAP_ANONYMOUS or MAP_PRIVATE or MAP_GROWSDOWN mov r8, -1 mov r9, 0 mov rax, 9 ; mmap syscall main endp end
C++
#include <sys/types.h> #include <sys/stat.h> #include <sys/mman.h> #include <fcntl.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> int main() { int *map = mmap(0, 4096, PROT_WRITE | PROT_READ, MAP_ANONYMOUS | MAP_PRIVATE | MAP_GROWSDOWN, -1, 0); printf ("%x\n", map); return 0; }
its same. but works inly in c++, asm return 0xfffffffffffffff7 error. please tell why not work in asm?
This will be displayed in a monospaced font. The first four spaces will be stripped off, but all other whitespace will be preserved.
Markdown and HTML are turned off in code blocks: <i>This is not italic</i>, and [this is not a link]()
- Data structure for representing C code using Java
I'm developing a
decompilerin
Javafor a certain assembly language which builds a
Crepresentation of the machine code.
I'm wondering how I should store the
Ccode during processing. Using
StringBuilderand appending to it when something has been translated sounds straightforward but not ideal since it is not flexible for language-based changes later on (such as inlining). Can I use some
AST-like data structure with pretty printing and traversing functionality? Can
antlrhelp in this regard? I really don't want to just build and modify strings but I also didn't find a reasonable
AST-way of doing this without "reinventing the wheel". Any ideas or hints?
- How to filter a table that has been loaded with JSON data using Javascript
I'm trying to filter information from a table that has been loaded with JSON data. What I'm trying to do is to put the inputs and then filter the table when I press the button. Here is the important part of my html file:
<form role="search" class="search-form" style="flex-grow:1"> <div class="form-group"> <label for="dpt">Partida:</label> <input type="text" class="form-control" id="dpt"> </div> <div class="form-group"> <label for="dtn">Destino:</label> <input type="text" class="form-control" id="dtn"> </div> <div class="row-md"> <button class="Search" onclick=searchDepartures()>Procurar</button> </div> </form> </div> <div class="container" style="width: 50%; overflow: hidden; float: right;"> <table class="table table-bordered table-striped table-hover" id="routes_table" style="width: 100%;"> <thread> <tr> <th>Partidas</th> <th>Destinos</th> </tr> </thread> <tbody> </tbody> </table> </div>
And my Javascript file:
$(document).ready(function () { $.getJSON("locations.json", function (data) { var routes_data = []; $.each(data, function (key, value) { routes_data += '<tr>'; routes_data += '<td>' + value.departure + '</td>'; routes_data += '<td>' + value.arrival + '</td>'; routes_data += '</tr>'; }) $(routes_table).append(routes_data); }); $.getJSON("locationsEN.json", function (data) { var routes_data = []; $.each(data, function (key, value) { routes_data += '<tr>'; routes_data += '<td>' + value.departure + '</td>'; routes_data += '<td>' + value.arrival + '</td>'; routes_data += '</tr>'; }) }); function searchDepartures() { var results = []; var searchField = value.departure; var searchVal = "#dpt"; for (var i=0 ; i < routes_data.length ; i++) { if (routes_data[i][searchField] == searchVal) { results.push(routes_data[i]); $(routes_table).append(routes_data); } } }
Also my JSON file:
[ { "id": "1", "departure": "Beja", "arrival": "Lisboa" }, { "id": "2", "departure": "Lisboa", "arrival": "Beja" }, { "id": "3", "departure": "Beja", "arrival": "Évora" }, { "id": "4", "departure": "Évora", "arrival": "Beja" }, { "id": "5", "departure": "Beja", "arrival": "Faro" }, { "id": "6", "departure": "Faro", "arrival": "Beja" }, { "id": "7", "departure": "Beja", "arrival": "Setúbal" }, { "id": "8", "departure": "Setúbal", "arrival": "Beja" } ]
So far nothing as worked except putting the whole table in, which is expected when the inputs are empty.
- Filter array by content?
I'm trying to filter an array that is non-object based, and I need the filter to simply check each piece of the array for a specific string.
Say I have this array:
["", "", ""]
What I need to do is harvest the array in a way so that I get a new array that only contain those who start with not
In conclusion making this:
["", "", ""]
into this
["", ""]
- WordPress comment_form() $fields arg not taking affect
I am trying to add a comment form using the
comment_form()function. When I don't pass in any arguments, the only field that shows up is the comment textarea field. I need to add in the author and email fields. I am trying to do this using the
fieldsarguments.
$args = array( 'fields' => array( 'author' => '<p class="comment-form-author"><label for="author">Name</label><input id="author" name="author" type="text" value="" size="30" /></p>' ), 'title_reply' => null, 'logged_in_as' => null, 'submit_button' => '<input name="%1$s" type="submit" id="%2$s" class="%3$s btn btn-primary" value="%4$s" />' ); comment_form($args);
I am still just getting the comment textarea. I have checked the markup with Inspect Element and nothing is being added. The three additional arguments,
title_reply, logged_in_as, submit_buttonall work fine.
Additionally, I have also tried using
apply_filterswhich also did not work.
'fields' => apply_filters( 'comment_form_default_fields', array( 'author' => '<p class="comment-form-author"><label for="author">Name</label><input id="author" name="author" type="text" value="" size="30" /></p>' )),
- Spectrum computed with Matlab FFT does not give a consistent result for different lengths of sample (same number of points but Fs different)?
I would like to plot profile of rugosity (from AFM measurements) but there are still this that I misunderstand regarding the FFT (especially in Matlab documentation).
I want to compare two measurements, a.k.a. two rugosity profiles. They were done on the same surface, they only diverge on the fact that one is made on a shorter length than the other one. For each profile though, I have the same number of sample measures (N=512 here). Let's say these are my profiles,
t10and
t100being the x-abscisse along which the measure is made, and
d10and
d100being the vertical coordinate, a.k. the height of the measurement in the rugosity profile.
N=512; t10 = linspace(0,10, N); t100= linspace(0,100, N); d10 = sin(2*pi*0.23 .*t10)+cos(2*pi*12 .*t10); d100 = sin(2*pi*0.23 .*t100)+cos(2*pi*12 .*t100);
As it is the same surface that I measure but with different spatial resolution, i.e. different sampling period, the single-sided Amplitude spectrum of these rugosity profiles should overlap, shouldn't they?
Unlike what I should obtain, I have the following graphs:
and
Using the following function:
function [f,P1,S1] = FFT_PowerSpectrumDensity(time,signal,flagfig) H=signal; X=time; ell=length(X); L = ell;% 2^(nextpow2(ell)-1) % Next power of 2 from length of the signal deltaTime = mean(diff(X)); Fs=1/deltaTime; %% mean sampling frequency %% Compute the Fourier transform of the signal. Y = fft(H); %% Compute the two-sided spectrum P2. Then compute the single-sided spectrum P1 based on P2 and the even-valued signal length L. P2 = abs(Y/L); % abs(fft(signal Y)) / Length_of_signal P1 = P2(1:L/2+1); P1(2:end-1) = 2*P1(2:end-1); f = Fs*(0:(L/2))/L; if flagfig~=0 figure(flagfig) loglog(f,P1) title('Single-Sided Amplitude Spectrum of X(t)','FontSize',18) xlabel('Spatial frequency f=1/\lambda (m^{-1})','FontSize',14) ylabel('|P1(f)| (m)','FontSize',14) end S = (Y.*conj(Y)).*(2/L).^2; % power spectral density S1 = S(1:L/2+1); S1(2:end-1) = S1(2:end-1); %% Power spectrum (amplitude = a^2+b^2), in length^2 if flagfig~=0 figure(flagfig+1) loglog(f,S1) title('Power spectrum','FontSize',18) xlabel('Spatial frequency f=1/\lambda (m^{-1})','FontSize',14) ylabel('(Y*2/L)^2 (m^2)','FontSize',14) end end
I call this function for instance using the following command:
[f10, S10]= FFT_PowerSpectrumDensity(t10, d10, 10);
Should I use
L=2^pow2(ell)-1)? I understood that it provides a better input to the FFT function? Also, I am quite unsure about most of the units and values I should find.
Thank you for your help, corrections and suggestions.
- How does a RADAR detect multiple targets?
I get detections in the form of a point(range index,doppler index) .If I have multiple targets ,i will get multiple points for those many targets.So how can the RADAR distinguish which point corresponds to which target?
- Matlab df2sos equivalent library in python
Is there any library in python equivalent to matlab
dfilt.df2sos. I have been looking for a library to calculate band powers of a signal but can't find any.
|
http://quabr.com/47253391/circular-buffer-in-assembly-of-tms320c6713
|
CC-MAIN-2018-30
|
refinedweb
| 1,647
| 54.42
|
Introduction on Java Booleans
In day to today life, we often make decisions about each of our activities, situations, visions, results, happenings, etc. The value of our decision is either of the twofold: yes or no; true or false; on or off; go or no-go etc. Programming does not fall under any exception. In programming, based on our core logic and use cases, we need to make decisions and based on those decisions; we need to write code accordingly. As a programming language, Java is not an exception and allows us to provide a special data type called “Boolean” to use them in our code for decision-making purposes. A Java Boolean variable or A Boolean expression can take either of the two values: true or false.
Let us discuss about Booleans from a java programming perspective.
Types of Java Boolean Value
Following are the different types of Java Boolean Value:
1. Keyword Boolean with Variable Names
You only have two options with you regarding the values of a Boolean type variable in java. Value to a Boolean type is either true or false. There is no other option available. You need to use keyword Boolean along with variable names and assign the value (true or false) to it.
Syntax:
Boolean <variable_name> = <value>, where value is either true or false
For example:
boolean bool = true, where bool is the variable name and associated with value as true
boolean bool2 = false, where bool is the variable name and associated with value as false
Code Example 1:
public class BooleanInJava { public static void main(String[] args) boolean bool = true ; boolean bool2 = false; System.out.println(bool); System.out.println(bool2); } }
Output:
2. Boolean Type Variable
What if you provide values other than true or false to a Boolean type variable?
For example:
boolean bool = 1 ;
boolean bool2 = 0;
You will get an error for this.
Code Example 2:
public class BooleanInJava { public static void main(String[] args) { boolean bool = 1 ; boolean bool2 = 0; System.out.println(bool); System.out.println(bool2); } }
Output:
3. Feature of Boolean
Now, how to use this feature of Boolean effectively?
We can use it to make decisions in our program. I mean to say that you can use to test some deciding factors in your program by using conditional operators to get or print a Boolean value. This is testing of condition of a Boolean Expression. The program will evaluate this expression, and a decision will be given accordingly.
Let us have some examples:
Code Example 3:
public class BooleanInJava { public static void main(String[] args) { int num1 = 10; int num2 =11; System.out.println(num1 > num2); // returns false, because 11 is higher than 10 System.out.println(num2 > num1); // returns true, because 11 is higher than 10 System.out.println(num1 < num2); // returns true, because 10 is lesser than 11 System.out.println(num2 <num1); // returns false, because 10 is lesser than 11 } }
Output:
How Boolean Value Works?
In this article, we will point out how Boolean works, which means how we can use the feature of Booleans in our program or use cases. As Boolean is helping us to make decisions, we can put this decision logic inside our conditional expressions such as: in while loop evaluation or if-else decision making. First, let us look at the Boolean operators, which will be used to generate a Boolean value from a Boolean expression and eventually use that value in making decisions. We will use here the logical operators for Boolean, which are: | , & , ^ , ! , || , && , == , != . Let us take two Boolean variables, num1 and num2, for use.
Please check the table for your understanding of how evaluation is happening in Boolean expressions. This understanding is very important to clear your concepts:
4. Public Class
Code Example 4:
public class BooleanInJava { public static void main(String[] args) { boolean num1 = true; boolean num2 = false; System.out.println("num1|num2 = "+(num1|num2)); System.out.println("num1&num2 = "+(num1&num2)); System.out.println("num1^num2 = "+(num1^num2)); System.out.println("!num1 = "+(!num1)); System.out.println("!num2 = "+(!num2)); } }
Output:
Let us see some more code examples.
5. Boolean Operators
Code Example 5:
Here we will compare two Boolean variables and assign values to them and then create Boolean expression for those using Boolean operators and then print them to see the final output.
public class BooleanInJava { public static void main(String[] args) { boolean num1 = true; boolean num2 = false; boolean num3=(num1==num2); // Boolean expression evaluating whether values of num1 and num2 are equal or not System.out.println(num1); System.out.println(num2); System.out.println(num3); //will return false as num1 and num2 have different values } }
Output:
6. Boolean Objects.
Code Example 6:
Here we will compare two Boolean objects.
public class BooleanInJava { public static void main(String[] args) { boolean boolObj1=new Boolean("TRUE"); boolean boolObj2=new Boolean("FALSE"); boolean boolObj3=new Boolean("FALSE"); boolean decision=(boolObj1==boolObj2); // evaluating values of boolObj1 and boolObj2 System.out.println("Are the value of boolean objects 1 and 2 equal? "+decision); boolean decision2=(boolObj3==boolObj2); // evaluating values of boolObj2 and boolObj3 System.out.println("Are the value of boolean objects 2 and 3 equal? "+decision2); } }
Output:
Conclusion – Java Boolean
All of the comparisons and conditions in Java are primarily based on Boolean expressions; hence you need to use them in an effective manner. In this topic, you have learned about many aspects of Boolean values but, you need to use them effectively based on your business/ client requirements and use cases.
Recommended Articles
This has been a guide to Java Boolean. Here we have discussed what is Java Boolean, how it works? Explaining the logical operations with Codes and Output. You can also go through our other suggested articles to learn more–
|
https://www.educba.com/java-booleans/
|
CC-MAIN-2022-40
|
refinedweb
| 957
| 55.03
|
After dealing with menus and commands I take a break to show you some new topics related to custom editors. As we develop applications we use programming languages with text editors to define the code to be compiled into our product. Actually, we could solve all software development tasks with text editors, but we like other kind of editors like a Winforms editor or an ASP.NET page editor since they make our work much fun and much productive.
Visual Studio IDE allows us to create editors of our own to extend productivity. To create a custom editor requires much more work than creating tool windows, since a custom editor has much more interaction point with the VS IDE than a tool window has.
In the first parts of this series I used the VSPackage wizard to create simple examples. I could have asked the VSPackage wizard in VS 2008 to create a custom editor for me and I would be able just go through the code and explain you how it works and how to extend it.
This time I chose other approach. The main reason is the code created by the VSPackage wizard: it has about five thousand of lines dealing with the custom editor. It is much longer than really required and can be explained within a few articles. However, there is another reason: the code generated by the wizard is not free of bugs, it often shows up “The operation could not be completed” messages (that means it raises unhandled exceptions). In the sample of VS 2008 SDK I have found an example (C# Example.EditorWithToolbox) that is a very good starting point for talking about custom editors. I got through this example, collected the information about the custom editors and later could make a lot of refactorings. As a result I managed to cut the original fifteen hundred lines of code into a few generic classes to make you able to write a simple custom editor in about a hundred lines of code.
In this article I show you the basic architecture behind custom editors and give you an overview about the example I created. We start to dive into the code and go on with this “under-surface” activity in the next articles.
All of us uses and so all us of know that Visual Studio has text editor, form editor and a few others. These are all internal editors.
With the Tools|External Tools menu function we can add external editors to our Visual Studio environment. Even we add them logically to Visual Studio, when we start them they run in a separate process (as they are separate .exe files).
We can use a few external editors within the editor windows just as if they were run in Visual Studio. A typical example is Microsoft Word 2007 or Excel 2007 in VSTO projects. Actually they are hosted as ActiveX controls in a VS document window. Making these kind of editors requires a lot of task to solve and we must know many other VSX internals (like custom projects, hierarchies, etc.) to create such kind of hosted editors.
In this article we are going to treat only internal editors that run within the devenv.exe process. Would you think or not, internal editors can have a variety of user interface styles:
Single view (window) editors. These are the most common (and simple) forms of editors. The data representing the information behind the editor (or designer) has exactly one view. When we edit a C# class file we use the text editor as a single view of the file.
Multiple view (window) editors. The data edited has multiple different views. An example is the Windows Forms editor. While editing a form file, we can switch between the form view and the code view. Even the data behind the designer (in our case behind the form) can be in multiple files. Depending on the action we do, we can change the content of one or more files. At the same time we can see both the form and the code window (for example we organize them into horizontal or vertical tab groups).
Multi-tabbed (simple window) editors. The data we handle has one or more views but in the same document window on separate tabs. A good example for that is the ASP.NET page editor when we can see the designer representing our page as we’ll have it in a browser and also we have a HTML view. The main difference between the multi-tabbed and the multi-window view is that the tabbed view generally provides a fashion where we see only one of the views provided by the editor and we cannot separate them into different windows.
Visual Studio also provides possibility to write editors bound to a hierarchical view in a tool window. Generally they require so-called custom projects where the editor has some special contract with the project type. An example is the SQL data editor. When we register a data connection to a SQL Server database in the Server Explorer window, we use this kind of hierarchical editors. Treating them is not the topic of this article.
In the introduction I used the term “editor” and “designer”. In some articles and in the VSX documentation you can meet also with both of them. These two terms are interchangeable, so if you read them you know they cover the same idea maybe emphasizing different user perceptions.
The architecture behind the editors uses the MVC principles. To look over its main elements, the following figure will help us a lot:
Just like tool windows, custom editors are objects owned by a VSPackage. The VS Shell provides a service called SVsRegisterEditors that allows a package registering an editor. Actually it means registering a so-called editor factory (represented by an object implementing the IVsEditorFactory). The main reason the factory pattern is used that an editor itself divides its responsibilities among a few objects. The editor factory is the guy who knows how to create and initialize these objects—taking into account the current context.
When I am talking about responsibilities of an editor those are ones like responding to commands (for example Save, Cut, Copy and Paste) arriving from the VS IDE, displaying the user interface of the editor, handling the program code, XML documents or whatever is behind the editor, and so on. Actually, we VS manages two set of responsibilities:
Document View. Our editor has some user interface to allow users interacting with the editor. An editor generally has only one view, but can have two or more. A good example is the ASP.NET webpage editor that has a WYSIWYG designer and a HTML (text) editor, or the XML schema editor that has a graphical and a textual (XML) designer. On the picture above Document View 1 and 2 represents two separate views.
Document Data. There is no reason to edit something without its data representation. The document data is the information we are editing with our custom editor. When we load our editor, this data is loaded into the memory, when we save the document this data is persisted into a file. Actually, VS does not require the data to be persisted in a file, but for this article we go on this thread.
Visual Studio does not require the document view and document data roles to be separated into two or more object instances. One editor instance may be smart enough to undertake the responsibility of the view and the data. It is always a design question how to separate the roles among objects.
When the editor factory created the objects representing the editor, the VS Shell (the services behind the shell) can use them to interact with through the implemented service end points. In the following table I summarize the most important service end points with their responsibility and general usage form.
This interface provides services to create and initialize view and document objects used by the editor. Of course, when closing the editors some cleanup activity is required to release resources held by the editor, so this cleanup service is also provided by IVsEditorFactory. As we have seen, this service endpoint is required by the editor factory object.
Both the document view and the document data must understand commands coming from the environment (VS IDE or other registered packages). For example, the view can understand and execute the Copy and Paste commands. The document data is required to handle the load and save commands. The IOleCommandTarget interface defines this responsibility.
(In Part #13 we treated the idea of command target. This is exactly the behavior defined by IOleCommandTarget. In future articles we’ll meet with it many times, but I think at the end of this article you will have a very good understanding what it does and how it does.)
Just like other windows in the VS IDE, editor windows can be moved, docked, pinned or unpinned, put into tabs and so on. If we create a user interface for our editor, all this windowing tasks are provided by the shell. To leverage on them our document view must implement the IVSWindowPane interface.
(In Part #4 we have already met with IVsWindowPane when we created our tool window. No surprise, VS Shell provides the same services for all windows...)
This set of services is responsible to manage document data persistence (to load it into the memory and save it sowhere). We might think it is a simple interface, but in reality it provides about ten methods. Just to picture that it makes a complex task, let me tell you a few things about it:
The document itself can be persisted to any kind of abstract storage. This interface provides this kind of abstraction.
The user can modify the document outside of Visual Studio. This situation is recognized and the user can reload the modified document.
The file holding the document can be renamed in Visual Studio or saved with the Save as... function.
Generally data behind editors is persisted to files. A document can be load from or saved to different file formats. This interface deals with handling functions related to these tasks.
When we use Visual Studio we generally edit more than one document. To understand how VS Shell handles them, we must look into a few internals.
As I treated a few paragraphs before, editor have document data and one or more document views working on the data. While en editor is not open in Visual Studio, it has no open views and its data is not affected: the data is simple sits in a file or in a database. However, when an editor is open, it means there is a view working on its data. If the editor has multiple views open, there some coordination must be done to synchronize the views.
There are editors where it is quites easy to do: let’s assume we have a database table designer when we can represent a table’s fields in a grid (Grid View) and in a text editor (DDL View). Where we modify the table information in one place, it is quite easy to represent the data in the other view.
There might be editors where it is much more difficult, a good example is the Windows Form editor. When we do some change in the graphical designer, changes are only synchronized in the textual view (in the designer code text) when we save the form.
Visual Studio uses the Running Document Table (RDT) to manage open documents. When we change a document data, it helps to administer what views and what files (or what other persistence elements, for example database tables, stored procedures, etc.) are modified. When we close a file or even the open solution, the RDT is the infrastructure element in the background that helps Visual Studio to pop-up the Save changes window:
Every item we see in the window above is a document in the RDT. A document is something that should be saved (persisted) as a whole undivided unit. If you decide that your application stores everithing in one file (even it is represented in the Solution Explorer as a hierarchy of items), than you have one document. If you decide that one item in the Solution Explorer is represented as two separate files, you have two documents.
RDT used so-called edit locks to coordinate the usage of open documents. When an editor is opened, it opens a view to edit the document. At this time the document goes into the RDT and an edit lock is put on that document. If another view is opened for the document, a new edit lock is put to the document. This is implemented so that RDT uses lock counts. So when the second view is opened, the lock count becomes two.
RDT watches the edit lock count transitions. When the counter goes to zero, Visual Studio prompts us to save the changes. Going back our sample, when we close any of the views from the two opened before, the lock count decrements to 1. It means there is one view already using the document. When we close the second view, the lock count goes to zero and Visual Studio prompts us.
Not only editors and view can open a document. We might use an add-in or a package that generate code snippets with the help of a tool window. When initiating an action, the add-in might invisibly open project files (without opening an editor with views) and put code snippets into them. When the add-in opens files (if it does it through the corresponding APIs of VS), the edit lock count in RDT is also maintaned.
So, what is stored in the RDT? Actually every information that is required to manage the document and its holders:
File path or equivalent URI. When our document is persisted in a file, the RDT must know its full path to provide an “address” when it is accessed. If the document is a database, an item in a logical store (e.g. a record in a databas table, etc.) some URI-like information is stored as an “address”.
A pointer to the object representing the document data in memory. Through this object we can not only access the document data but even check its state (for example, if it is “dirty”, since we modified after opening it).
Document flags. Some simple flags influencing document behaviour (e.g. “Do not save this document”, “Do not open it next time when the solution is opened”, etc.)
Edit locks and read locks.
The owner hierarchy of the document. Each document has an owner in a hierarchy. Generally this is one of the file nodes of the Solution Explorer, but of course it can be any other hierarchy. For example, a SQL database in the Server Explorer also has a hierarchy. This hierarchy is the owner of a database table document. The role of owner is important, since VS Shell does not saves the document directly, it always turns to the owner and asks it to save.
A list of pointers to “invisible” lock holders. I mentioned that add-ins and packages might have open documents invisibly. The RDT keeps a list of this kind of lock holders to notify them about events through the IVsDocumentLockHolder interface the lockers implement.
Editors belong to a file extension. When we register them we also register the file extension them and a property called priority. This priority is important, since it is used by the Shell to find the best editor for a certain file extension. Editors can register file extensions with wildchars (even can register themselves for “.*”.
When Visual Studio opens a file, checks the editors registered for a matching file extension. Then it goes through the list of potential editors in priority order (starts with the highest priority). The editor has the opportunity to make a decision if it can (and wants) to handle the file. If it accepts the file, Visual Studio says “yes, you’ve got it”. If the editor refuses the file, Visual Studio goes to the subsequent editor on its list while it does not find one.
How can it be ensured that there is at least one editor that handles a certain file? The solution is provided by Visual Studio built-in editors: there a re a few editors (for example the binary editor and the XML editor) that registers itself to “.*”. Due to this fact what is happening where there are no specific editors for a certain file is similer to the folllowing scenario:
There are many developers using XML files, so if there is no other editors handling a file, somewhere at the end of the priority list the XML editor tries to open the file. If it recognises that is an XML feli, the editor accepts and loads it. If the file is not an XML file, then the binary editor opens it.
Now it’s the time to see in practice how to create a custom editor. It is a much more complex topic than creating a tool window since we have more functionality behind an editor (if I say designer you can imagine why this functionality is so complex). In the introduction of this article I mentioned that I was not really satisfied with the custom editor code created by the VSPackage wizard, since it was too long with its five thousand lines of code to explain. However, the VS SDK contained the C# Example.EditorWithToolbox sample that was a perfect starting point.
I examined the sample code and established my own example of a simple custom editor. The original sample used a single RichTextEdit control to provide its functionality, but it is not a frequently used example.
I called my example BlogItemEditor having a simple (but multi-control) user interface like this::
<BlogItem xmlns=”...”>
<Title>Sample Blog Item</Title>
<Categories>
<Category>VSX Sample</Category>
<Category>Visual Studio 2008</Category>
<Category>LearnVSXNow!</Category>
</Categories>
<Body>
<![CDATA[
After dealing with menus and commands I take a break to show you some new
topics related to custom editors. As we develop applications we use programming
languages with text editors to define the code to be compiled into our product.
...
Where we are?
]]>
</Body>
</BlogItem>
I created the custom editor with four core types as illustrated in the following diagram:
The BlogItemEditorFactory class does what we expect from an editor factory. I separated the document view and the document data roles into three types. The BlogItemEditorPane undertakes the majority or tasks we expect from a document view and from a document data. The BlogItemEditorControl class that provides user interface for the editor and provides a part of functions what the controller does in the MVC pattern. The BlogItemEditorData stores the information in the memory and is able to persist itself from and to ax XDocument (new style for managing XML documents, see the System.Xml.Linq namespace).
If you look at the user interface prototype, the XML data representation and the simple class diagram above, you may have to the same idea I had when thinking it over:
We can make a bunch of reusable code for simple editors with a form-like user interface persisting in-memory data into XML files. I factored out four reusable types and put them into the VsxLibrary:
Provides an editor factory that creates en editor where the document view and the data view is represented by a TEditorPane type.
Type undertaking the role of a document view and a document data. This type is instantiated by a TFactory editor factory. The user interface is represented by a TUIControl user control.
The interface represents the behavior of a user interface that supports standard editor commands like Select All, Copy, Paste, etc.
A simple interface describing Save and Load operations for an instance of XElement.
To understand how these out-factored element help in the BlogItemEditor example, let’s see the details.
Due to the fact that the SimpleEditorFactory<> generic type does everything an editor factory should do, BlogItemEditorFactory has quite simple code:
[Guid(GuidList.guidBlogEditorFactoryString)]
public sealed class BlogItemEditorFactory:
SimpleEditorFactory<BlogItemEditorPane>
{
}
It will use the BlogItemEditorPane as the view and the data of the editor. As for any other object used by the VS services we need a Guid for the factory.
This class represents the data content (in memory representation) of a blog item. This type has the following blueprint:
public sealed class BlogItemEditorData : IXmlPersistable
public BlogItemEditorData(string title, string categories, string body)
{ ... }
public string Title { get; }
public string Categories { get; }
public string Body { get; }
public void SaveTo(string fileName) { ... }
public void ReadFrom(string fileName) { ... }
// --- IXmlPersistable implementation
public void SaveTo(XElement targetElement) { ... }
public void ReadFrom(XElement sourceElement) { ... }
The Title, Categories and Body properties are used to read the content of the blog item set by the constructor. We have SaveTo(XElement) and ReadFrom(XElement) methods implementing the IXmlPersistable interface. These methods use XElement arguments rather than XDocument arguments since with design you can compose separate IXmlPersistable objects into one XDocument.
The SaveTo and ReadFrom methods with a string argument simply use the XElement content and save it to a file or load it from.
This user control implements the user interface of our blog editor. Allows the user interacting with it and provides support for the most common Visual Studio commands:
public partial class BlogItemEditorControl :
UserControl,
ICommonCommandSupport
public BlogItemEditorControl()
{
InitializeComponent();
}
// ...
// --- ICommonCommandSupport implementation
// ...
This interface defines the behavior a user control must provide to add basic support for the most common editor commands. The definition of this interface tells what this support is:
public interface ICommonCommandSupport
// --- Support flags
bool SupportsSelectAll { get; }
bool SupportsCopy { get; }
bool SupportsCut { get; }
bool SupportsPaste { get; }
bool SupportsRedo { get; }
bool SupportsUndo { get; }
// --- Command execution methods
void DoSelectAll();
void DoCopy();
void DoCut();
void DoPaste();
void DoRedo();
void DoUndo();
Properties having the Supports prefix tell the environment whether the implementer object supports the command named in the property. If the environment finds the object supports the command it will call the appropriate Do-prefixed method to execute that command.
The major part of the whole editor work is done by the BlogItemEditorPane class which represents both the document view and data. However, its code is really simple:
public sealed class BlogItemEditorPane:
SimpleEditorPane<BlogItemEditorFactory, BlogItemEditorControl>
public BlogItemEditorPane() { ... }
protected override string GetFileExtension() { ... }
protected override Guid GetCommandSetGuid() { ... }
protected override void LoadFile(string fileName) { ... }
protected override void SaveFile(string fileName) { ... }
The key of this simplicity is the SimpleEditor<,> generic type that takes two type arguments. The first type is the editor factory creating the view and data for this editor. The second type is the user control defining the user interface of the editor. When deriving our editor pane from SimpleEditor<,> we need only override four abstract methods:
Defines the file extension used by our editor.
Defines the GUID identifying the command set handled by the editor.
Loads the data content of the editor from a file.
Saves the data content of the editor into a file.
It is not a secret, the longest code belongs to the SimpleEditorPane<,> type. Later we’ll see it in details, now let’s have a look for its type definition:
public abstract class SimpleEditorPane<TFactory, TUIControl> :
WindowPane,
IOleCommandTarget,
IVsPersistDocData,
IPersistFileFormat
where TFactory: IVsEditorFactory
where TUIControl: Control, ICommonCommandSupport, new()
SimpleEditorPane implements all the key interfaces required for a custom editor. By inheriting from WindowPane we got the IVsWindowPane implementation. The class implements the IOleCommandTarget to be able process commands; IVsPersistDocData and IPersistFileFormat to handle persistence functions. It accepts only real factory types implementing IVsEditorFactory as the TFactory type argument. Expects user controls implementing the ICommonCommandSupport interface as the TUIControl type argument.
We started to develop a simple custom editor. Before going into the concrete example we examined the basic architecture behind editors in VS. Editors (represented by editor factories) should be registered in Visual Studio in order to use them with associated file types. Editors have concepts for document data and document views. An editor may have one or more views, all views working on the same data.
The Running Document Table is the infrastructure element in the VS IDE that is responsible for managing open documents (document data) behind editors. It implements a simplelocking mechanism to manage saving (or persisting) documents from memory to their physical storage. Registered editors have priorities and Visual Studio find the appropriate (“best”) editor for a certain file using this priority information.
In the article I introduced the basic elements of a BlogItemEditor sample. In the next article we take a deep dive into the code starting with editor factories.
When I started VSX programming with Visual Studio 2008 SDK, one of the most esoteric things were custom
Pingback from ???????????? | VsxHowTo-???Windows Forms Designer???????????????????????????1???
|
http://dotneteers.net/blogs/divedeeper/archive/2008/03/12/LearnVSXNowPart15.aspx
|
CC-MAIN-2014-41
|
refinedweb
| 4,148
| 54.12
|
I have a form which the user is able to change the id of, so I have declared an array containing the details of the form and the array is updated in case the details of the form change, so I can have something like
formdetails = ['someid', 'index.html', 'post'];
but the user can change any of those and the form details could be updated to:
formdetails = ['someotherid', 'form.php', 'get'];
then from inside the function I can call the form by doing:
document.getElementById(formdetails[0]);
I am still learning JS and have read a lot that is best to avoid, as much as possible, the usage of global variables and would like to know how I could use that same updated array or any other variable inside a function if is not global
There are two common techniques that could be applied here.
Store in the HTML
The first common technique is to store the information on an HTML element, such as the container within which your script is applied to.
The benefits of this technique is that you can store any JavaScript variables as properties of the element, and as long as no other scripts try to use the same properties of the same object, you'll be find.
Here's a simple example to demonstrate that technique.
<div id="container">
<p>Content of the container.</p>
<button id="reveal">Reveal other content</button>
</div>
document.getElementById('reveal').onclick = function () {
alert(this.parentNode.otherContent);
};
var container = document.getElementById('container');
container.otherContent = 'More content stored as a property of the container.';
Store in an Object
The second technique is more complex, where you instantiate a JavaScript object that contains all of your methods, which have access to the variables within the instantiating function.
The HTML remains the same as above, and here's the JavaScript for that second technique.
function someObject(otherContent) {
function getOtherContent() {
alert(otherContent);
}
return {
getOther: getOtherContent
};
}
var myObject = someObject('More content stored as a property of the object.');
document.getElementById('reveal').onclick = myObject.getOther;
Typically the first technique does fine, and is easier to apply to your code. The second technique is more robust but can be more difficult to understand.
I always create separate self calling closures for independent pieces of functionality. Essentially, each closure can be thought of an "individual" module that adds some type of functionality to the application without being reliant (dependent) on anything outside it. This keeps the global namespace just about untouched.
// set-up gallery
(function() {
....
})();
// Set-up modal window
(function() {
})();
// Set-up persistent result page using AJAX
(function() {
})();
...
is it a good idea to do something like window.myvar = xxx or it would end up the same as declaring a global variable?
That is precisely the definition of how to declare a global variable.
|
https://www.sitepoint.com/community/t/how-to-avoid-global-variables/88467
|
CC-MAIN-2017-09
|
refinedweb
| 466
| 53.92
|
Copyright © 2006 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark and document use rules apply. Widgets 1.0 specification. This document is produced by the Web Application Formats Working Group, part of the Rich Web Clients Activity in the W3C Interaction Domain.
Web content and browser developers are encouraged to review this draft. Please send comments to public-appformats@w3.org, the W3C's public email list for issues related to Web Application Formats. Archives of the list.
config.xml
widgetElement
widgetnameElement
widthand
heightElements
authorElement
nameElement
organizationElement
linkElement
descriptionElement
iconElement
idElement
securityElement
WidgetObject
Widgets are web applications which use the browser as an environment to run in, but which do not have the usual browser chrome. They are installed on a local client, and have several features that are not available to regular web applications, such as a more explicit security model to allow them to perform a wider range of tasks easily, and a persistent information store apart from cookies.
This specification is not complete. Besides things that are obviously missing there may well be inconsistencies in writing and editorial choices.
They are installed by a user agent, for re-use. This specification does not define the storage method, nor limit the ways the user agent can find a widget (such as downloading, installing from a local file, having widgets pushed to a client, etc).
Eventually this document will attempt to address all requirements of the [WIDGET-REQ] document.
As well as sections marked as non-normative, all diagrams, examples, and notes in this specification are non-normative. Everything else in this specification is normative.
The key words must, must not, required, shall, shall not, should, should not, recommended, may and optional in this document shall be interpreted as described in [RFC2119].
Need to define classes of products.
Widgets are a bundled archive of files, as specified by the [ZIP] file format specification, with exception that the "Deflate64" compression method for the [ZIP] file format is not supported.
I think this last sentence means "conforming to level 2.0 zip". Need to check.
A future revision of this draft will address digital signing of widgets. Need to figure out how.
It has been suggested that the widget should have some means of preventing access to the content of it.
Every widget must contain the following two files:
config.xml
A manifest file containing information necessary to initialize the widget. This file always contains information about the widget's name and geometry, and may optionally contain more information about the widget:
index.html
config.xmlfile. This HTML document can reference external content, including, but not limited to scripts, CSS files and images the same way regular web pages can.
Need to address other formats, such as SVG and XHTML, as well. Probably in a way by making this a whole lot more abstract, so that you can use any language you want.
Need to look into how ZIP actually handles folders and define some useful terminology around that.
The
config.xml and
index.html should be at the root
of the
.zip file, with any associated resources, such as
scripts and images, in the same directory or subdirectories.
In some user agents the config.xml and index.html files may be placed in a directory inside the zip file, with all the widget's files and folders located inside this subfolder. This folder should bear the same name as the compressed zip file. User agents may not support this structure, so authors should not use it.
When a widget is run a virtual root path for a file system is
established based on the location of the
config.xml, where this root path is in the
same folder where
config.xml
exists.
When widgets are served from web servers, they must be
served with the content-type
application/widget.
Need to register this.
When not served over HTTP widgets should
have the file extension
.widget
config.xml
This is an XML file, do we need a namespace? Advantages either way: input solicited.
Need to address licensing and copyright information. Also per file or just for the whole widget?
Some necessary information to run a widget is stored in a file named
config.xml. This file contains
information about the widget's size which is neccesary to establish the
initial view for the widget file. The
config.xml file is an XML document [XML].
A minimal
config.xml looks like
the following, giving the widget a name, and an initial viewport the size
of 300×300 pixels:
<widget> <widgetname> Hello World! </widgetname> <width> 300 </width> <height> 300 </height> </widget>
Element content presented to the user must be styled
as if the value
normal for the
white-space
property in [CSS21] is applied.
widgetElement
widgetname,
widthand
heightelement and optionally one of each
author,
description,
icon,
securityand
idelement.
The
widget element is the root
element of the
config.xml file and
must be present.
widgetnameElement
widgetelement.
The
widgetname element must be present in
config.xml as a child of the
widget element. It should
contain a string whose purpose is to provide a human-readable title for
the widget that can be used for example in application menus and similar
contexts.
widthand
heightElements
The
width and
height elements must be
present in
config.xml as children
of the
widget element. After stripping
of any leading/trailing whitespace the value of this element must be interpretable as a string representation of an
integer, containing only the characters [0-9].
These integers give the initial width and height of the viewport avilable to the widget, measured in CSS pixels, as per section 4.3.2 of [CSS21].
This should handle percentages or perhaps defer the whole thing to CSS? CSS should probably remain optional... Need default values as well (for when the elements are omitted). Perhaps make it clear that these give the initial height and width as you can use scripting to change that.
authorElement
widgetelement.
name,
organization,
linkelements
The
author element is an optional
element of the
widget element. If
present, the purpose of the element is to provide information about the
widget's author.
nameElement
authorelement.
If the
author element is present in
the document, this element should be present as well. If
present, this element must be a child of the
author element and its value must be a string that contains a human-readable
representation of the widget author's name.
organizationElement
authorelement.
If this element is used present, it must be a child of
the
author element and its value should be a string that contains a human-readable name for
an organization representing or represented by the widget author.
authorelement.
When present, this element must contain a string, whose value should be a valid e-mail adress as specified by [RFC2822]. This e-mail address should be a live e-mail address widget users can use to contact the widget author.
linkElement
authorelement.
If the
author element is present,
the
link element should be present as well and if it is it must be a child element of the
author element and contain a string whose value
is a syntactically valid IRI as specified by [RFC3987]. User agents should make this IRI available as a link the user can follow
to find out more about the author.
descriptionElement
widgetelement.
If present, this element must be a child of the
widget element and should contain a string that serves as a human-readable
short plain-text description of the widget.
iconElement
widgetelement.
The
icon element should be present as a child of the
widget element. The purpose of this element is
to provide a pointer to an icon file contained within the widget archive
that the underlying operating system and widget player can display to the
end user as appropriate. This may include as an icon in
a toolbar, widget management interface or siimilar.
The element must contain a string that is a relative
reference in accordance with [RFC3987], with the root path being the same
as the location of the
config.xml
file.
When present, the IRI should resolve, and should reference an image, in either of the following formats: [PNG] or [GIF]. User agents may recognize other formats.
idElement
The plan is for this element to define a universally unique
identifier for the widget. Together with an element that defines a
timestamp, like
atom:updated, this creates a simple
versioning mechanism.
Perhaps rename
id to
something else. Suggestions welcome!
securityElement
Specific details of this element are to be determined. This element might address things like:
WidgetObject
The purpose of the
widget object is to expose functionality
specific to widgets that either should not or must not be available to scripts running on regular web
pages.
interface Widget { void openURL(DOMString url); DOMString preferenceForKey(DOMString key); void setPreferenceForKey(DOMString value, DOMString key); }
openURL(url), method
The
openURL() method on the widget object takes a String
as an argument. as defined by [RFC3987]. When this method is called with
a valid URL as defined by [RFC3987], the URL should be opened in the system browser on the system on
which the widget runs.
Note that restrictions to what URLs can be opened using openURL, as defined in the security section of this specification. Specifically this applies:
openURL()does not accept relative IRI’s and as such cannot open any files stored inside the widget.
preferenceForKey(), method
The
preferenceForKey()
method takes a String argument, key. When called, this method
shall return a string that has previously been stored
with the
setPreferenceForKey method, or
undefined if the key key does not exist.
setPreferenceForKey(), method
The
setPreferenceForKey() method
takes two String arguments, preference and key.
When called, this method shall store the string in the
preference argument with the key named in the key
argument for later retrieval using the
preferenceForKey() method. If the
setPreferenceForKey()
method is called with the value null in the
preference argument, the key identified in the key
argument shall be deleted.
This should probably be defined in The Window Object specification.ForKey() propably. pseudocode: only applies to HTML user agents.. An
example in HTML would look like this:
<link type="application/widget" rel="alternate" href="" title="An Example Widget">
A document may contain multiple autodiscovery elements. A User Agent should present an installation option for all autodiscovered widgets to the user, listed in the order of appearance in the source code.
Only when the following conditions are met a user agent should expose the available widget(s) for download:
typeattribute of the
linkelement is set to
application/widget(case-insensitive matching);
relattribute of the
linkelement contains the
alternatevalue, but not
stylesheet(case-insensitive matching);
hrefattribute of the
linkelement is not absent;
We should probably have some author requirements as well: title attribute should have a meaningfull value. If multiple link elements are provided the title attributes should be clear. Not just "Widget 1", "Widget 2", etc. The href attribute should point to a location that actually has a widget served with the application/widget media type, etc.
User agents may block access to resources according to internal security models. User agents should consider the following things when implementing a security model:
An intranet is defined based on the resolved IPv4 address of a host name. The following IPv4 ranges are defined as intranets:
All other IP ranges than these are defined as Internet addresses.
This section needs more details, including requirements on
how to implement the security model, given that we keep signing and the
security element.
The editors would like to thank the following people for their contributions to this specification:
Special thanks go to Arve Bersvendsen and Charles McCathieNevile who wrote the initial version of this document, "Opera Widgets 1.0."
The
widget object was based on Apple's
Dashboard [Dashboard] and Widget Autodiscovery is based on Atom
Autodiscovery [AtomAutodiscovery].
|
http://www.w3.org/TR/2006/WD-widgets-20061109/
|
CC-MAIN-2015-32
|
refinedweb
| 1,977
| 54.52
|
This Module provides a quick and easy way to build complex SOAP data and header structures for use with SOAP::Lite. It primarily provides a wrapper around SOAP::Serializer and SOAP::Data (or SOAP::Header) enabling you to generate complex XML within y...TEEJAY/SOAP-Data-Builder-1 - 14 Mar 2012 06:47:19 GMT
Simplified interface to SOAP::Data for creating data structures for use with SOAP::Lite....MJEMMESON/SOAP-Data-Builder-Simple-0.04 - 16 Feb 2015 18:09:54 GMT
This Module provides a quick and easy way to build complex SOAP data and header structures for use with SOAP::Lite, managed by SOAP::Data::Builder....TEEJAY/SOAP-Data-Builder-1 - 14 Mar 2012 06:47:19 GMT
This module is intended to make it much easier to create complex SOAP::Data objects in an object-oriented class-structure, as users of SOAP::Lite must currently craft SOAP data structures manually. It uses SOAP::Data::Builder internally to store and ...RYBSKEJ/SOAP-Data-ComplexType-0.044 - 13 Nov 2006 16:18:54 GMT
SOAP::Data::ComplexType::Array is an abstract class that represents the native Array complex type in SOAP. This allows users to define complex types that extend the Array class...RYBSKEJ/SOAP-Data-ComplexType-0.044 - 13 Nov 2006 16:18:54 GMT
SOAP::Lite is a collection of Perl modules which provides a simple and lightweight interface to the Simple Object Access Protocol (SOAP) both on client and server side....PHRED/SOAP-Lite-1.27 - 14 May 2018 20:36:08 GMT
MARCEL/Data-Conveyor-1.103130 - 09 Nov 2010 12:41:30 GMT.14 - 04 Sep 2015 06:40:18 GMT - 02 Apr 2015 17:39:19 GMT
Kwiki::SOAP provides a base class and framework for access SOAP services from a WAFL phrase. It can be used directly (as shown in the synopsis) but is designed to be subclassed for special data handling and presentation management. You can see Kwiki:...CDENT/Kwiki-Soap-0.05 - 15 Jun 2005 07:10:41 GMT
BYRNE/SOAP-MIME-0.55-7 - 16 Apr 2003 16:41:06 GMT GMT GMT GMT
EKAWAS/lsid-perl-1.1.7 - 05 Nov 2007 19:38:52 GMT GMT
A number of "constant" values are provided by means of this namespace. The values aren't constants in the strictest sense; the purpose of the values detailed here is to allow the application to change them if it desires to alter the specific behavior...PHRED/SOAP-Lite-1.27 - 14 May 2018 20:36:08 GMT
IVANWILLS/W3C-SOAP-0.14 - 04 Sep 2015 06:40:18 GMT
|
https://metacpan.org/search?q=module%3ASOAP%3A%3AData
|
CC-MAIN-2020-05
|
refinedweb
| 438
| 54.83
|
Re: from __future__ import absolute_import ?
- From: Ron Adam <rrr@xxxxxxxxxxx>
- Date: Sat, 03 Feb 2007 10:30:35 -0600
Peter Otten wrote:
Ron Adam wrote:
work
|
|- foo.py # print "foo not in bar"
|
`- bar
|
|- __init__.py
|
|- foo.py # print "foo in bar"
|
|- absolute.py # from __futer__ import absolute_import
| # import foo
|
`- relative.py # import foo
* Where "work" is in the path.
(1)
C:\work>python -c "import bar.absolute"
foo not in bar
C:\work>python -c "import bar.relative"
foo in bar
(2)
C:\work>python -m "bar.absolute"
foo not in bar
C:\work>python -m "bar.relative"
foo not in bar
(3)
C:\work>python
Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)]
on win 32
Type "help", "copyright", "credits" or "license" for more information.
>>> import bar.absolute
foo not in bar
>>> import bar.relative
foo in bar
(4)
C:\work>cd bar
A path below the package level is generally a good means to shoot yourself
in the foot and should be avoided with or without absolute import.
Seems so. :-/
C:\work\bar>python -c "import bar.absolute"
foo in bar
C:\work\bar>python -c "import bar.relative"
foo in bar
(5)
C:\work\bar>python
Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)]
on win 32
Type "help", "copyright", "credits" or "license" for more information.
>>> import bar.absolute
foo in bar
>>> import bar.relative
foo in bar
>>>
Case (2) seems like it is a bug.
I think so, too.
This one is the reasons I had trouble figuring it out. I was using the -m command option when I tried to test it.
There is a bug report on absolute/relative imports already. I'm not sure if this particular item is covered under it or not. Doesn't sound like it as the bug report address the relative aspects of it.
Why not also have (4), and (5) do the same as cases (1) and (3)?
The work/bar directory is the current working directory and occurs in the
path before the work directory.
Yes. Unfortunately this is a side effect of using the os's directory structure to represent a python "package" structure. If a package was represented as a combined single file. Then the working directory would always be the package directory.
> When bar.absolute imports foo python is
> unaware that work/bar/foo.py is part of the bar package.
Umm.... isn't the "bar" stuck on the front of "bar.absolute" a pretty obvious hint. ;-)
If you run the module directly as a file...
python bar/foo.py
or python foo.py
Then I can see that it doesn't know. But even then, it's possible to find out. ie... just check for an __init__.py file.
Python has a certain minimalist quality where it tries to do a lot with a minimum amount of resources, which I generally love. But in this situation that might not be the best thing. It would not be difficult for python to detect if a module is in a package, and determine the package location. With the move to explicit absolute/relative imports, it would make since if python also were a little smarter in this area.
in cases (4) and (5), that is the result I would expect if I did:
import absolute # with no 'bar.' prefix.
import relative
From what I understand, in 2.6 relative imports will be depreciated, and
in 2.7
they will raise an error. (providing plans don't change)
Would that mean the absolute imports in (4) and (5) would either find the
'foo not in bar' or raise an error?
No, in 1, 3 -- and 2 if the current behaviour is indeed a bug. This is only
for the relative import which would have to be spelt
from . import foo
Was that a 'yes' for exampels 4 and 5, since 1,2 and 3 are 'no'?
in an absolute-import-as-default environment;
import foo
would always be an absolute import.
But what is the precise meaning of "absolute import" in this un-dotted case?
Currently it is:
"A module or package that is located in sys.path or the current directory".
But maybe a narrower interpretation may be better?:
"A module or package found in sys.path, or the current directory
and is *not* in a package."
If it's in a package then the dotted "absolute" name should be used. Right?
I guess what I'm getting at, is it would be nice if the following were always true.
from __import__ import absolute_import
import thispackage.module
import thispackage.subpackage
# If thispackage is the same name as the current package,
# then do not look on sys.path.
import otherpackage.module
import otherpackage.subpackage
# If otherpackage is a different name from the current package,
# then do not look in this package.
import module
import package
# Module and package are not in a package, even the current one,
# so don't look in any packages, even if the current directory is
# in this (or other) package.
If these were always true, :-) I think it avoid some situations where things don't work, or don't work like one would expect.
In addition to the above, when executing modules directly from a directory inside a package, if python were to detect the package and then follow these same rules. It would avoid even more surprises. While you are editing modules in a package, you could then run them directly and get the same behavior you get if you cd'd out of the package and then ran it.
All in all, what I'm suggesting is that the concept of a package (type) be much stronger than that of a search path or current directory. And that this would add a fair amount of reliability to the language.
IMHO, of course. :-)
Cheers,
Ron
If so, is there any way to force (warning/error) behavior now?
I don't know.
Peter
.
- Follow-Ups:
- Re: from __future__ import absolute_import ?
- From: Peter Otten
- References:
- from __future__ import absolute_import ?
- From: Ron Adam
- Re: from __future__ import absolute_import ?
- From: Peter Otten
- Re: from __future__ import absolute_import ?
- From: Ron Adam
- Re: from __future__ import absolute_import ?
- From: Peter Otten
- Prev by Date: Re: Python does not play well with others
- Next by Date: Re: Jython
- Previous by thread: Re: from __future__ import absolute_import ?
- Next by thread: Re: from __future__ import absolute_import ?
- Index(es):
|
http://coding.derkeiler.com/Archive/Python/comp.lang.python/2007-02/msg00466.html
|
crawl-002
|
refinedweb
| 1,088
| 68.06
|
28 November 2011 08:49 [Source: ICIS news]
SINGAPORE (ICIS)--?xml:namespace>
The company’s December Far East Contract Price (FECP) nomination is on a cost and freight (CFR)
The downstream acrylonitrile-butadiene-styrene (ABS) producers are increasing their operating rates to 70-80% from 50-60% previously, thus lifting demand for ACN, traders said.
“Market sentiment has turned more positive. Demand is picking up and we have been getting more enquiries from customers in
Production cutbacks by several Asian ACN producers in
ACN spot prices were assessed at $1,700-1,750/tonne CFR (cost and freight)
ACN spot prices have been falling steadily since late April, when prices were at $2,750-2,850/tonne CFR NE Asia, ICIS data showed.
($1 = €0.75)
For more information on
|
http://www.icis.com/Articles/2011/11/28/9511921/japans-asahi-kasei-keeps-2000tonne-acn-offer-for-dec-contract.html
|
CC-MAIN-2015-22
|
refinedweb
| 130
| 57
|
General cleanups as part of the libcaps userland threading work.
1: /*- 2: * Copyright (c) 1993: * $FreeBSD: src/sys/i386/include/asmacros.h,v 1.18 1999/08/28 00:44:06 peter Exp $ 34: * $DragonFly: src/sys/i386/include/asmacros.h,v 1.6 2003/12/04 20:09:33 dillon Exp $ 35: */ 36: 37: #ifndef _MACHINE_ASMACROS_H_ 38: #define _MACHINE_ASMACROS_H_ 39: 40: #include <sys/cdefs.h> 41: 42: #ifdef _KERNEL 43: 44: /* 45: * Access to a per-cpu data element 46: */ 47: #define PCPU(x) %fs:gd_ ## x 48: 49: #endif 50: 51: /* 52: * CNAME and HIDENAME manage the relationship between symbol names in C 53: * and the equivalent assembly language names. CNAME is given a name as 54: * it would be used in a C program. It expands to the equivalent assembly 55: * language name. HIDENAME is given an assembly-language name, and expands 56: * to a possibly-modified form that will be invisible to C programs. 57: */ 58: #define CNAME(csym) csym 59: #define HIDENAME(asmsym) __CONCAT(.,asmsym) 60: 61: #define ALIGN_PAGE .p2align PAGE_SHIFT /* page alignment */ 62: #define ALIGN_DATA .p2align 2 /* 4 byte alignment, zero filled */ 63: #ifdef GPROF 64: #define ALIGN_TEXT .p2align 4,0x90 /* 16-byte alignment, nop filled */ 65: #else 66: #define ALIGN_TEXT .p2align 2,0x90 /* 4-byte alignment, nop filled */ 67: #endif 68: #define SUPERALIGN_TEXT .p2align 4,0x90 /* 16-byte alignment, nop filled */ 69: 70: #define GEN_ENTRY(name) ALIGN_TEXT; .globl CNAME(name); \ 71: .type CNAME(name),@function; CNAME(name): 72: #define NON_GPROF_ENTRY(name) GEN_ENTRY(name) 73: #define NON_GPROF_RET .byte 0xc3 /* opcode for `ret' */ 74: 75: #ifdef GPROF 76: /* 77: * __mcount is like [.]mcount except that doesn't require its caller to set 78: * up a frame pointer. It must be called before pushing anything onto the 79: * stack. gcc should eventually generate code to call __mcount in most 80: * cases. This would make -pg in combination with -fomit-frame-pointer 81: * useful. gcc has a configuration variable PROFILE_BEFORE_PROLOGUE to 82: * allow profiling before setting up the frame pointer, but this is 83: * inadequate for good handling of special cases, e.g., -fpic works best 84: * with profiling after the prologue. 85: * 86: * [.]mexitcount is a new function to support non-statistical profiling if an 87: * accurate clock is available. For C sources, calls to it are generated 88: * by the FreeBSD extension `-mprofiler-epilogue' to gcc. It is best to 89: * call [.]mexitcount at the end of a function like the MEXITCOUNT macro does, 90: * but gcc currently generates calls to it at the start of the epilogue to 91: * avoid problems with -fpic. 92: * 93: * [.]mcount and __mcount will not clobber the call-used registers or %ef. 94: * [.]mexitcount will not clobber the call-used registers or %ef. 95: * 96: * Cross-jumping makes non-statistical profiling timing more complicated. 97: * It is handled in many cases by calling [.]mexitcount before jumping. It 98: * is handled for conditional jumps using CROSSJUMP() and CROSSJUMP_LABEL(). 99: * It is handled for some fault-handling jumps by not sharing the exit 100: * routine. 101: * 102: * ALTENTRY() must be before a corresponding ENTRY() so that it can jump to 103: * the main entry point. Note that alt entries are counted twice. They 104: * have to be counted as ordinary entries for gprof to get the call times 105: * right for the ordinary entries. 106: * 107: * High local labels are used in macros to avoid clashes with local labels 108: * in functions. 109: * 110: * Ordinary `ret' is used instead of a macro `RET' because there are a lot 111: * of `ret's. 0xc3 is the opcode for `ret' (`#define ret ... ret' can't 112: * be used because this file is sometimes preprocessed in traditional mode). 113: * `ret' clobbers eflags but this doesn't matter. 114: */ 115: #define ALTENTRY(name) GEN_ENTRY(name) ; MCOUNT ; MEXITCOUNT ; jmp 9f 116: #define CROSSJUMP(jtrue, label, jfalse) \ 117: jfalse 8f; MEXITCOUNT; jmp __CONCAT(to,label); 8: 118: #define CROSSJUMPTARGET(label) \ 119: ALIGN_TEXT; __CONCAT(to,label): ; MCOUNT; jmp label 120: #define ENTRY(name) GEN_ENTRY(name) ; 9: ; MCOUNT 121: #define FAKE_MCOUNT(caller) pushl caller ; call __mcount ; addl $4,%esp 122: #define MCOUNT call __mcount 123: #define MCOUNT_LABEL(name) GEN_ENTRY(name) ; nop ; ALIGN_TEXT 124: #define MEXITCOUNT call HIDENAME(mexitcount) 125: #define ret MEXITCOUNT ; NON_GPROF_RET 126: 127: #else /* !GPROF */ 128: /* 129: * ALTENTRY() has to align because it is before a corresponding ENTRY(). 130: * ENTRY() has to align to because there may be no ALTENTRY() before it. 131: * If there is a previous ALTENTRY() then the alignment code for ENTRY() 132: * is empty. 133: */ 134: #define ALTENTRY(name) GEN_ENTRY(name) 135: #define CROSSJUMP(jtrue, label, jfalse) jtrue label 136: #define CROSSJUMPTARGET(label) 137: #define ENTRY(name) GEN_ENTRY(name) 138: #define FAKE_MCOUNT(caller) 139: #define MCOUNT 140: #define MCOUNT_LABEL(name) 141: #define MEXITCOUNT 142: #endif /* GPROF */ 143: 144: #endif /* !_MACHINE_ASMACROS_H_ */
|
http://www.dragonflybsd.org/cvsweb/src/sys/i386/include/Attic/asmacros.h?f=h;content-type=text%2Fx-cvsweb-markup;ln=1;rev=1.6
|
CC-MAIN-2015-11
|
refinedweb
| 797
| 56.35
|
Last Updated on January 13, 2021
It can be more flexible to predict probabilities of an observation belonging to each class in a classification problem rather than predicting classes directly.
This flexibility comes from the way that probabilities may be interpreted using different thresholds that allow the operator of the model to trade-off concerns in the errors made by the model, such as the number of false positives compared to the number of false negatives. This is required when using models where the cost of one error outweighs the cost of other types of errors.
Two diagnostic tools that help in the interpretation of probabilistic forecast for binary (two-class) classification predictive modeling problems are ROC Curves and Precision-Recall curves.
In this tutorial, you will discover ROC Curves, Precision-Recall Curves, and when to use each to interpret the prediction of probabilities for binary classification problems.
After completing this tutorial, you will know:
-.
Kick-start your project with my new book Probability for Machine Learning, including step-by-step tutorials and the Python source code files for all examples.
Let’s get started.
- Update Aug/2018: Fixed bug in the representation of the no skill line for the precision-recall plot. Also fixed typo where I referred to ROC as relative rather than receiver (thanks spellcheck).
- Update Nov/2018: Fixed description on interpreting size of values on each axis, thanks Karl Humphries.
- Update Jun/2019: Fixed typo when interpreting imbalanced results.
- Update Oct/2019: Updated ROC Curve and Precision Recall Curve plots to add labels, use a logistic regression model and actually compute the performance of the no skill classifier.
- Update Nov/2019: Improved description of no skill classifier for precision-recall curve.
How and When to Use ROC Curves and Precision-Recall Curves for Classification in Python
Photo by Giuseppe Milo, some rights reserved.
Tutorial Overview
This tutorial is divided into 6 parts; they are:
- Predicting Probabilities
- What Are ROC Curves?
- ROC Curves and AUC in Python
- What Are Precision-Recall Curves?
- Precision-Recall Curves and AUC in Python
- When to Use ROC vs. Precision-Recall Curves?
Predicting Probabilities
In a classification problem, we may decide to predict the class values directly.
Alternately, it can be more flexible to predict the probabilities for each class instead. The reason for this is to provide the capability to choose and even calibrate the threshold for how to interpret the predicted probabilities.
For example, a default might be to use a threshold of 0.5, meaning that a probability in [0.0, 0.49] is a negative outcome (0) and a probability in [0.5, 1.0] is a positive outcome (1).
This threshold can be adjusted to tune the behavior of the model for a specific problem. An example would be to reduce more of one or another type of error.
When making a prediction for a binary or two-class classification problem, there are two types of errors that we could make.
- False Positive. Predict an event when there was no event.
- False Negative. Predict no event when in fact there was an event.
By predicting probabilities and calibrating a threshold, a balance of these two concerns can be chosen by the operator of the model.
For example, in a smog prediction system, we may be far more concerned with having low false negatives than low false positives. A false negative would mean not warning about a smog day when in fact it is a high smog day, leading to health issues in the public that are unable to take precautions. A false positive means the public would take precautionary measures when they didn’t need to.
A common way to compare models that predict probabilities for two-class problems is to use a ROC curve.
What Are ROC Curves?
A useful tool when predicting the probability of a binary outcome is the Receiver Operating Characteristic curve, or ROC curve.
It is a plot of the false positive rate (x-axis) versus the true positive rate (y-axis) for a number of different candidate threshold values between 0.0 and 1.0. Put another way, it plots the false alarm rate versus the hit rate.
The true positive rate is calculated as the number of true positives divided by the sum of the number of true positives and the number of false negatives. It describes how good the model is at predicting the positive class when the actual outcome is positive.
The true positive rate is also referred to as sensitivity.
The false positive rate is calculated as the number of false positives divided by the sum of the number of false positives and the number of true negatives.
It is also called the false alarm rate as it summarizes how often a positive class is predicted when the actual outcome is negative.
The false positive rate is also referred to as the inverted specificity where specificity is the total number of true negatives divided by the sum of the number of true negatives and false positives.
Where:
The ROC curve is a useful tool for a few reasons:
- The curves of different models can be compared directly in general or for different thresholds.
- The area under the curve (AUC) can be used as a summary of the model skill.
The shape of the curve contains a lot of information, including what we might care about most for a problem, the expected false positive rate, and the false negative rate.
To make this clear:
- Smaller values on the x-axis of the plot indicate lower false positives and higher true negatives.
- Larger values on the y-axis of the plot indicate higher true positives and lower false negatives.
If you are confused, remember, when we predict a binary outcome, it is either a correct prediction (true positive) or not (false positive). There is a tension between these options, the same with true negative and false negative.
A skilful model will assign a higher probability to a randomly chosen real positive occurrence than a negative occurrence on average. This is what we mean when we say that the model has skill. Generally, skilful models are represented by curves that bow up to the top left of the plot.
A no-skill classifier is one that cannot discriminate between the classes and would predict a random class or a constant class in all cases. A model with no skill is represented at the point (0.5, 0.5). A model with no skill at each threshold is represented by a diagonal line from the bottom left of the plot to the top right and has an AUC of 0.5.
A model with perfect skill is represented at a point (0,1). A model with perfect skill is represented by a line that travels from the bottom left of the plot to the top left and then across the top to the top right.
An operator may plot the ROC curve for the final model and choose a threshold that gives a desirable balance between the false positives and false negatives.
Want to Learn Probability for Machine Learning
Take my free 7-day email crash course now (with sample code).
Click to sign-up and also get a free PDF Ebook version of the course.
ROC Curves and AUC in Python
We can plot a ROC curve for a model in Python using the roc_curve() scikit-learn function.
The function takes both the true outcomes (0,1) from the test set and the predicted probabilities for the 1 class. The function returns the false positive rates for each threshold, true positive rates for each threshold and thresholds..
A complete example of calculating the ROC curve and ROC AUC for a Logistic Regression model on a small test problem is listed below.
Running the example prints the ROC AUC for the logistic regression model and the no skill classifier that only predicts 0 for all examples.
A plot of the ROC curve for the model is also created showing that the model has skill.
Note: Your results may vary given the stochastic nature of the algorithm or evaluation procedure, or differences in numerical precision. Consider running the example a few times and compare the average outcome.
ROC Curve Plot for a No Skill Classifier and a Logistic Regression Model
What Are Precision-Recall Curves?
There are many ways to evaluate the skill of a prediction model.
An approach in the related field of information retrieval (finding documents based on queries) measures precision and recall.
These measures are also useful in applied machine learning for evaluating binary classification models.
Precision is a ratio of the number of true positives divided by the sum of the true positives and false positives. It describes how good a model is at predicting the positive class. Precision is referred to as the positive predictive value.
or
Recall is calculated as the ratio of the number of true positives divided by the sum of the true positives and the false negatives. Recall is the same as sensitivity.
or
Reviewing both precision and recall is useful in cases where there is an imbalance in the observations between the two classes. Specifically, there are many examples of no event (class 0) and only a few examples of an event (class 1).
The reason for this is that typically the large number of class 0 examples means we are less interested in the skill of the model at predicting class 0 correctly, e.g. high true negatives.
Key to the calculation of precision and recall is that the calculations do not make use of the true negatives. It is only concerned with the correct prediction of the minority class, class 1.
A precision-recall curve is a plot of the precision (y-axis) and the recall (x-axis) for different thresholds, much like the ROC curve.
A no-skill classifier is one that cannot discriminate between the classes and would predict a random class or a constant class in all cases. The no-skill line changes based on the distribution of the positive to negative classes. It is a horizontal line with the value of the ratio of positive cases in the dataset. For a balanced dataset, this is 0.5.
While the baseline is fixed with ROC, the baseline of [precision-recall curve] is determined by the ratio of positives (P) and negatives (N) as y = P / (P + N). For instance, we have y = 0.5 for a balanced class distribution …
— The Precision-Recall Plot Is More Informative than the ROC Plot When Evaluating Binary Classifiers on Imbalanced Datasets, 2015.
A model with perfect skill is depicted as a point at (1,1). A skilful model is represented by a curve that bows towards (1,1) above the flat line of no skill.
There are also composite scores that attempt to summarize the precision and recall; two examples include:
- F-Measure or F1 score: that calculates the harmonic mean of the precision and recall (harmonic mean because the precision and recall are rates).
- Area Under Curve: like the AUC, summarizes the integral or an approximation of the area under the precision-recall curve.
In terms of model selection, F-Measure summarizes model skill for a specific probability threshold (e.g. 0.5), whereas the area under curve summarize the skill of a model across thresholds, like ROC AUC.
This makes precision-recall and a plot of precision vs. recall and summary measures useful tools for binary classification problems that have an imbalance in the observations for each class.
Precision-Recall Curves in Python
Precision and recall can be calculated in scikit-learn.
The precision and recall can be calculated for thresholds using the precision_recall_curve() function that takes the true output values and the probabilities for the positive class as input and returns the precision, recall and threshold values.
The F-Measure can be calculated by calling the f1_score() function that takes the true class values and the predicted class values as arguments.
The area under the precision-recall curve can be approximated by calling the auc() function and passing it the recall (x) and precision (y) values calculated for each threshold.
When plotting precision and recall for each threshold as a curve, it is important that recall is provided as the x-axis and precision is provided as the y-axis.
The complete example of calculating precision-recall curves for a Logistic Regression model is listed below.
Running the example first prints the F1, area under curve (AUC) for the logistic regression model.
Note: Your results may vary given the stochastic nature of the algorithm or evaluation procedure, or differences in numerical precision. Consider running the example a few times and compare the average outcome.
The precision-recall curve plot is then created showing the precision/recall for each threshold for a logistic regression model (orange) compared to a no skill model (blue).
Precision-Recall Plot for a No Skill Classifier and a Logistic Regression Model
When to Use ROC vs. Precision-Recall Curves?
Generally, the use of ROC curves and precision-recall curves are as follows:
- ROC curves should be used when there are roughly equal numbers of observations for each class.
- Precision-Recall curves should be used when there is a moderate to large class imbalance.
The reason for this recommendation is that ROC curves present an optimistic picture of the model on datasets with a class imbalance.
However, ROC curves can present an overly optimistic view of an algorithm’s performance if there is a large skew in the class distribution. […] Precision-Recall (PR) curves, often used in Information Retrieval , have been cited as an alternative to ROC curves for tasks with a large skew in the class distribution.
— The Relationship Between Precision-Recall and ROC Curves, 2006.
Some go further and suggest that using a ROC curve with an imbalanced dataset might be deceptive and lead to incorrect interpretations of the model skill.
[…] the visual interpretability of ROC plots in the context of imbalanced datasets can be deceptive with respect to conclusions about the reliability of classification performance, owing to an intuitive but wrong interpretation of specificity. [Precision-recall curve] plots, on the other hand, can provide the viewer with an accurate prediction of future classification performance due to the fact that they evaluate the fraction of true positives among positive predictions
— The Precision-Recall Plot Is More Informative than the ROC Plot When Evaluating Binary Classifiers on Imbalanced Datasets, 2015.
The main reason for this optimistic picture is because of the use of true negatives in the False Positive Rate in the ROC Curve and the careful avoidance of this rate in the Precision-Recall curve.
If the proportion of positive to negative instances changes in a test set, the ROC curves will not change. Metrics such as accuracy, precision, lift and F scores use values from both columns of the confusion matrix. As a class distribution changes these measures will change as well, even if the fundamental classifier performance does not. ROC graphs are based upon TP rate and FP rate, in which each dimension is a strict columnar ratio, so do not depend on class distributions.
— ROC Graphs: Notes and Practical Considerations for Data Mining Researchers, 2003.
We can make this concrete with a short example.
Below is the same ROC Curve example with a modified problem where there is a ratio of about 100:1 ratio of class=0 to class=1 observations (specifically Class0=985, Class1=15).
Running the example suggests that the model has skill.
Note: Your results may vary given the stochastic nature of the algorithm or evaluation procedure, or differences in numerical precision. Consider running the example a few times and compare the average outcome.
Indeed, it has skill, but all of that skill is measured as making correct true negative predictions and there are a lot of negative predictions to make.
If you review the predictions, you will see that the model predicts the majority class (class 0) in all cases on the test set. The score is very misleading.
A plot of the ROC Curve confirms the AUC interpretation of a skilful model for most probability thresholds.
ROC Curve Plot for a No Skill Classifier and a Logistic Regression Model for an Imbalanced Dataset
We can also repeat the test of the same model on the same dataset and calculate a precision-recall curve and statistics instead.
The complete example is listed below.
Running the example first prints the F1 and AUC scores.
Note: Your results may vary given the stochastic nature of the algorithm or evaluation procedure, or differences in numerical precision. Consider running the example a few times and compare the average outcome.
We can see that the model is penalized for predicting the majority class in all cases. The scores show that the model that looked good according to the ROC Curve is in fact barely skillful when considered using using precision and recall that focus on the positive class.
The plot of the precision-recall curve highlights that the model is just barely above the no skill line for most thresholds.
This is possible because the model predicts probabilities and is uncertain about some cases. These get exposed through the different thresholds evaluated in the construction of the curve, flipping some class 0 to class 1, offering some precision but very low recall.
Precision-Recall Plot for a No Skill Classifier and a Logistic Regression Model for am Imbalanced Dataset
Further Reading
This section provides more resources on the topic if you are looking to go deeper.
Papers
- A critical investigation of recall and precision as measures of retrieval system performance, 1989.
- The Relationship Between Precision-Recall and ROC Curves, 2006.
- The Precision-Recall Plot Is More Informative than the ROC Plot When Evaluating Binary Classifiers on Imbalanced Datasets, 2015.
- ROC Graphs: Notes and Practical Considerations for Data Mining Researchers, 2003.
API
- sklearn.metrics.roc_curve API
- sklearn.metrics.roc_auc_score API
- sklearn.metrics.precision_recall_curve API
- sklearn.metrics.auc API
- sklearn.metrics.average_precision_score API
- Precision-Recall, scikit-learn
- Precision, recall and F-measures, scikit-learn
Articles
- Receiver operating characteristic on Wikipedia
- Sensitivity and specificity on Wikipedia
- Precision and recall on Wikipedia
- Information retrieval on Wikipedia
- F1 score on Wikipedia
- ROC and precision-recall with imbalanced datasets, blog.
Summary
In this tutorial, you discovered ROC Curves, Precision-Recall Curves, and when to use each to interpret the prediction of probabilities for binary classification problems.
Specifically, you learned:
-.
Do you have any questions?
Ask your questions in the comments below and I will do my best to answer.
I don’t think a diagonal straight line is the right baseline for P/R curve. The baseline “dumb” classifier should be a straight line with precision=positive%
You’re right, thanks!
Fixed.
Thanks for the intro on the topic:
The following line raises questions:
>>> The scores do not look encouraging, given skilful models are generally above 0.5.
The baseline of a random model is n_positive/(n_positive+n_negative). Or just the fraction of positives, so it makes sense to compare auc of precision-recall curve to that.
Sorry, I don’t follow your question. Can you elaborate?
I’m sorry I was not clear enough above.
Here’s what I meant:
for ROC the auc of the random model is 0.5.
for PR curve the auc of the random model is n_positive/(n_positive+n_negative).
Perhaps it would make sense to highlight that the PR auc should be compared to n_positive/(n_positive+n_negative)?
In the first reading the phrase
>>> The scores do not look encouraging, given skilful models are generally above 0.5.
in the context of PR curve auc looked ambiguous.
Thank you!
Thanks.
I second Alexander on this, .
The random classifier in PR curve gives an AUPR of 0.1
The AUPR is better for imbalanced datasets because it shows that there is still room for improvement, while AUROC seems saturated.
A few comments on the precision-recall plots from your 10/2019 edit:
In your current precision-recall plot, the baseline is a diagonal straight line for no-skill, which does not seem to be right: the no-skill model either predicts only negatives (precision=0 (!), recall=0) or only positives (precision=fraction of positives in the dataset, recall=1).
The function precision_recall_curve() returns the point (precision=1,recall=0), but it shouldn’t in this case, because no positive predictions are made.
Also, the diagonal line is misleading, because precision_recall_curve() actually only returns two points, which are then connected. The points on the line cannot be achieved by the no-skill model.
Moreover, in my opinion the right precision-recall baseline to compare a model to is a random model resulting in a horizontal line with precision = fraction of positives in the dataset.
Thanks Theresa, I will investigate.
Great tutorial.
Thanks!
How about the Mathews Correlation Coefficient ?
I’ve not used it, got some refs?
This is a nice simple explanation
I have also been advised that in the field of horse racing ratings produced using ML if you already have probabilistic outputs, then it makes much more sense to use a metric directly on the probabilities themselves (eg: McFadden’s pseudo-R^2, Brier score, etc).
Thanks.
Do you not think that a model with no skill (which I assume means a random coin toss) should have an AUC of 0.5 and not 0.0?
A ROC AUC of 0.0 means that the model is perfectly in-correct.
A ROC AUC of 0.5 would be a naive model.
I do not know what you mean by a naive model. Going by what you’ve used to describe a model with no skill, it should have an AUC of 0.5 while a model that perfectly misclassifies every point will have an AUC of 0.
Perfectly misclassifying every point is just as hard as perfectly classifying every point.
A naive model is still right sometimes. The most common naive model always predicts the most common class, and such a model will have a minimum AUC of 0.5.
Excellent point, thanks!
Thanks for explaining the difference in simpler way.
I’m happy it helped.
there’s a typo here, should be “is”:
“A common way to compare models that predict probabilities for two-class problems us to use a
ROC curve.”
nice article 🙂 thanks for sharing!
Thanks, fixed!
Average precision is in fact just area under precision-recall curve. Very misleading that you “compared them”. Differences are due to different implementations in sklearn. Auc interpolates the precision recall curve linearly while the average precision uses a piecewise constant discritization
Thanks Tony.
I don’t believe we are comparing them, they are different measures.
“To make this clear:
Larger values on the x-axis of the plot indicate higher true positives and lower false negatives.
Smaller values on the y-axis of the plot indicate lower false positives and higher true negatives.”
Should swap x & y in this description of ROC curves??
You’re right, fixed. Thanks!
Hi, Thanks for the nice tutorial 🙂
I have one comment though.
you have written that ‘A model with no skill at each threshold is represented by a diagonal line from the bottom left of the plot to the top right and has an AUC of 0.0.’
I think AUC is the area under the curve of ROC. According to your Explantation (diagonal line from the bottom left of the plot to the top right) the area under the the diagonal line that passes through (0.5, 0.5) is 0.5 and not 0. Thus in this case AUC = 0. 5(?)
Maybe I misunderstood sth here.
You’re correct, fixed.
Hi Jason.
I went through your nice tutorial again and a question came to my mind.
Within sklearn, it is possible that we use the average precision score to evaluate the skill of the model (applied on highly imbalanced dataset) and perform cross validation. For some ML algorithms like Lightgbm we can not use such a metric for cross validation, instead there are other metrics such as binary logloss.
The question is that does binary logloss is a good metric as average precision score for such kind of imbalanced problems?
Yes, log loss (cross entropy) can be a good measure for imbalanced classes. It captures the difference in the predicted and actual probability distributions.
Hi Jason,
Thank you for a summary.
Your statement
“Generally, the use of ROC curves and precision-recall curves are as follows:
* ROC curves should be used when there are roughly equal numbers of observations for each class.
* Precision-Recall curves should be used when there is a moderate to large class imbalance.”
…is misleading, if not just wrong. Even articles you cite do not say that.
Usually it is advised to use PRC in addition to ROC for highly inbalanced datatsets, which means for dataset with ratio of positives to negatives less then 1:100 or so. Moreover, high ideas around PRC are aimed at having no negatives for high values of scores, only positives. It just might not be the goal of the study and classifier. Also, as mentioned in one of the articles you cite, AUROC can be misleading even for balanced datasets, as it “weights” equally true positives and true negatives. I would also mention that AUROC is an estimator of the “probability that a classifier will rank a randomly chosen positive instance higher than a randomly chosen negative one” and that it is related to Mann–Whitney U test.
To sum it up, I would always recommend to
1) Use AUROC, AUPRC, accuracy and any other metrics which are relevant to the goals of the study
2) Plot distributions of positives and negatives and analyse it
Let me know what you think
Thanks for the note.
Hi Jason,
in these examples, you always use APIs, so all of them have calculated functions. But I dont understand how to use the equations, for example:
True Positive Rate = True Positives / (True Positives + False Negatives)
this ‘True Positives’ are all single float numbers, then how we have array to plot?
(True Positives + False Negatives): is sum of total final predicted of test data?
I really confuse when calculate by hand
They are counts, e.g. the number of examples that were true positives, etc.
Can you please explain how to plot roc curve for multilabel classification.
Generally, ROC Curves are not used for multi-label classification, as far as I know.
Hi Jason,
I’ve plotted ROC which you can see in the following link but I don’t know why it’s not like a real ROC.
Could you please check oy out and let me what could be my mistake?
hist = model.fit(x_train, y_train, batch_size= 10, epochs= 10, verbose= 2)
y_predic = model.predict(x_test)
y_predic = (y_predic> 0.5)
fpr, tpr, thresholds = metrics.roc_curve(y_test, y_predic)
plt.figure()
plt.plot([0, 1], [0, 1], ‘k–‘)
plt.plot(fpr, tpr)
plt.xlabel(‘False positive rate’, fontsize = 16)
plt.ylabel(‘True positive rate’, fontsize = 16)
plt.title(‘ROC curve’, fontsize = 16)
plt.legend(loc=’best’, fontsize = 14)
plt.show()
I’m happy to answer questions, but I don’t have the capacity to debug your code sorry.
Thanks a lot for your reply.
No, I meant if it’s possible please check the plot and let me know your idea about it.
Hi Jason,
sorry, there’s a little confusing here,
we generate 2 classes dataset, why we use n_neighbors=3?
appreciate your help.
Alex
Yes, 2 classes is unrelated to the number of samples (k=3) used in kNN.
A dataset is comprised of many examples or rows of data, some will belong to class 0 and some to class 1. We will look at 3 sample in kNN to choose the class of a new example.
Hi, Jason, on top of this part of the code, you mentioned that “A complete example of calculating the ROC curve and AUC for a logistic regression model on a small test problem is listed below”. Is the KNN considered a “logistic regression”? I’m a little confused.
Looks like a typo. Fixed. Thanks!
Hi Jason, thank you for your excellent tutorials!
Is it EXACTLY the same to judge a model by PR-AUC vs F1-score? since both metrics rely exclusively on Precision and Recall? or am I missing something here?
thanks!
I don’t think so, off the cuff.
Nice post — what inferences may we make for a particular segment of a PR curve that is monotonically increasing (i.e. as recall increases, precision increases) vs another segment where the PR curve is monotonically decreasing (i.e. as recall increases, precision decreases)?
In the PR curve, it should be decreasing, never increasing – it will always have the same general shape downward.
If not, it might be a case of poorly calibrated predictions/model or highly imbalance data (e.g. like in the tutorial) resulting in an artefact in the precision/recall relationship.
I have been thinking about the same, the first answer here has a simple demonstration of why the y-axis (precision) is not monotonically decreasing while x-axis(recall) is monotonically increasing while threshold decreases, because at each threshold step, either the numerator or denominator may grow for precision, but only the numerator may grow for recall.
Thanks for sharing.
I think that’s VERY wrong. 🙁
Hi Jason,
great stuff as usual. Just a small thing but may cause slight confusion, in the code for all precision-recall curves the comment indicates a ROC curve.
# plot the roc curve for the model
pyplot.plot(recall, precision, marker=’.’)
Regards
Gerry
Thanks, fixed!
Hi Jason,
Thanks for the article! You always wrote articles I have trouble finding answers anywhere else. This is an awesome summary! A quick question – when you used ‘smog system’ as an example to describe FP vs. FN cost, did you mean we will be more concerns about HIGH FN than HIGH FP? Correct me if I did not get what you meant.
Regards,
Sunny
Thanks.
Yes, it might be confusing. I was saying we want (are concerned with) low false neg, not false pos.
High false neg is a problem, high false pos is less of a problem.
Hi Jason,
How do we decide on what is a good operating point for precision% and recall %? I know it depends on the use case, but can you give your thoughts on how to approach it?
Thanks!
Yes, establish a baseline score with a naive method, and compare more sophisticated methods to the baseline.
Great post. Thank you Jason.
One query. what is the difference between area under the PR curve and the average precision score? Both have similar definitions I guess.
Also what approach do you recommend for selecting a threshold from the precision-recall curve, like the way we can use Youden’s index for ROC curve?
I’d recommend looking at the curve for your model and choose a point where the trade off makes sense for your domain/stakeholders.
Great question. They are similar.
I can’t give a good answer off the cuff, I’d have to write about about it and go through worked examples.
I am guessing both average precision score and area under precision recall curve are same. The difference arises in the way these metrics are calculated. As per the documentation page for AUC, it says
“Compute Area Under the Curve (AUC) using the trapezoidal rule
This is a general function, given points on a curve. For computing the area under the ROC-curve, see roc_auc_score. For an alternative way to summarize a precision-recall curve, see average_precision_score.”
So i guess, it finds the area under any curve using trapezoidal rule which is not the case with average_precision_score.
Thanks for the nice and clear post 🙂
Shouldn’t it be “false negatives” instead of “false positives” in the following phrase:
“here is a tension between these options, the same with true negative and false positives.”
I think you’re right. Fixed.
Thanks for the nice and clear article.
i used GaussianNB model, i got the thresholds [2.00000e+000, 1.00000e+000, 1.00000e+000, 9.59632e-018 ].
is it noraml that the thresholds have very small value??
thanx in advance
This line makes no sense to me at all : “Indeed, it has skill, but much of that skill is measured as making correct false negative predictions”
What is a “correct false negative”? The “correct” to my current understanding consist TP and TN, not FP or FN. If it’s correct, why is it false? If it’s false, how can it be correct?
Could you explain correct according to what? y_true or something else?
Looks like a typo, I believe I wanted to talk about true negatives, e.g. the abundant class.
Fixed. Thanks.
Great post, I found this very intuitive.
But why keep probabilities for the positive outcome only for the precision_recall_curve?
I tried with the probabilities for the negative class and the plot was weird. Please, I will like you to explain the intuition behind using the probabilities for the positive outcome and not the one for the negative outcome?
Actually scikit learn “predict_proba()” predict probability for each class for a row and it sums upto 1. In binary classification case, it predicts the probability for an example to be negative and positive and 2nd column shows how much probability of an example belongs to positive class.
When we pass only positive probability, ROC evaluate on different thresholds and check if given probability > threshold (say 0.5), it belongs to positive class otherwise it belongs to negative class. Similarly, it evaluates on different thresholds and give roc_auc score.
Thanks for explaining the ROC curve, i would like to aske how i can compare the Roc curves of many algorithms means SVM knn, RandomForest and so on.
Typically they are all plotted together.
You can also compare the Area under the ROC Curve for each algorithm.
can anyone explain whats the significance of average precision score?
Yes, see this:
Thanks a lot for this tutourial. There are actually not a lot of resources like this.
Thanks, I’m glad it helped!
Hi Jason,
thank you for your tutorial!
I have a question about the F1 score, because i know the best value is 1 (perfect precision and recall) and worst value is 0, but i’m wondering if there is a minimun standard value.
I’m obtaining a F score of 0.44, because i have high false positives, but a few false negatives. But i don’t know if 0.44 is enough to say that i have a good model. Do you know is there is a standard in the literature? for example in ROC about 0.75 is good
Thanks
Yes, the F1 score returned from a naive classification model:
Hi Jason,
Thanks for the explaining these concepts in simple words!
I have a little confusion. You mentioned Roc would be a better choice if we have a balanced dataset, and precision-recall for an imbalanced dataset. But if we get an imbalanced dataset, will we not try to balance it out first and then start with the models?
Regards,
Bishal Mandal
We may decide to balance the training set, but not the test set used as the basis for making predictions.
i was thinking about this whole day 🙂 .Thanks
HI.could you tell me whether i can create roc curve in this way or not ?
y_test=my test data ground truth (6500,1)
x_test= my test data (6500,3001)
prediction=model.predict(x_test)
fpr,tpr,thresholds=roc_curve(y_test,prediction)
plt.plot(fpr,tpr)
plt.show()
auc = roc_auc_score(y_test, prediction)
I can’t debug your example sorry.
Perhaps try it?
Thanks,it’s solved.
Happy to hear that.
Sorry i have another question .when i saw the thresholds array elements , i noticed that its first element is about 1.996 . How is it possible ? thresholds should be between 0 and 1 , isn’t it ?
Thanks again
Also i check it in your code , and it is the same , you’re first element of thresholds is 2 !
Could yo tell me how the number of thresholds elements are obtained ? for example in your code you have thresholds have 5 elements but in my problem it has 1842 element
Perhaps double check the value?
I suggest carefully rereading Aleks post and considering rephrasing your statement about the ROC is just for balanced data at the end, which it isn’t. The PlosONE papers title is misleading. It is true ROC in cases of N >> P can give a high AUC, but many false positives, and PR curve is more sensitive to that. But it all depends on your objectives and I refer you to the papers of David Powers to read about the many preferable statistical properties of the ROC to the PROC., he has written an excellent straightforward summary here which could be used to improve this blog post.
Great blog btw.
Thanks Chris, I’ll take another run at the paper.
my precision and recall curve goes up to the end but at the end it crashs. do you know why and is this ok? thanks.
Sorry to hear it crashes, why error does it give?
Many thanks Jason for this tutorial
I would like to ask about the ROC Curves and Precision-Recall Curves for deep multi-label Classification.
I was able to plot the confusion matrices for all the labels with sklearn.matrics (multilabel_confusion_matrix).. My question is, How can I plot the ROC Curves and Precision-Recall Curves for all the labels?
I appreciate any help.
Thanks a lot.
Generally PR Curves and ROC Curves are for 2-class problems only.
Thanks a lot Jason for your reply.
so what are the evaluation matrices for multi-label classification?
Just the ACC and Loss?
It depends on what is important for your problem.
Log loss is a good place to start for multiclass. For multilabel (something else entirely), average precision or F1 is good.
My best advice is to go back to stakeholders or domain experts, figure out what is the most important about the model, then choose a metric that captures that. You can get a good feeling for this by taking a few standard measures and running mock predictions through it to see what scores it gives and whether it tells a good story for you/stakeholders.
Great!
Many thanks Jason.
You’re welcome.
Hello sir , thank you for your excellent tutorials!
i am facing a problem when ever i show the roc curve i get the following error
File “C:\Program Files\Python37\lib\site-packages\sklearn\metrics\base.py”, line 73, in _average_binary_score raise ValueError(“{0} format is not supported”.format(y_type))
ValueError: multiclass format is not supported
sir please help me to solve this issue. Thanks
ROC Curves can only be used for binary (2 class) classification problems.
It was very useful. Thanks for helping beginners like us with an apt explanation
I’m happy to hear that.
Hi Jason,
I am dealing with a medical database for prediction of extreme rare event (0.6% chance of occurrence). I have 10 distinct features, 28,597 samples from class 0 and 186 from class 1.
I have developed several models. Also, I have tried to downsample the training set to make a balanced training set and tested on imbalanced test set.
Unfortunately regardless of my model the PR curve is similar to “Precision-Recall Plot for a No Skill Classifier and a Logistic Regression Model for am Imbalanced Dataset” figure in this post.
Any idea how can I deal with this database? I would appreciate any suggestion!
Yes, some ideas:
– try standard models with a range of data scaling
– try class weighted versions of models like logistic regression, svm, etc.
– try undersampling methods
– try over sampling methods
– try combinations of over and under sampling on the same training set
– try one class classifiers
– try ensemble methods designed for imbalanced data
– try an alternate performance metric
– try k-fold cross validation to estimate pr auc
I hope that helps as a start.
Thanks a lot. I already started to use your suggestions. Wish me luck and patience 😀
Good luck!
I have the same problem in the data I am dealing with (around 0.3% occurrence).
I assume you have some expert knowledge about the biological connections between the features and your event, but try calculating the Pearson (point biserial) correlation of each feature with the target, this should give you a hint whether there is any connection between your features and the event you want to predict.
You could also try unsupervised learning (clustering) to see if the event is only located within certain clusters.
Validating with ROC can be a bit tricky in the case that not enough positive events end up in the validation data set.
Though this is a bit cheaty because you would make assumptions about the validation data beforehand, split the negative and positive cases seperately so that you end up with the same prevalence in training and validation data.
Great tips.
A LOOCV evaluation is a good approach with limited data.
Thanks for the tips. I am considering them.
Hello Jason,
great article.
I stumbled upon the PLoS One paper (Saito and Rehmsmeier 2015) myself and I have one question regarding the evaluation of the PRC.
The authors state:
“Nonetheless, care must be taken when interpolations between points are performed, since the interpolation methods for PRC and ROC curves differ—ROC analysis uses linear and PRC analysis uses non-linear interpolation. Interpolation between two points A and B in PRC space can be represented as a function y = (TPA + x) / {TPA + x + FPA + ((FPB – FPA) * x) / (TPB – TPA)} where x can be any value between TPA and TPB [26].”
In your article, you calculated the AUC (PRC) with the sklearn auc(recall, precision).
Is this in conflict with the quoted statement since I would also calculate the ROC AUC with auc(FPR, TPR)?
I don’t think this matters much when I am comparing models within my own trial, but what about comparing the AUC to other papers?
Hmmm. Yes, you may be right.
Here comes a rant.
As a general rule, repeat an an experiment and compare locally.
Comparing results to those in papers is next to useless as it is almost always the case that it is insufficiently described – which in turn is basically fraud. I’m not impressed with the computational sciences.
how to calculate the probabilities that i need to pass for below funciton
roc_curve(y, probs)
You can call model.predict_proba() to predict probabilities.
Can I ask why you said that in the case of precision -recall we’re less interested in high true negative? Is it because you took class 0 to be the dominant class? But isn’t the choice of class 0 as being the dominant class just an example? So, in the case of class 1 being the dominant class, that would mean that the model will be less interested in true positives. And in this case your point about true negatives not figuring in the precision and recall formulas wouldn’t be relevant.
In binary classification, class 0 is the negative/majority class and class 1 is always the positive/minority class. This is convention.
Hi,
Is there any formula to determine the optimal threshold from an ROC Curve ?
Thanks
Surajit
Yes, I have a post scheduled on the topic.
You can use the j-statistic:
Thanks for your reply. How shall i come to know about your post on this topic ?
You can follow the site via email/rss/twitter/facebook/linkedin.
See the links at the bottom of every page.
Also, how to determine the optimal threshold from a PR Curve ? Is it the F-Score or something else ?
Excellent question!
You can test each threshold in the curve using the f-measure.
I cover this in an upcoming post as well.
Why f-measure over other metrics
Good question, see this framework for choosing a metric:
Hey there!
You obtain the thresholds as “_” through the call “lr_precision, lr_recall, _ = precision_recall_curve(testy, lr_probs)” – but you never use them when plotting the curve, am I right? How are you using the thresholds? I mean, you have to be using them in some way for the plot?
Correct, we are not using the thresholds directly, rather a line plot of recall vs precision.
well, does it then mean for roughly balanced dataset I can safely ignore Precision Recall curve score and for moderately (or largely) imbalances dataset, I can safely ignore AUC ROC curve score?
No, you must select the metric that is most appropriate for your task, then use it to evaluate and choose a model.
Metric first.
thank you, I was talking about specifically binary classification task. And I have two datasets. one is imbalanced (1:2.7) and the second one is almost perfectly balanced. which metric should I choose for the two? Thank you once again, cheers!
I recommend choosing a metric that best captures the requirements of the project for you and the stakeholders.
A good starting point is to think about what is important about classification and misclassification errors. Are errors symmetrical? Are both classes important, etc.
Some metrics to consider include roc auc, pr auc, gmean, f-measure and more.
you’re awesome, thank you
You’re welcome.
Hi, Thanks for your excellent post.
My question is if I do resampling to my imbalance dataset, can I use AUC in this case to evaluate the model?
Yes.
Sorry I meant can I use the ROC curves to evaluate the model in this case?
Yes. Any metric you want.
Sampling only impacts the training set, not the test set used for evaluation.
Hi, Jasono, you explain in a way that I always write ‘machinelearningmastery’ in the end of my query at the end. Thanks
My probllem is: I have imbalance dataset of (22:1, positive:negative) and I train the neural network model with the ‘sigmoid’ as a activation function in last (output) layer. After training I call the function ‘model.predict’ as below:
y_prediction = model.predict(X_test)
and when I print y_prediction it shows me float values between 1 and 0 (I am thinking that these are the probabilities of class 1(positive) for every X_test sample).
After that I convert y_prediction to 1s and 0s by threshold of 0.5 as blow:
y_pred = np.zeros_like(y_prediction)
y_idx = [y_prediction >= 0.5]
y_pred[y_idx] = 1
After that I draw Precision-Recall Curve (PR-Curve), which bows towards (1,1).
Now I have following Questions:
Q1: How I have to get the best threshold from my PR-curve, that I apply this threshold to y_prediction(mentioned above) and results me in good recall and precision.
Q2: How I became satisfied that this precision and recall or F1-score are good and model perform well.
Thanks
Thanks!
You can test all thresholds using the F-measure, and use the threshold with the highest F-measure score. I have a tutorial on this scheduled.
Not sure I understand the second question. Use lots of data and repeated evaluation to ensure the score is robust?
How to plot ROC when I have a predicted output as a reconstructed image (e.g. Autoencoder), suppose I calculate some score of reconstructed an consider as a binary classification. I have tried using scikit-learn package and the result is almost the same with my training experiment.
my model structure:
Image sequence as Input -> Encoder -> ConvLSTM -> Decoder -> output a reconstructed image sequence
Not sure that is possible.
Sir how i can draw the ROC Curve by using PROMISE DATASET KC1, Kindly help.
A ROC curve is drawn for predictions, not for a dataset.
First model the dataset, then make predictions on a test set, then use the code above to draw a ROC curve from the predictions.
great
Thanks!
Hi Jason Brownlee,
First, I regret the loooong question, below. Having said that….;o)
…I cannot escape the fact that you represent a significant capacity in the field of data science and that you show an impressive willingness to share your valuable knowledge with others. In light of that, I hope that you could possible assist me providing some advice. I have two questions.
I am currently in the process of defining a KNN based classification of a relatively imbalanced, some might say highly imbalanced dataset, consisting of 2K+ articles of various scientific content. Purpose of algo is to clarify which articles to scrap and, more interestingly, which ones to proceed with. These ones are highly outnumbered by the ones not of interest. I’ve managed to make the algo run, and it does a pretty fine job. I think. This is where I’d like you to tell me, after having pre-processed text, vectorized, how I can evaluate on the KNN model’s performance. Reading your article, I seem to understand that precision-recall curves are better at showing results when working with (highly?) imbalanced datasets.
Therefore, and first:
Do I need to do a confusion matrix before a precision-recall curve, and do both these exist as standard components of the scikit-learn module?
Second, I seem to face an issue when executing on the KNN classification part of the algo. I am importing a csv, adding a unique id to each line/text representation, and then–when testing relationship of a new observation–I am adding a number from the list of unique id’s I added. Then–in presenting result–I concatenate to df’s and get an overview of e.g. 20 nearest neighbors. Could be 10 or whatever. This works fine. It points back to a list where I can see that my preferred articles are highlighted, typically at rate of precision betw 75 and 80 per cent. My issue is really that I’d like to be able to add a piece of text/search word in stead of a number. From the tutorial I ‘inherited’ my own adaptation, it says ‘Barack Obama’s nearest neighbors are this and that, but that is only because the data applied i structured in a ‘name’ and ‘text’ feature. My articles cannot be split like that. While overall covering the same scientific area, they are different, very different. So my question is: Is it possible to add a new feature/column, index by that new one and then use text as search criteria when attempting to add input the ‘get_closest_neighs’ result?
Thanks.
Start with a good idea of what is important to the project, then find a metric that matches that.
This will help a lot, specifically the end:
Not sure I follow your second question sorry. It might be more of an engineering question than a modeling question.
Hi, this is the tutorial I used, re question 2 –
You mentioned “This is possible because the model predicts probabilities and is uncertain about some cases. These get exposed through the different thresholds evaluated in the construction of the curve, flipping some class 0 to class 1, offering some precision but very low recall.”
Shouldn’t this offer some recall but very low precision as depicted by the graph?
Very illuminating!
Thanks!
Dear Sir,
I am using the Ant Miner based on the Ant colony optimization algorithm for my dataset. I don’t know how to take the threshold value and predict_value in that algorithm. It is not like the classifier using here. Can you guide me on how to use that value to plot the ROC curve? If you want the code I can mail you, So, that you can see it.
Sorry, I don’t have the capacity to debug your code.
I am not familiar with the software you are using, perhaps contact the authors directly?
Hey, maybe you or someone can help me with understanding ROC AUC. When would I use it to assess model performance instead of accuracy? I am especially asking in the context where you say that one should not use ROC in the case of imbalanced data. You say that while the ROC curve shows a useful model for most thresholds, your model only predicts the big class. With predictions you mean with threshold 0.5? And with model skill in this: “might be deceptive and lead to incorrect interpretations of the model skill” you mean how good a model does its predictions with all samples weighted equally? But with threshold 0.5 and weighting all samples equally we would be back at simple accuracy measure no? Is ROC AUC not meant to check whether the model was able to separate two classes? That would be independent of the class distributions, no?
This can help you choose what metric to use:
Hi Jason,
Lets say we build a classification model using logistic regression and there is a huge imbalance in the data( to find out credit default) . Now the model has given the confusion matrix with (sensitivity/recall/TP/TN etc..) . Since the model threshold is by default 0.5, the TP rate is less.
Now my understanding.
1) We go to ROC AUC curve just to find the threshold probability
2) come back to the initial model built , to classify as per the new threshold ( by getting the predicted probabilities and classify accordingly with threshold)
If the above understanding is correct, what does AUC signifies ? How can it be an alternate metric to precision/recall? At the end of the day i still have to go back to my initial model built and change the thresholds right and still draw a confusion matrix right?
kindly advise.
Nearly.
We can use the ROC Curve to find a threshold to tune a metric.
We can use ROC AUC metric to evaluate the model directly, not related to threshold or a confusion matrix.
ROC AUC is the area under the curve.
Hi Jason,
Thanks for the post.
One question. You got threshold value but how you gonna use it? I mean you will fit your model again and set threshold value for example in “Earlystopping” function?
I am asking because I couldn’t find anywhere how to use the threshold value. I mean what will you when you want to save adjusted improved model?
Thanks.
You’re welcome.
Good question, see this on selecting a threshold and using it to turn probabilities into crisp labels:
Hello,
How would one go about comparing two AUC’s given by y the AUROC & AUPRC curves in python? AKA is there a statistical difference between two AUC’S produced by two different but correlated models?
let me clarify a little…
I have the following “values”
Model 1 (49 items)
Logistic Regression AUROC
Logistic Regression AUPRC
Random forest AUROC
Random forest AUPRC
Gradient Boosting AUROC
Gradient Boosting AUPRC
Model 1 (51 items)
Logistic Regression AUROC
Logistic Regression AUPRC
Random forest AUROC
Random forest AUPRC
Gradient Boosting AUROC
Gradient Boosting AUPRC
I want to compare the corresponding AUROC/AUPRC values between models 1 and 2 in python to see if there is a significant difference between the predictive validity in the models…but unsure how to go about running this test, are you aware of any package in python that would allow me to do so?
If both treatments were applied to the same data, you could use a paired test.
You can calculate a ROC AUC for each method and compare them directly.
Hi Jason,
thanks a lot for your excellent tutorial!
I work in a research lab and I need to start using Python to calculate the EC50 and AUC on ELISA assay data tables (a dose-response curve on serial dilutions of samples), and I would like to ask you if you have experience doing similar things with Python or help me find useful resources. Of course EC50 and AUC can be easily calculated with Prism, but I also need to know how to do it with Python. I know how to plot data tables in Python, but I am at a loss when it comes to proceed with transform, normalization and linear regression, and after that calculate the final AUC of the ELISA assay.
Any help would be greatly appreciated.
Thanks,
Alex
You’re welcome!
The above tutorial will show you how to plot a ROC curve and calculate ROC AUC.
For help normalizing data, see this:
For help with linear regression, see this:
I don’t know what EC50 is, sorry.
I hope that helps as a starting point.
Dear Jason,
would you please tell me a short answer for the question below?
Is it possible to get the AUC = 1 for the Sensitivity = 1.0, Specificity = 0.556, PPV= 0.818, NPV = 1.0 ?
Thank you,
I would suggest no.
Wouldn’t a “no skill classifier that only predicts 0 for all examples” result in just a single point on the ROC curve at (0, 0), not an AUC of 0.5? To get an AUC of 0.5, wouldn’t you have to look at all models which predict class 1 with probability p in [0, 1], resulting in a set of points {(p, p)}, which together form the diagonal line?
The example plots this exact case as a diagonal line, you can see for yourself if you are unsure.
Thanks for your response. I do see the diagonal line, but I don’t think the entire line corresponds to predicting 0 for all examples, which is what is written in the text. Predicting 0 for all examples is just one point on the line (the point at (0, 0)). The no skill line is created by a set of classifiers which predict class 1 with probabilities ranging from 0 to 1. For example, the point at (0.25, 0.25) is created by predicting class 1 25% of the time. This holds regardless of class imbalance. Does that make sense?
Agreed.
You can predict random labels to get a more appropriate line.,
Choosing just recall or just precision is not a good idea, they need balance. Use fbeta instead:
Thank you, and sorry, I accidentally posted the same question again. Will go through the article you sent.
Thank you,
Karthik
No problem.
Hello, great job on the article!
If I’m trying to create a model where I’m interested in higher recall, how can I tune my model to achieve that? With a KNN Classifier, what parameters can I change to influence recall?
Thank you very much!
Good question, select a metric like “recall” or “f1” and test a suite of models and model configuration to see which achieves the best result with your chosen metric.
This will help you choose a metric:,
Good is relative to the goals of your project or requirements of your project stakeholders. There is no objectively “good” model.
I would recommend optimizing an F-beta metric instead of just recall because you want the best recall and precision, not just recall:
Model performance is estimated using repeated k-fold cross validation:
What a great article – thanks so much, Jason! I did have a qq: I do finally understand, thanks to you, how AUC can be misleading in terms of how much better our model is than chance (when the dataset is unbalanced), but does this matter when you are choosing from several models? Wouldn’t AUC still pick the best one?
Thanks again – awesome how you reference papers and actually interpret how they add context to your article!
Thanks!
Good question. Yes, choosing the model with the better AUC will have a relatively good “AUC” score by definition, it just may not be good when considering other metrics.
LOL, I realize I didn’t state that very well! I guess I meant would the rankings of the models be the same as if I used AUPR? Thanks for the quick response – really appreciate your work.
Maybe, but probably not, choosing an appropriate metric is critical, more here:
Thank you for your article.
Dear Jason, is there any way (in python) to investigate the predictive power of each feature in our dataset using ROC AUC?
ROC AUC is a score for binary classification. Not sure how it is related to feature importance exactly.
Perhaps start here:
Hey Jason, thanks for the awesome tutorials.
I just want to report a possible typo in your text. In the sentence:
“…thresholds using the precision_recall_curve() function that takes the true output values and the probabilities for the positive class as output and returns…”
shouldn’t it be “input” instead of “output”?
Cheers
Dário
You’re welcome.
Thanks, fixed!
Hello, please how these two numbers in brackets stand for :
a probability in [0.0, 0.49] is a negative outcome (0)
and a probability in [0.5, 1.0] is a positive outcome (1).
You can use an if-statement directly.
Hello Jason…
I made a classification using Random Tree in Weka, and I exported the predicted instances of the testing dataset please what is the numbers in the column “Prediction” stand for, since it is Random Tree, not logistic regression to produce probabilities:
inst# actual, predicted ,error , prediction
1 2 2 0.933
2 1 2 + 0.58
3 2 2 0.828
4 2 2 0.667
The predictions are the probability of class=1, I would guess.
thank you very much
Hello again. thanks for the great explanations. I want to ask about creating ROC for the
Decision Tree in weka.
Is there a meaning of choosing a cut-off to choose the best threshold point?
since with Decision Tree, we can’t change the assignment, and there’s no such thing as
threshold in Decision Trees. or only we can calculate the AUC for decision tree without a cut-off?
Sorry, I don’t have an example of choosing the threshold in Weka.
I have an example in Python here:
thank you very much ( : , so helpful ..
You’re welcome.
Hello Dear Jason
My dataset contains attack and normal data. How can I use logistic regression to do this? Do I have to bet on attack data?
This process will help you work through your project:
I got a multiclass (5-classes) highly imbalanced dataset. Can I use ROC curve as evaluation metrics?
Typically ROC curves are used for 2-class (binary) classification, not multi-class.
Hi Jason, Thanks for the great tutorial as always.
I have an imbalanced dataset where the test set has positive class as the dominant class. The PR curve should be used when the negative class is dominant right? So, what should I use in this case?
Class=1 should be the minority class, if not you may have to specify which is positive and which is negative to the metric.
Pls how can roc be plotted for a multiclass classification problem?
It cannot.
Hi, Thanks for your excellent post.
I am just wondering how to choose a threshold in Precision-Recall curve, although it’s plotted over all the possible thresholds and how can I define the exact threshold value for a specific point in the curve.
Thanks in advance.
You’re welcome.
Good question, see this tutorial:
Is there a python code where precision-recall curves are obtained from multi-classification ANNs (more than 2 classes)? Thank you.
Not that I’m aware.
with predict prob you only plot the 2nd columns with positive class probability. But if column2 values are less than column1 values for certain examples then that means that those examples belonged to class 0 and not 1. But we still end up plotting column 2 where they never belonged to class 1. So these will not be a part of the TPR?
Hi Jason,
Thanks so much for your excellent posts and blogs. Really informative indeed. I am still struggling on the no skill model for the PR curve, and why is that a straight line. Please see below:
1- a random model, coin toss, would simply predict a precision equal to the ratio of positive class in the data set, and recall =0.5 (middle of the dotted flat line/no skill classifier)
2- a model, which predicts 1, for all the data points, would simply predict precision equal to the ratio of positive class in the data set, and recall = 1 (end of the dotted flat line)
3- a model, which predicts 0 (negative class), for all the data posits, would predict an undefined precision (denominator =0) and recall of 0. (this is not on the dotted flat line…?)
Also, I really don’t get, how an unskilled model can predict a recall of lets say 0.75 and precision equal to the TP ratio. It seems like to me that not all the points in the no-skill model can be ached, and no skill model should be limited number of points , rather than a whole flat line…?
3-
On a ROC curve, the no sill is not really a line, it is a point or two points, we construct a line as reference.
Hi Mr Jason,
Please, I have two questions:
1- why ROC AUC results are reduced with normalization?
2- could you explain this situation: even the model accuracy in SVM or GNB is good -about 90%- but the AUC value is small about 50% even without normalization?
regards
sorry, question two just with SVM
Normalization of input data can help with models that weight inputs or use distance measures.
I recommend not comparing different types of metrics, instead, select one metric and optimize it.
yes, that’s right but GNB has no parameters to be tuned only normalization could affect the result. Moreover, if ACC is high that’s mean all other metrics are high, so how AUC is reduced while it depends on recall and FPR. I can’t imagine the idea.
Hi Jason,
For the roc_curve function, is it correct to pass scores as probability density or probability?
Yes, as long as the value is a measure of decisions.
Hi
I am trying to plot a ROC curve to evaluate the accuracy of a prediction model I developed in Python using AdaBoostclassifier packages.
probs = model.predict_proba(X_test)
preds = probs[:,1]
fpr, tpr, threshold = metrics.roc_curve(y_test, preds)
roc_auc = metrics.auc(fpr, tpr)
# method I: plt
import matplotlib.pyplot as plt
plt.title(‘Receiver Operating Characteristic’)
plt.plot(fpr, tpr, ‘b’, label = ‘AUC = %0.2f’ % roc_auc)
plt.legend(loc = ‘lower right’)
plt.plot([0, 1], [0, 1],’r–‘)
plt.xlim([0, 1])
plt.ylim([0, 1])
plt.ylabel(‘True Positive Rate’)
plt.xlabel(‘False Positive Rate’)
plt.show()
I run this code bute i have this “ValueError: multiclass format is not supported”
The error says it all. ROC curve is for prediction accuracy, i.e., binary classification. The formula cannot apply to non-binary case.
Hi,
I am having trouble to find out PRC curve and its AUC for a multiclass (no of classes=4) classification problem:
from sklearn.multiclass import OneVsRestClassifier
from xgboost import XGBClassifier
from sklearn.metrics import precision_recall_curve
from sklearn.metrics import average_precision_score
clf = OneVsRestClassifier(XGBClassifier(n_estimators=50, max_depth=3, random_state=0))
clf.fit(X_train, Y_train)
Y_score = clf.predict_proba(X_test)
# precision recall curve
n_classes=4
precision = dict()
recall = dict()
for i in range(n_classes):
precision[i], recall[i], _ = precision_recall_curve(Y_test[:, i], Y_score[:, i])
plt.plot(recall[i], precision[i], lw=2, label=’class {}’.format(i))
plt.xlabel(“recall”)
plt.ylabel(“precision”)
plt.legend(loc=”best”)
plt.title(“precision vs. recall curve”)
plt.show()
It gives me an error saying
IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed
Could you please share a working code for multiclass so that I can understand my mistake.
Hi Jason,
thanks for your tutorial! Very explanatory!
In the last sentence:
“These get exposed through the different thresholds evaluated in the construction of the curve, flipping some class 0 to class 1, offering some precision but very low recall.”
Shouldn’t it be the other way around: “offering some recall but very low precision.” ?
Thanks,
Abel
Precision and recall are both about positive predictions. Which class is considered positive is the question of how you write this sentence.
|
https://machinelearningmastery.com/roc-curves-and-precision-recall-curves-for-classification-in-python/
|
CC-MAIN-2021-49
|
refinedweb
| 11,413
| 64.41
|
2020/09/20: We released
torchsparsev1.1, which is significantly faster than our
torchsparsev1.0 and is also achieves 1.9x speedup over MinkowskiEngine v0.5 alpha when running MinkUNet18C!
2020/08/30: We released
torchsparsev1.0.
We release
torchsparse, a high-performance computing library for efficient 3D sparse convolution. This library aims at accelerating sparse computation in 3D, in particular the Sparse Convolution operation.
The major advantage of this library is that we support all computation on the GPU, especially the kernel map construction (which is done on the CPU in latest MinkowskiEngine V0.4.3).
You may run the following command to install torchsparse.
pip install --upgrade git+
Note that this library depends on Google's sparse hash map project. In order to install this library, you may run
sudo apt-get install libsparsehash-dev
on Ubuntu servers. If you are not sudo, please clone Google's codebase, compile it and install locally. Finally, add the path to this library to your
CPLUS_INCLUDE_PATHenvironmental variable.
For GPU server users, we currently support PyTorch 1.6.0 + CUDA 10.2 + CUDNN 7.6.2. For CPU users, we support PyTorch 1.6.0 (CPU version), MKLDNN backend is optional.
Our SPVNAS project (ECCV2020) is built with torchsparse. You may navigate to this project and follow the instructions in that codebase to play around.
Here, we also provide a walk-through on some important concepts in torchsparse.
In torchsparse, we have two data structures for point cloud storage, namely
torchsparse.SparseTensorand
torchsparse.PointTensor. Both structures has two data fields
C(coordinates) and
F(features). In
SparseTensor, we assume that all coordinates are integer and do not duplicate. However, in
PointTensor, all coordinates are floating-point and can duplicate.
The way to convert a point cloud to
SparseTensorso that it can be consumed by networks built with Sparse Convolution or Sparse Point-Voxel Convolution is to use the function
torchsparse.utils.sparse_quantize. An example is given here:
inds, labels, inverse_map = sparse_quantize(pc, feat, labels, return_index=True, return_invs=True)
where
pc,
feat,
labelscorresponds to point cloud (coordinates, should be integer), feature and ground-truth. The
indsdenotes unique indices in the point cloud coordinates, and
inverse_mapdenotes the unique index each point is corresponding to. The
inverse mapis used to restore full point cloud prediction from downsampled prediction.
To combine a list of
SparseTensors to a batch, you may want to use the
torchsparse.utils.sparse_collate_fnfunction.
Detailed results are given in SemanticKITTI dataset preprocessing code in our SPVNAS project.
The computation interface in torchsparse is straightforward and very similar to original PyTorch. An example here defines a basic convolution block:
class BasicConvolutionBlock(nn.Module): def __init__(self, inc, outc, ks=3, stride=1, dilation=1): super().__init__() self.net = nn.Sequential( spnn.Conv3d(inc, outc, kernel_size=ks, dilation=dilation, stride=stride), spnn.BatchNorm(outc), spnn.ReLU(True) )
def forward(self, x): out = self.net(x) return out
where
spnndenotes
torchsparse.nn, and
spnn.Conv3dmeans 3D sparse convolution operation,
spnn.BatchNormand
spnn.ReLUdenotes 3D sparse tensor batchnorm and activations, respectively. We also support direct convolution kernel call via
torchsparse.nn.functional, for example:
outputs = torchsparse.nn.functional.conv3d(inputs, kernel, stride=1, dilation=1, transpose=False)
where we need to define
inputs(SparseTensor),
kernel(of shape k^3 x OC x IC when k > 1, or OC x IC when k = 1, where k denotes the kernel size and IC, OC means input / output channels). The
outputsis still a SparseTensor.
Detailed examples are given in here, where we use the
torchsparse.nn.functionalinterfaces to implement weight-shared 3D-NAS modules.
Sparse hash map query is important in 3D sparse computation. It is mainly used to infer a point's memory location (i.e. index) given its coordinates. For example, we use this operation in kernel map construction part of 3D sparse convolution, and also sparse voxelization / devoxelization in Sparse Point-Voxel Convolution. Here, we provide the following example for hash map API:
source_hash = torchsparse.nn.functional.sphash(torch.floor(source_coords).int()) target_hash = torchsparse.nn.functional.sphash(torch.floor(target_coords).int()) idx_query = torchsparse.nn.functional.sphashquery(source_hash, target_hash)
In this example,
sphashis the function converting integer coordinates to hashing. The
sphashquery(source_hash, target_hash)performs the hash table lookup. Here, the hash map has key
target_hashand value corresponding to point indices in the target point cloud tensor. For each point in the
source_coords, we find the point index in
target_coordswhich has the same coordinate as it.
We here provides an entire training example with dummy input here. In this example, we cover
You are also welcomed to check out our SPVNAS project to implement training / inference with real data.
We benchmark the performance of our torchsparse and latest MinkowskiEngine V0.4.3 here, latency is measured on NVIDIA GTX 1080Ti GPU:
| Network | Latency (ME V0.4.3) | Latency (torchsparse V1.0.0) | | :----------------------: | :-----------------: | :--------------------------: | | MinkUNet18C (MACs / 10) | 224.7 | 124.3 | | MinkUNet18C (MACs / 4) | 244.3 | 160.9 | | MinkUNet18C (MACs / 2.5) | 269.6 | 214.3 | | MinkUNet18C | 323.5 | 294.0 |
If you find this code useful, please consider citing:
@inproceedings{ tang2020searching, title = {Searching Efficient 3D Architectures with Sparse Point-Voxel Convolution}, author = {Tang, Haotian* and Liu, Zhijian* and Zhao, Shengyu and Lin, Yujun and Lin, Ji and Wang, Hanrui and Han, Song}, booktitle = {European Conference on Computer Vision}, year = {2020} }
This library is inspired by MinkowskiEngine, SECOND and SparseConvNet.
|
https://xscode.com/mit-han-lab/torchsparse
|
CC-MAIN-2021-10
|
refinedweb
| 890
| 51.44
|
On 02/23/2018 08:33 AM, Tomasz Figa wrote: > On Fri, Feb 23, 2018 at 4:21 PM, Hans Verkuil <hverk...@xs4all.nl> wrote: >> On 02/23/2018 07:34 AM, Tomasz Figa wrote: >>> On Wed, Feb 21, 2018 at 1:18 AM, Hans Verkuil <hverk...@xs4all.nl> wrote: >>>> On 02/20/2018 05:44 AM, Alexandre Courbot wrote: >>>>> Add a new vb2_qbuf_request() (a request-aware version of vb2_qbuf()) >>>>> that request-aware drivers can call to queue a buffer into a request >>>>> instead of directly into the vb2 queue if relevent. >>>>> >>>>> This function expects that drivers invoking it are using instances of >>>>> v4l2_request_entity and v4l2_request_entity_data to describe their >>>>> entity and entity data respectively. >>>>> >>>>> Also add the vb2_request_submit() helper function which drivers can >>>>> invoke in order to queue all the buffers previously queued into a >>>>> request into the regular vb2 queue. >>>>> >>>>> Signed-off-by: Alexandre Courbot <acour...@chromium.org> >>>>> --- >>>>> .../media/common/videobuf2/videobuf2-v4l2.c | 129 +++++++++++++++++- >>>>> include/media/videobuf2-v4l2.h | 59 ++++++++ >>>>> 2 files changed, 187 insertions(+), 1 deletion(-) >>>>> >>>> >>>> <snip> >>>> >>>>> @@ -776,10 +899,14 @@ EXPORT_SYMBOL_GPL(vb2_ioctl_querybuf); >>>>> int vb2_ioctl_qbuf(struct file *file, void *priv, struct v4l2_buffer *p) >>>>> { >>>>> struct video_device *vdev = video_devdata(file); >>>>> + struct v4l2_fh *fh = NULL; >>>>> + >>>>> + if (test_bit(V4L2_FL_USES_V4L2_FH, &vdev->flags)) >>>>> + fh = file->private_data; >>>> >>>> No need for this. All drivers using vb2 will also use v4l2_fh. >>>> >>>>> >>>>> if (vb2_queue_is_busy(vdev, file)) >>>>> return -EBUSY; >>>>> - return vb2_qbuf(vdev->queue, p); >>>>> + return vb2_qbuf_request(vdev->queue, p, fh ? fh->entity : NULL); >>>>> } >>>>> EXPORT_SYMBOL_GPL(vb2_ioctl_qbuf); >>>>> >>>>> diff --git a/include/media/videobuf2-v4l2.h >>>>> b/include/media/videobuf2-v4l2.h >>>>> index 3d5e2d739f05..d4dfa266a0da 100644 >>>>> --- a/include/media/videobuf2-v4l2.h >>>>> +++ b/include/media/videobuf2-v4l2.h >>>>> @@ -23,6 +23,12 @@ >>>>> #error VB2_MAX_PLANES != VIDEO_MAX_PLANES >>>>> #endif >>>>> >>>>> +struct media_entity; >>>>> +struct v4l2_fh; >>>>> +struct media_request; >>>>> +struct media_request_entity; >>>>> +struct v4l2_request_entity_data; >>>>> + >>>>> /** >>>>> * struct vb2_v4l2_buffer - video buffer information for v4l2. >>>>> * >>>>> @@ -116,6 +122,59 @@ int vb2_prepare_buf(struct vb2_queue *q, struct >>>>> v4l2_buffer *b); >>>>> */ >>>>> int vb2_qbuf(struct vb2_queue *q, struct v4l2_buffer *b); >>>>> >>>>> +#if IS_ENABLED(CONFIG_MEDIA_REQUEST_API) >>>>> + >>>>> +/** >>>>> + * vb2_qbuf_request() - Queue a buffer, with request support >>>>> + * @q: pointer to &struct vb2_queue with videobuf2 queue. >>>>> + * @b: buffer structure passed from userspace to >>>>> + * &v4l2_ioctl_ops->vidioc_qbuf handler in driver >>>>> + * @entity: request entity to queue for if requests are used. >>>>> + * >>>>> + * Should be called from &v4l2_ioctl_ops->vidioc_qbuf handler of a >>>>> driver. >>>>> + * >>>>> + * If requests are not in use, calling this is equivalent to calling >>>>> vb2_qbuf(). >>>>> + * >>>>> + * If the request_fd member of b is set, then the buffer represented by >>>>> b is >>>>> + * queued in the request instead of the vb2 queue. The buffer will be >>>>> passed >>>>> + * to the vb2 queue when the request is submitted. >>>> >>>> I would definitely also prepare the buffer at this time. That way you'll >>>> see any >>>> errors relating to the prepare early on. >>> >>> Would the prepare operation be completely independent of other state? >>> I can see a case when how the buffer is to be prepared may depend on >>> values of some controls. If so, it would be only possible at request >>> submission time. Alternatively, the application would have to be >>> mandated to include any controls that may affect buffer preparing in >>> the request and before the QBUF is called. >> >> The buffer is just memory. Controls play no role here. So the prepare >> operation is indeed independent of other state. Anything else would make >> this horrible complicated. And besides, with buffers allocated by other >> subsystems (dmabuf) how could controls from our subsystems ever affect >> those? The videobuf(2) frameworks have always just operated on memory >> buffers without any knowledge of what it contains. > > What you said applies to the videobuf(2) frameworks, but driver > callback is explicitly defined as having access to the buffer > contents: > > * .
Advertising
Ah, good point. So the prepare step should be taken when the request is submitted. You definitely want to know at submit time if all the buffers in the request can be prepared so you can return an error. Userspace can also prepare the buffer with VIDIOC_BUF_PREPARE before queuing it into the request if it wants to. Regards, Hans
|
https://www.mail-archive.com/linux-media@vger.kernel.org/msg126703.html
|
CC-MAIN-2018-13
|
refinedweb
| 648
| 56.25
|
A storage to store particles. More...
#include <ParticleStorage.h>
A storage to store particles.
This class provides both generic CPU and GPU storages for particles, and provides generic methods to keep track of the currently allocated particles in this storage, and to keep track of the free slots that can be used to allocate new particles.
Creates a new ParticleStorage.
Deletes this ParticleStorage.
This deletes the data associated with all the particles managed by this particle storage.
Creates a new uninitialized ParticleStorage.
Deletes the entire list of particles.
Deletes the given particle.
Returns an iterator just past the last stored particle.
Returns the maximum number of particles that can be stored in this storage.
Returns a texture buffer containing particles data on GPU.
The particles data on GPU is splitted in several textures (see initGpuStorage()) identified by names. This method returns the texture buffer whose name is given. Its associated GPU buffer can be used in a ork::MeshBuffers (via an ork::AttributeBuffer) to directly use the content of this texture as a vertex array.
Returns the index of the given particle.
Returns an iterator to the first particle currently stored in this storage.
Provided the returned iterator is only used in a sequential way, particles can be added and removed while using this iterator. The iterator will only iterate through the particles that existed when this method was called, regardless of the creation and destruction of particles while iterating. This is no longer true, however, if several iterators are used at the same time and if several of them create and destroy particles while iterating.
Returns the current number of particles stored in this storage.
Initializes this ParticleStorage.
See ParticleStorage
Initializes the CPU storage for the particles.
Initializes a GPU storage for the particles.
The full GPU storage is supposed to be splitted in several textures, each texture storing one or more particle attribute (for instance one texture for positions, another for velocities, etc). All textures are texture buffers, (textures similar to 1D textures, whose pixels are accessible via a GPUBuffer) of capacity * components pixels. Each texture is associated with a name, so that ParticleLayer can access them with symbolic names.
Returns a new uninitialized particle.
The maximum number of particles that can be stored in this storage.
Pointers to the free and allocated particles in particles.
This vector is of size capacity. Its first available elements contain pointers to the free slots in particles, arranged in a heap data structure (if pack is true). The remaining elements contain pointers to the currently allocated particles.
The particles data on GPU, in the form of texture buffers.
See initGPUStorage().
True to ensure that new particles are always created with the minimum available index.
See ParticleStorage.
The particles data on CPU.
This memory chunk is of size capacity * particleSize bytes.
The size in bytes, on CPU, of each particle.
|
https://proland.imag.fr/doc/proland-4.0/core/html/classproland_1_1ParticleStorage.html
|
CC-MAIN-2021-21
|
refinedweb
| 478
| 50.33
|
Help on Storage Development
Contents
- Help on Storage Development
- Prerequisites
- A Complete Tour
- The Storage API
- What data is handled by the storage API?
- The Players
- How it is used by Moin
- Using it
- Extending the Storage Eco-System
Prerequisites
This guide assumes you have already read and understood Storage2009/HelpOnStorageConfiguration as the terminology used there will be used here as well.
A Complete Tour
When MoinMoin receives a request from a browser it looks up the action that should be taken (e.g. most commonly 'show page') from the request arguments. It then creates a so called context (similar to old request object) that contains information about the user who accessed the page in the browser and other configuration parameters (such as what is used for storage). The action in question is invoked and the context is passed to that action. Dependant on the mimetype of the item the user wants to access, an appropriate high-level item is created in the show action. We then get the content from that high-level item and ask our theme to render the content for the user.
Now, where does the content come from? As explained in Storage2009/HelpOnStorageConfiguration it may come from an instance of any final backend type supported. Before the content is accessed (or in the case of the modify action, modified), the ACL middleware (that belongs to the backend the item comes from) automatically performs permission checks and raises an AccessDeniedError if appropriate. This means that you usually do not need to take care of checking permissions yourself.
In the early steps of processing the request the namespace_mapping that was defined in the wiki's configuration is used to assemble two instances of the router middleware which are the central points from where storage data is accessed throughout the wiki. One of those routers takes the ACL rules that were specified for each individual backend into account (hence protecting the backend's contents), the other doesn't. The former can be accessed as request.storage, the latter as request.unprotected_storage. You can use these middlewares just as if they were normal backends and need not take care of putting items into the correct backend yourself.
The Storage API
The storage API of MoinMoin >2.0 is defined in MoinMoin/storage/__init__.py. It is well documented in the docstrings. It might still be helpful for you to get a better idea about the components it's comprised of. We will explain that in the following so you can start using the API in your own code.
What data is handled by the storage API?
All data. Pages, Attachments (Movies, Soundclips, Images, ...) and even users and their confidential data.
The Players
- Backend - A backend is a collection of zero or more items. It manages them and makes sure that item names are unique. It allows to iterate over items and revisisions and to create, get and search for items.
- Item - An item is a collection of zero or more revisions. The item is the only player that has a name associated with it. It contains metadata about itself. It allows to create, get and iterate over its revisions.
- Revisions - A Revision can contain arbitrarily large amounts of data. This could be a page's content at a given point in time or even your movie's data. Revisions also have metadata.
StoredRevision - Revisions that are only used for reading content. These are immutable.
NewRevision - Revisions that are used when new content should be stored. These can be modified until they are committed to storage.
How it is used by Moin
MoinMoin needs to store several different things. In the following it will be explained how these things are stored, so you will get an idea of how the storage API is used and how it can be used.
Storing Pages
A page in Moin consists of a name, meta-information (such as the page authors) and obviously the page's contents. We now store a page as an item that makes use of revisions. If a non-existing page is modified and saved, a new item (with the page's name as item name) is created along with a first revision of that item. The contents the user entered for the page are then written to the revision. The meta-information is stored separately in the revision's metadata. After all data has been pumped into the revision, the item is committed and the new revision ends up in storage. If the same or another user now comes along and modifies the already existing page, Moin realizes that there already is an item with the name of the page and hence does not create but get the already existing item. A second revision is created and the new page contents are written to the new revision alongside the meta-information of this second modification. Let's say another user wants to look at the changes that have been made in revision 2 of the page (Note that the term 'Revision' is used in page and item context alike). In order to construct the differences between the two revisions the diff action obviously needs to get both revisions of the item. It then reads both revision's data and compares it. The result of the comparison is then rendered in the browser.
Storing Attachments
Attachments are stored in the very same way as pages. They have been special-cased in MoinMoin <= 1.9 but are now treated as items as well.
Storing Users
Obviously you need to store your users' profile data somehow as well in order to send emails to users or to allow them to log in with their password. It might not be clear at first glance how one would store users with the approach described above, but the answer is quite simple: We don't need to revision a user's data, so we can just use a normal item (with the user's id as item name) and store the user's data in the item's metadata. That's it. Whenever the user updates his data, the item's metadata is simply updated reflecting the change made by the user.
Using it
Below we will provide a few simple examples on how you can use the storage API to store and retrieve data. Note: For all of the examples below we will assume that a backend object is present already. In order to get used to the API, you can construct it as follows:
If you want prefer to work with a persistent backend, you can choose between the fs and hg backends. A snippet for a persistent environment is given below:
1 >>> from MoinMoin.storage.backends import fs, hg 2 3 # If you want to use hg, use: 4 backend = hg.MercurialBackend("path/to/already/existing/folder") 5 6 # And for fs it would be: 7 backend = fs.FSBackend("path/to/already/existing/folder") 8 9 # Note that you should use only one of those, as the second assignment to the name backend will overwrite the reference to the first backend.
Creating an Item with Revision
This is the most common case. We will just create an item and a revision and store some contents.
1 # We create an item with a unique name. No other item in the backend has this name. 2 >>> item = backend.create_item("MyDiary") 3 4 # There's a handy attribute on every item object that gives you its name: 5 >>> item.name 6 "MyDiary" 7 8 # Note that you must pass the number of the revision you want to create as argument. 9 # This is done for concurrency reasons. You can also pass item.next_revno, which would 10 # be 0 in this case because the item does not have any revisions yet. 11 >>> rev = item.create_revision(0) 12 13 # There is a similar helper for revisions. This gives you the revision's unique number (item-wide, not backend-wide) 14 >>> rev.revno 15 0 16 17 # We can modify the revisions metadata. Revisions support dict-like access for this. 18 >>> rev["Date"] = "Today!" 19 20 # We now write some data to the revision: 21 >>> rev.write("Beloved diary, today I learned how to use MoinMoin's great storage API!") 22 23 # In order to actually store our changes in the storage backend, we need to commit the item: 24 >>> item.commit()
Adding a Second Revision
In order to add a revision to an already existing item, you would do the following:
1 # Since we have already created an item once, we *get* it this time and do not create it again: 2 >>> item = backend.get_item("MyDiary") 3 4 # Create the next revision. Again: You must pass the next revision number. We do that with the 5 # item.next_revno helper this time, so you don't need to compute it manually. 6 >>> rev = item.create_revision(item.next_revno) 7 8 # Naturally, we can again store something in the revisions metadata... 9 >>> rev["Date"] = "Yesterday + 1" 10 11 # ... and write to the revision.... 12 >>> rev.write("Hey Diary! Today I'm gonna write my first piece of code using the storage API!") 13 14 # ... and commit the item again so we can be sure that our data was actually saved. 15 >>> item.commit()
Getting an Old Revision
If you want to take a look at revisions that have already been added to storage, you can do it like this:
1 # Since revisions are bound to their item, we first need to get the item that contains the revision 2 >>> item = backend.get_item("MyDiary") 3 4 # We can now get the revision we want... 5 >>> rev = item.get_revision(0) 6 7 # ... take a look at its metadata... 8 >>> rev["Date"] 9 "Today!" 10 11 # ... and of course read its contents: 12 >>> rev.read() 13 "Beloved diary, today I learned how to use MoinMoin's great storage API!"
Accessing an Item's Metadata
As was already mentioned when explaining how Moin stores users, item can have metadata as well. Accessing it is similar to how a revisions metadata is accessed.
1 # We need the item obviously, so get it if we don't have it around anymore 2 >>> item = backend.get_item("MyDiary") 3 4 # We need to acquire a lock on the item so that only one person is allowed to change the 5 # metadata at any given point in time. We do that with a call to change_metadata(). 6 >>> item.change_metadata() 7 8 # We can now set new metadata key/value pairs as we see fit 9 >>> item["Warning"] = "This diary is private! Take your filthy hands off!" 10 11 # We need to release the lock that we acquired before. This also flushes the metadata to 12 # the storage system. 13 >>> item.publish_metadata() 14 15 # We can now access the key we set before and get the value back. (This is read-only now as 16 # we don't have a lock anymore). 17 >>> item["Warning"] 18 'This diary is private! Take your filthy hands off!'
Error Handling
There are several storage specific exceptions that may be raised while you are working with the storage system. For a complete list, please see MoinMoin/storage/errors.py. We will show a few of those errors in practice:
1 # If we try to change an item's metadata without having acquired a lock, it will raise an error: 2 >>> item["Warning"] = "This diary is a wiki! Feel free to modify." 3 Traceback (most recent call last): 4 File "<input>", line 1, in <module> 5 File "./MoinMoin/storage/__init__.py", line 650, in __setitem__ 6 raise AttributeError("Cannot write to unlocked metadata") 7 AttributeError: Cannot write to unlocked metadata 8 9 # We will also see an error if we try to create a revision that has already made its way to the storage system: 10 >>> rev = item.create_revision(1) 11 Traceback (most recent call last): 12 File "<input>", line 1, in <module> 13 File "./MoinMoin/storage/__init__.py", line 782, in create_revision 14 self._uncommitted_revision = self._backend._create_revision(self, revno) 15 File "./MoinMoin/storage/backends/memory.py", line 179, in _create_revision 16 "The revision number must be latest_revision + 1.") % (item.name, last_rev, revno)) 17 RevisionNumberMismatchError: The latest revision of the item ''MyDiary'' is 1, thus you cannot create revision number 1. The revision number must be latest_revision + 1. 18 19 # Due to the uniqueness of item names we cannot create an item with an already occupied name: 20 >>> item = backend.create_item("MyDiary") 21 Traceback (most recent call last): 22 File "<input>", line 1, in <module> 23 File "./MoinMoin/storage/backends/memory.py", line 100, in create_item 24 raise ItemAlreadyExistsError("An Item with the name %r already exists!" % (itemname)) 25 ItemAlreadyExistsError: An Item with the name 'MyDiary' already exists! 26 27 # We cannot get items that do not exist: 28 >>> item = backend.get_item("MyOtherDiary") 29 Traceback (most recent call last): 30 File "<input>", line 1, in <module> 31 File "./MoinMoin/storage/backends/memory.py", line 71, in get_item 32 raise NoSuchItemError("No such item, %r" % (itemname)) 33 NoSuchItemError: No such item, 'MyOtherDiary' 34 35 # The same is true for revisions: 36 >>> item.get_revision(404) 37 Traceback (most recent call last): 38 File "<input>", line 1, in <module> 39 File "./MoinMoin/storage/__init__.py", line 734, in get_revision 40 return self._backend._get_revision(self, revno) 41 File "./MoinMoin/storage/backends/memory.py", line 153, in _get_revision 42 raise NoSuchRevisionError("No Revision #%d on Item %s - Available revisions: %r" % (revno, item.name, revisions)) 43 NoSuchRevisionError: No Revision #404 on Item MyDiary - Available revisions: [0, 1]
Processing Several Items/Revisions Iteratively
There are several ways you can access multiple items or revisions iteratively. We will demonstrate how:
1 # By now you should be familiar with the following call: 2 >>> item = backend.get_item("MyDiary") 3 4 # You can get a list of the item's revisions' numbers: 5 >>> item.list_revisions() 6 [0, 1] 7 8 # You can also iterate over all revisions that the *backend* has. Note that the following is just the same as what we 9 # had in the step before because there only is one item in the backend in this case. 10 >>> [rev.revno for rev in backend.history()] 11 [0, 1] 12 13 # In a similar way you can iterate over the items a backend has: 14 >>> [item.name for item in backend.iteritems()] 15 ["MyDiary"] 16 17 # IMPORTANT: Note that you should NOT do something like list(backend.iteritems()). While revisions, content and metada 18 # may be loaded lazily, some backends need to perform some additional bookkeeping and such a call would make 19 # the backend explode. The fs backend, for example, would struggle since it keeps an open file handle for each item.
Extending the Storage Eco-System
The most common way to extend the storage API is to write a backend yourself. That backend can then be used by yourself or others with the API presented above. It will automatically fit into the storage system and can be used in combination with the already existing middlewares.
If you want to write your own backend, all you have to do at the very least is to implement the Backend class (MoinMoin.storage.Backend). Generic items and revisions will then automatically be available for your backend, so you don't need to implement those yourself as well (although you can do that if you want).
The storage system internally is constructed in a way that allows to easily write and add new backends. Most method calls you can perform on an item or a revision call an internal method on the backend by default. This is why it is sufficient to implement the backend (including the internal methods, obviously) to get something functional. For reference, please see the simple MemoryBackend implementation in MoinMoin.storage.backends.memory. In order to get started you can just copy MoinMoin/storage/__init__.py to a new file in MoinMoin/storage/backends and implement the methods that raise a NotImplementedError. (If you have something that you would like to share with us and perhaps even see included in MoinMoin, please do not hesitate to contact us.)
Happy Hacking!
|
http://www.moinmo.in/Storage2009/HelpOnStorageDevelopment
|
crawl-003
|
refinedweb
| 2,700
| 64.2
|
With inlining turned off, run time is about 1.70 seconds. With inlining turned on, run time is less than a second.
/* inline int sum(int a, int b) { return (a + b); } int c = sum(1, 4); // If the compiler inlines the function the compiled code will be the same as writing: int c = 1 + 4; */ #include <stdio.h> #include <stdlib.h> #include <time.h> /* int sum (int a, int b) __attribute__ ((noinline)); */ static inline int sum (int a, int b) { return a+b; } int main() { const int SIZE = 100000; int X[SIZE],Y[SIZE],A[SIZE]; int i,j; for (i=0;i<SIZE;++i) { X[i] = rand(); Y[i] = rand(); } clock_t t = clock(); /* start clock */ for (i=0;i<5000;++i) { for (j=0;j<SIZE;++j) A[j] = sum(X[j],Y[j]); } t = clock()-t; /* stop clock */ printf("Time used: %f seconds\n", ((float)t)/CLOCKS_PER_SEC); printf("%d\n", A[0]); }
Possible output:
Time used: 0.750000 seconds -1643747027
()
|
http://en.cppreference.com/mwiki/index.php?title=c/language/function_specifiers&oldid=68016
|
CC-MAIN-2015-40
|
refinedweb
| 163
| 79.19
|
Python Contoso Ads Application Cloud Service
Introduction
Flask (Micro-framework for Python) version of the Contoso Ads application in Get started with Azure Cloud Services and ASP.NET.
Prerequisites
1. Python 3.4 interpreter for Windows.
Note that only Python 3.4 and 2.7 are natively supported by Azure (Python 3.4 by default). If you prefer 2.7 or other versions, additional configuration for startup task is required.
2. Visual Studio 2013 or 2015
3. Python Tools for Visual Studio (PTVS)
4. Azure SDK Tools for VS 2013 or Azure SDK Tools for VS 2015
5. Azure Storage Account
Follow this guide to create a storage account and obtain the Access Key.
6. Azure Service Bus
Follow this guide to create a service bus and obtain the SAS key.
7. MongoDB
You may use MongoDB on Azure Virtual Machine or mLab.
Run the sample
1. Right click the project in the solution explorer and then choose Reload Project if it shows “unavailable”.
a
2. Modify the connection settings in WebRole1 > app > config.py.
MONGODB_SETTINGS ={
'db': 'your database name',
'host': 'your MongoDB host',
'port': port number,
'username': 'your user name',
'password': 'your password'
}
STORAGE_ACCOUNT_NAME = 'your storage account name'
STORAGE_ACCOUNT_KEY = 'storage access key'
SERVICEBUS_NAMESPACE = 'your servicebus namespace'
SERVICEBUS_ACCESS_KEYNAME = 'access key name'
SERVICEBUS_ACCESS_KEYVALUE = 'access key value'
3. Modify the connection settings in WorkerRole1 > config.py.
STORAGE_ACCOUNT_NAME = 'storage account name'
STORAGE_ACCOUNT_KEY = 'storage access key'
SERVICEBUS_NAMESPACE = 'servicebus namespace'
SERVICEBUS_ACCESS_KEYNAME = 'access key name'
SERVICEBUS_ACCESS_KEYVALUE = 'access key value'
MONGODB_NAME = 'your database name'
MONGODB_HOST = 'your MongoDB host'
MONGODB_PORT = port number
MONGODB_USERNAME = 'your user name'
MONGODB_PASSWORD = 'your password'
4. Right click the Python Environments section under the solution, remove the old virtual environment setting in WebRole1.
5. Add a new virtual environment in WebRole1.
6. Uncheck “Download and install packages” because we need to add some wheel files to local disk.
7. Repeat step 2 - 6 for WorkerRole1.
8. Find the .whl files in bin folder under WorkerRole1.
9. Create a bin folder in WorkerRole1 env folder and copy the .whl files to bin.
10. Repeat step 8 - 9 for WebRole1.
11. Run Install from requirements.txt for both virtual env.
12. To debug a particular role, right click on the role name and click "Set as StartUp Project".
Publish to Azure
You may follow this guide to publish the application to Azure Cloud Service.
Additional Information
1. We use wheels to install cffi, cryptograpy and Pillow library, because in Python 3.4 normal pip installation for these libraries may fail and return error "Unable to find vcvarsall.bat". If you can successfully install all references just by defining the name in requirements, you may safely skip above step 8 - 10.
2. Startup and Runtime task logs are located in the C:\Resources\Directory{role}\LogFiles folder in the Cloud Service instance. Check ConfigureCloudService.txt if any library in requirements.txt is not successfully installed. Check LaunchWorker.err.txt for WorkerRole runtime errors.
|
https://azure.microsoft.com/hu-hu/resources/samples/cloud-services-python-contoso-ads-application/
|
CC-MAIN-2017-34
|
refinedweb
| 486
| 59.6
|
1. What is simulated annealing algorithm?
Simulated annealing algorithm (SAA) was first proposed by N.Metropolis in 1953.
It is said that he suddenly thought of this simulated annealing method when he took a bath. The principle of simulated annealing is starting from a higher initial temperature at the initial time, and the molecules in the material are in a random arrangement state. With the constant decrease of temperature coefficient, the molecules are gradually arranged in a low-energy state, and finally reach a certain stable state.
Physical annealing
To understand the simulated annealing algorithm, first of all, we need to know how to realize physical annealing. The process of physical annealing is roughly divided into three stages:
The process of heating up - we accelerate the thermal movement of molecules by heating continuously, so that the whole object is in a random and disordered state until the object is at an initial temperature T.
Constant temperature process - because the object is always exchanging with the outside world, the state of the object is always in the direction of reducing the free energy. When the free energy is stable, the object reaches a balance state.
Cooling process: the thermal movement of molecules inside the object gradually weakens and tends to be orderly, and the energy of the object will drop, thus reaching a low-energy crystal shape.
Metropolis guidelines
In the simulated annealing algorithm, a very important criterion is called the Metropolis criterion. The process of this criterion is as follows:
1. First, set an initial condition, the initial number k, the initial temperature T, the solution (also known as the state) S(k) output in the process, give S(k) an initial value S(k)=S0;
2. ① generate an adjacent subset N(S(k)) on the state s of S(k) (current solution) in a certain way,
② In N(S(k)), a state s' is randomly selected as a candidate solution, and the difference between the candidate solution and the current solution is calculated to compare which one is better. ΔC’=C(S’)-C(S(k));
3. Next, we will discuss according to the situation of Δ C ':
① If Δ C '< 0, then S' is the best solution;
② If Δ C '> 0, then S' should be chosen as the optimal solution according to the formula with probability P=e^{-(Ej − Ei)/(k * T)}. Where Ej is the energy of the new state j, Ei is the energy of the old state i, K is the proportional coefficient of the temperature drop, and T is the current temperature.
4.k=k+1, the status is updated. Before the next operation, check whether the algorithm has met the termination conditions:
① If satisfied, proceed to step 5.
② If not, return to step 2 to continue.
5. At this time, the optimal solution S(k) obtained is the final answer, and the program ends.
simulated annealing
1.S(0)=S0 sets the initial state, i=0, and records the times of operation;
2. Set the initial temperature T=Ti, call the Metropolis sampling algorithm with T and S(k), and return the state Si as the current solution of the algorithm, at this time S=Si;
3. Cool down in a certain way, i.e. T=T(i+1), where t (I + 1) < Ti, i=i+1;
4. Check whether the termination condition is met. If it is, carry out step (5). Otherwise, carry out step (2).
5. The current Si is the optimal solution and the output stops.
TSP problem
TSP problem is also called traveling salesman problem (TSP). It was put forward by Irish mathematician Sir William Rowan Hamilton and British mathematician Thomas Penyngton Kirkman in the 19th century.
Its description is as follows: a businessman wants to go to several cities to sell goods, knowing the number of cities and the distance (or travel expenses) between cities, asking for a route starting from city 1, passing through all cities and each city can only be visited once, and finally returning to city 1, so as to minimize the total distance (or travel expenses). It has been proved to be a NP (non deterministic polynomial) problem.
Advantages of simulated annealing in solving TSP problems
The old algorithm has the following disadvantages in solving TSP: high time complexity, unknown time complexity in the worst case, will fall into the trap of local optimal solution.
SAA can accept the new solution according to the Metropolis criterion. In addition to the optimal solution, SAA can also accept the deteriorated solution within a certain limit. When the temperature T value is large, the acceptable deterioration solution is poor; when the temperature T value is small, the acceptable deterioration solution begins to get better. When T - > 0, we no longer accept the deteriorating solution.
Such an algorithm can jump out of the trap of local optimal solution. With the decrease of T, the probability of global optimal solution returned by the algorithm monotonically increases, and the probability of non optimal solution decreases.
Code
#include <iostream> #include <string.h> #include <stdlib.h> #include <algorithm> #include <stdio.h> #include <time.h> #include <math.h> #include<fstream> #include<typeinfo> #include<vector> #include <iterator> #define N 200 //Maximum number of cities #define T 3000 //initial temperature #define ET 1e-8 //Termination temperature #define DELTA 0.98 //Temperature decay rate #define LIMIT 1000 //Upper limit of probability selection #define OUTLOOP 20 //Number of external cycles #define INLOOP 100 //Number of internal cycles using namespace std; //Defining the structure of an alignment struct Path { int city[N];//City node double len;//Length of route }; //Define the structure of the city struct City { double w[N][N];//Record the distance between two cities double x, y;//Record the coordinates of the city int n; }; Path b;//Best path City p[N];//Record the coordinates of each city City C; int ncase;//Record the total number of tests double dis(City A, City B)//Calculate the distance between points A and B { return sqrt((A.x - B.x) * (A.x - B.x) + (A.y - B.y) * (A.y - B.y)); } void GetDist(City& C,City p[])//Store the distance between a and B cities { for (int i = 0; i < C.n; i++) for (int j = i + 1; j < C.n; j++) C.w[i][j] = C.w[j][i] = dis(p[i], p[j]); } void Inputf(int& n,City p[])//Enter coordinates for each city { cin >> n; for (int i = 0; i < n; i++) { cin >> p[i].x >> p[i].y; } } void Input(int& n, City& C) { C.n=n; } void tIn(int& n, City p[]) { int i, datalen = 0; double num[600]; ifstream file("data.txt"); while (!file.eof()) file >> num[datalen++]; n = num[0]; for (int i = 1; i < datalen - 1; i++) { if (i % 2 == 0) p[i - 1].y = num[i]; else p[i - 1].x = num[i]; } } void Init(City C)//Create a path { ncase = 0; b.len = 0; for (int i = 0; i < C.n; i++) { b.city[i] = i; if (i != C.n - 1) { cout << i <<"----->";//Print this city node b.len += C.w[i][i + 1];//Increase in the length of the best path } else cout << i<<endl;//Print last city node } } void Print(Path t, City C)//Print specific route and length { cout << "Path is : "; for (int i = 0; i <= C.n; i++) { if (i != C.n) cout << t.city[i] << "-->"; else cout << t.city[i]; } cout << "\nThe path length is :\n" << t.len; cout << "-----------------------------------\n\n"; } Path GetNext(Path p,City C) { //Path p; Path ans = p; int x = rand() % (C.n - 1) + 1;// %Remainder - > to control the random number at [1, n - 1] int y = rand() % (C.n - 1) + 1; while (x == y)//Ensure that x and y are not equal { x = rand() % (C.n - 1) + 1; y = rand() % (C.n - 1) + 1; } swap(ans.city[x], ans.city[y]);//A way to exchange the location of two cities ans.len = 0; for (int i = 0; i < C.n-1; i++) ans.len += C.w[ans.city[i]][ans.city[i + 1]];//Calculate the length of the route ans.len += C.w[ans.city[C.n - 1]][ans.city[0]]; cout << "nCase = " << ncase << endl;//Printing has gone through several situations Print(ans, C);//Print route ncase++; return ans; } void SA(City C) { double t = T; srand((unsigned)(time(NULL))); Path curPath = b; Path newPath = b; int P_L = 0; int P_F = 0; while (1) //External circulation, main update parameter t, simulated annealing process { for (int i = 0; i < INLOOP; i++) //Internal circulation, looking for the best value at a certain temperature { newPath = GetNext(curPath, C);//Randomly generate route double dE = newPath.len - curPath.len;//Calculate if the new route is better if (dE < 0) //If the new route is better, update it directly { curPath = newPath; P_L = 0; P_F = 0; } else { double rd = rand() / (RAND_MAX + 1.0);//If the solution is not good, it will be updated with a certain probability, and the probability will be smaller and smaller if (exp(dE / t) > rd&& exp(dE / t) < 1) curPath = newPath; P_L++; } if (P_L > LIMIT)//If the probability of more than a thousand choices { P_F++;//End of primary external circulation break; } } if (curPath.len < b.len) b = curPath;//Update if the current path is optimal if (P_F > OUTLOOP || t < ET)//If the external cycle exceeds 20 times and the temperature drops to the end temperature, the cycle will jump out break; t *= DELTA;//Otherwise, the temperature will decay at a rate of 0.98 } } int main(int argc, const char* argv[]) { int n; tIn(n, p); Input(n,C); GetDist(C,p); Init(C); SA(C); Print(b, C); cout << "Total test times is \n" << ncase; return 0; }
Program screenshots
data.txt text
This text is placed in the folder where the program is located. At first, the program uses manual input, and then manual input has small amount of data, low efficiency and other reasons, and finally uses text reading.
The first line is the total number of cities
Here are the coordinates of each city
Run screenshots
All the test results are printed out, and the last result is the optimal path graph.
Thank you here.
and
The guidance of the maze.
|
https://programmer.ink/think/simulated-annealing-algorithm-saa-to-solve-tsp-problem.html
|
CC-MAIN-2021-04
|
refinedweb
| 1,712
| 53.41
|
When creating a shape node with Maya’s API in the draw event you simply get the state of the object. Sadly, this can never be retrieved anywhere else (unless we’d override all Maya nodes to have them store the value somewhere). After a long search I found no way of replicating what Maya does before drawing a node, so I had to come up with a different method.
When determining the color of an object’s wireframe there’s all kind of inÎfluences. Is it:
>selected
>a lead selection
>templated
>referenced
>in a layer which is templated or referenced
>does it have an override color set
>does it have a layer with a color
>does it have a parent with an override color
and most hated of all:
>is it purple? (affected by a selected object)
Now luckily layers drive the overridesEnabled, overrideColor and overrideDisplayType attributes, so we don’t really have to worry about those.
An important part is determining in which order of importance these colors are determined. Essentially templating is most important
>objects turn orange when selected and templated simultanously
>green when selected as last (lead)
>white when selected
>purple when influenced by other selected objects (affected)
>gray when templated
>black when referenced
>overrideColor when enableOverrides is True
>blue otherwise
All these properties are inherited from parents as well. So when a referenced object has a drawingOverride, it is still black, when an object is affected by another selected object but also selected it will still be green (or white). When an object’s parent is templated, the object itself appears templated, etcetera.
Do realize this only applies to shapes, as they are the only objects actually being drawn!
The next problem once we know all this information, is determining what colour links to that info. There’s the displayColor and displayRGBColor commands for that, and lucky for use, they have a list feature. So printing each entry and then reading for quite a while we find out the names of the attributes (which mostly match those in the Window -> Settings/preferences -> Color Settings but not always).
So some colors can be set freely, such as the template color. Other colors can only be set to certain indices, displayColor returns a number and we’ll have to use the colorIndex command to get to the actual color. We could hardcore the colors, but then the result is not matching the display if the user changes his settings.
So let’s start with the most basic scenario, a given node’s child shape’s dormant color. Here we run immediately into the next issue, every shape type can have it’s own deselected and selected color and most of the names do not match the nodeType name. For example a measure node is of type distanceDimShape and it’s color needs to be retrieved as ‘dimension’. So here’s a partial list of name conversion:
def displayColorType(inObj): objtype = cmds.nodeType(inObj) if objtype == 'nurbsSurface': trims = cmds.listConnections(shape, s=True, d=False, type='planarTrimSurface') if trims: obtype = 'trimmedSurface' else: objtype = 'surface' if objtype == 'nurbsCurve': projectCurves = cmds.listConnections(shape, s=True, d=False. type='projectCurve') if projectCurves: objtype = 'curveOnSurface' else: objtype = 'curve' if objtype == 'mesh': objtype = 'polymesh' if objtype == 'joint' and cmds.listRelatives(shape, ad=True, type='effector'): objtype = 'segment' if objtype == 'cluster': objtype = 'locator' if objtype == 'distanceDimShape': objtype = 'dimension' return objtype
This function is not limited to shapes, but it will result in errors when you attempt to use
cmds.displayColor(displayColorType(),q=True)
on a transform node.
So I assume this to be all I need but the list may get longer when it turns out certain objects try to get their color by the wrong name. Now let’s check whether the object is selected or not and return either the dormant or the active color related to its type:
def drawColor(inObj): shapes = cmds.listRelatives(inObj, ad=True, type='shape', f=True) if not shapes: if cmds.nodeType(inObj) != 'transform': shape = inObj else: #transform node without shapes has no color return None else: shape = shapes[0] nodetype = displayColorType( shape ) if shape in cmds.ls(sl=True,l=True): return cmds.colorIndex( cmds.displayColor(nodetype, q=True, active=True), q=True ) return cmds.colorIndex( cmds.displayColor(nodetype, q=True, dormant=True), q=True ) print( drawColor( cmds.polyCube()[0] ) )
Now this will immediately print the wrong color, as the parent is selected and not the shape.
#result: [1.0, 1.0, 1.0]
So let’s solve that bit with the following function:
def isParentSelected(inObj): selection = cmds.ls(sl=True, l=True) target = cmds.ls(inObj, l=True)[0] #ensure full path while target: if target in selection: return True target = cmds.listRelatives(target, p=True, f=True)[0] return False
Now in drawColor on line 11 instead of using
if shape in cmds.ls(sl=True, l=True)
I will use
if isParentSelected(shape):
Now it returns the the selected color, which is white.
#result: [1.0, 1.0, 1.0]
But our object is in the lead, so it is green. So with some modifications this isn’t too difficult. Let the isParentSelected return the parent (or None) instead of True. I also fixed the part where I forgot to check if we had a selection, ls and listRelatives return None instead of an empty list if there is no result, so we get problems at ‘target in selection’ if there is no selection.
def isParentSelected(inObj, ignoreSelf=False): selection = cmds.ls(sl=True, l=True) if not selection: #no selection, no result return if not ignoreSelf: if inObj in selection: return inObj targets = cmds.listRelatives(inObj, ap=True, f=True) if not targets: return for target in targets: if target in selection: return target return
Then the last bit of drawColor becomes this:
nodetype = displayColorType( shape ) selected = isParentSelected( shape ) if selected: if selected == cmds.ls(os=True, l=True)[-1]: return cmds.colorIndex( cmds.displayColor('lead', q=True, active=True), q=True ) return cmds.colorIndex( cmds.displayColor(nodetype, q=True, active=True), q=True ) return cmds.colorIndex( cmds.displayColor(nodetype, q=True, dormant=True), q=True )
The ls function returns the ordered selection, ensuring that the last entry is indeed the lead entry and we use the active lead displayColor isntead of the active nodetype displayColor. The lead color can also be customised, but not per object type.
#result: [0.2630000114440918, 1.0, 0.63899999856948853]
Now this post is getting rather long, so more on this later, where I’ll have a look into overrides.
|
http://trevorius.com/scrapbook/maya/detecting-wire-color-in-maya/
|
CC-MAIN-2018-47
|
refinedweb
| 1,095
| 53
|
I was able to print out daily values and aggregate the final annual result but I am lost and dont know where to start on how to sum the daily values to monthly and print it out. I need your help badely.
Here is part of the code
import os.path # Open files to read ifh = open("D:/ArcView/pcp_avg.txt", "r") ifh2 = open("D:/ArcView/parameters_31Oct.txt", "r") # Open files to write output ofh1 = open("D:/ArcView/rye1.txt", "w") ofh2 = open("D:/ArcView/rye2.txt", "w") # Read the files rainF = ifh.readline() cropP = ifh2.readline() # print heading on the annual output print >>ofh2, 'X_CORD', 'Y_CORD', 'ID', 'ETct', 'ETat' while rainF and cropP: rfields = rainF.split() cfields = cropP.split() X_Grid = cfields[0] # X-grid (latitude) in degree Y_Grid = cfields[1] # Y-grid (longitude) ID = int(float(cfields[2])) # parameters initialization KS = 1 Dri = TAWC*Zrmin_rf*Pstd Total = 0 ETat = 0 ETct = 0 print >>ofh1, X_Grid, Y_Grid, ID, print >>ofh2, X_Grid, Y_Grid, ID, #for loop over the grawing period - from planting to harvest for J in range (1, 365, 1): # Daily calculation of different parameters PR = float(rfields[J]) ETo = float(efields[J]) ETc = ETo * KC # do some more here ........ # calculation of soil water balance if Dri > RAW: KS = max(0,((St)/((1-Pi)*TAW))) else: KS = 1 # and some more ...... ETa = ETc * KS # aggregation over the growing period ETct += ETc ETat += ETa # print daily values print >>ofh1, '%7.2f' %ETc, # how to print monthly values ?????? # print annual values print >> ofh2, '%.2f %.2f'%(ETct, ETat), print >>ofh1 print >>ofh2 # running over the files rainF = ifh.readline() cropP = ifh2.readline() # closing the files ofh1.close() ofh2.close() ifh.close() ifh2.close()
|
https://www.daniweb.com/programming/software-development/threads/283012/need-help-on-how-to-sum-daily-to-monthly
|
CC-MAIN-2017-51
|
refinedweb
| 280
| 67.45
|
Re: Struct inside class
- From: "Michael D. Ober" <obermd.@.alum.mit.edu.nospam>
- Date: Wed, 31 May 2006 16:03:03 -0600
In OPs original source, it isn't obvious that OP is referring to a generic
object variable. In this case, boxing must be done. The runtime cannot
operate on a generic object variable without the boxing. I suspect that the
concrete object will still be laid out the same manner by the compiler, but
that the compiler will have to generate addition calls into the memory
manager to box and unbox every reference to the object "o". That's why I
copied OP's original sample.
Mike.
"Göran Andersson" <guffa@xxxxxxxxx> wrote in message
news:eYap1NMhGHA.4304@xxxxxxxxxxxxxxxxxxxxxxx
No, you are missing the point.instance
This is the code in question:
object o = myClass.s.i1;
From the previous discussion, we know that i1 is a member variable of a
strunct in a class, so it's stored on the heap.
The question was if boxing occurs or not, considering that the i1
variable is stored on the heap.
The answer is that boxing does occur, because it's not the i1 variable
that is stored in the object, but the value from the i1 variable. It
doesn't matter where the i1 variable is stored.
Michael D. Ober wrote:
You're missing the point.
All instance data inside a class is stored on the heap, but within the
memory allocation for that object. The compiler figures computes the
instance data layout, just like it would for the local variables in a
procedure and then references all the instance data relative to the
onlyonlybase address. This is very simple to code in machine assembler (MOV AX,
WORD PTR [DX]) for example. Boxing is a runtime feature and is used
anotheranotherwhen an object's type is unknown at compile time. When you put a struct
inside a class, the compiler knows the types at runtime, except when you
declare a structure component as a generic "Object".
Here's a simple set of rules for how storage is allocated:
Reference types, including anything derived from "Object": Heap pointer
from either a stack frame, global compilera allocated storage, or
ononobject on the heap.
All Value Types, including "Struct": Stored on the stack, in global
compiler allocated storage, or relative to the base address of an object
storedstoredthe heap
Where this gets confusing is when you use a value type as part of the
instance data of a reference type. In this case, the value type is
instance.instance.on the heap, but inside the allocated space for the reference type
thatthatWhen you use a reference type as instance data of a reference type, all
totois allocated inside the containing reference type instances is a pointer
havehavethe instance data. This complexity is why C and C++ programs tend to
variables asvariables asmemory leaks and why the .NET good garbage collector is required.
Note that I referenced "global compiler allocated storage". This is the
memory allocated by the compiler for globally accessible public
x86x86well as static (VB Shared) variables associated with objects. On the
ititplatforms, this memory is reference relative to the "DS" register.
In your original example,
namespace _111_
{
public struct S
{
public int i1, i2;
}
public class C
{
public S s;
}
class Program
{
static void Main(string[] args)
{
C myClass = new C();
myClass.s.i1 = 999;
myClass.s.i2 = 888;
//at this point some memory must be assigned for
myClass.s.i1 & myClass.s.i2
//question: where this memory was taken from? From stack?
Or from heap?
}
}
}
The class C is allocated from the heap. Since struct S is a value type,
valuevalueit stored entirely in the class. The named components of S are also
thethetypes, so they are stored inside S:
Offset Value Code Reference Comments
0000 i1 base of class C, start of Struct S, int i1 is laid
down first by the compiler
0004 i2 int i2
0008 next object starts here
In code:
// myClass = allocate(C)
MOV EAX, 8 // C is 8 bytes long - GC_ALLOCATE will
return the offset in EAX as well
CALL GC_ALLOCATE // Have the garbage collector allocate 8 bytes of
storage
// The GC will add object
overhead, but these will be negative offsets from the returned address.
MOV [ESP], EAX // The variable myClass is on the stack at
offset 0 relative to the current stack frame BP
MOV EAX, myClass // myClass's address is actually stored on
ininstack; this instruction can be optimized out in this case
MOV DWORD PTR [EAX], 999 // myClass.s.i1 = 999
MOV DWORD PTR [EAX]+4, 888 // myClass.s.i2 = 888
First - I don't guarantee the syntax (I haven't written in x86 assembler
relativerelativeseveral years), but this is close enough for discussion.
Second - GC_ALLOCATE returns an offset into the heap. This is a "magic"
number that the memory management subsystem handles for you. It is
therethereto the value in register DS, which is set at application startup by the
memory manager. As you should be able to see from the assembler code,
call tocall tois no "boxing" of the variables. Boxing requires a rather expensive
example.example.determine an object's actual data type.
All Reference types are allocated in a similar method to the above
forforValue types are allocated by the compiler and don't require the call to
GC_ALLOCATE at run time.
Note the magic occurring in "GC_ALLOCATE" - it allocates memory from the
heap and returns an offset into the heap that is then used by later code
atatreference to the memory. The actual object size will be 8 bytes plus
garbage collector management buffer. The GC management buffer will be
andandnegative offets to the returned address, thus making the rest of the
compiler easier to write. If GC_ALLOCATE can't allocate the requested
memory, it calls GC_COLLECT, which runs compacts accessible heap memory
IfIfresets the allocation pointer for GC_ALLOCATE, which then tries again.
heap.heap.GC_ALLOCATE still can't allocate memory, it asks the OS to extend the
can'tcan'tThe OS returns the new heap size to GC_ALLOCATE. If GC_ALLOCATE still
allocate the requested memory, it throws an Out of Memory exception.
Mike Ober.
"Göran Andersson" <guffa@xxxxxxxxx> wrote in message
news:uvsw2UJhGHA.3424@xxxxxxxxxxxxxxxxxxxxxxx
Jon Skeet [C# MVP] wrote:variable.
Göran Andersson <guffa@xxxxxxxxx> wrote:
OK, I think the same. BUT! In other words myClass.s.i1 is already inYes, it's boxed. You are not storing the myClass.s.il variable in the
heap, yes? Now - what is boxing? Boxing is creating special packed
version of value-type in heap. In our case i1 ALREADY in heap. So...
object o = myClass.s.i1; //_not_ a boxing here?
???
object, you are storing a copy of the value of the myClass.s.il
No, there's no boxing going on there. Boxing is creating a separateYes, it is.
object on the heap for a value type. That's not happening here.
myClass.s.i1 is an integer variable. The value copied from that integer
variable can not be stored in the variable o, as it is an object
reference, so a separate object has to be created on the heap where the
value can be stored, and the reference to that object is stored in the
variable o.
.
- Prev by Date: .Net Remoting Exception
- Next by Date: Re: locking across multiple computers
- Previous by thread: .Net Remoting Exception
- Next by thread: Re: Struct inside class
- Index(es):
|
http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.framework/2006-06/msg00000.html
|
crawl-002
|
refinedweb
| 1,244
| 63.9
|
Building the Right Environment to Support AI, Machine Learning and Deep Learning
Watch→
Files have multiple properties and they are interesting to use. In fact, your own file system can be developed using them. Create a file named PATH.txt and try this program twice to see how the setReadOnly() method works. Explore and enjoy!
setReadOnly()
import java.io.File;
public class ReadOnlyFile {
public static void main(String[] args)
{
//File to choose
String fileNameWithPath = "C:/PATH.txt";
File file = new File(fileNameWithPath);
System.out.println("File is writeable: " + file.canWrite());
//If the file is writable, then making it read-only
if (file.canWrite())
{
System.out.println("File is writable. Making it read-only now");
file.setRead.
|
http://www.devx.com/DevX/tip-making-a-file-read-only-using-java.html
|
CC-MAIN-2020-10
|
refinedweb
| 116
| 54.69
|
6445/swapping-values
I have seen this code used to swap the values of two variables -
a, b = b, a
How does this work?
a,b = b,a
Here, python interprets the comma separated variables as tuples. The RHS is first evaluated as a tuple and then stored in memory. The LHS is then evaluated as a tuple and is assigned the values of the RHS. Hence, the net effect is that the values of the variables are swapped.
Actually in later versions of pandas this ...READ MORE
You can loop over the dictionary and ...READ MORE
Place your values in a tuple and ...READ MORE
import json
from pprint import pprint
with open('data.json') as ...READ MORE
You can use the enumerate function and ...READ MORE
if you google it you can find. ...READ MORE
Syntax :
list. count(value)
Code:
colors = ['red', 'green', ...READ MORE
can you give an example using a ...READ MORE
You can simply the built-in function in ...READ MORE
OR
Already have an account? Sign in.
|
https://www.edureka.co/community/6445/swapping-values
|
CC-MAIN-2020-05
|
refinedweb
| 173
| 86.4
|
We compare four numerical languages in a Vox blog post.
Section 3 of the blog post compares running times for the calculation of GARCH log-likelihood. It is a good representative example of the type of numerical problem we often encounter. Because the values at any given time t depend on values at t-1, this loop is not vectorisable. The GARCH(1,1) specification is
with its log-likelihood given by
For the purposes of our comparison, we are only concerned with the iterative calculation involved for the second term. Hence, the constant term on the left is ignored.
We coded up the log-likelihood calculation in the four languages and in C, keeping the code as similar as possible between languages. We then simulated a sample of size 10,000, loaded that in, and timed the calculation of the log-likelihood 1000 times (wall time), picking the lowest in each case.
The code can be downloaded here.
The fastest calculation is likely to be in C (or FORTRAN)
gcc -march=native -ffast-math -Ofast run.c double likelihood(double o, double a, double b, double h, double y2, int N){ double lik=0; for (int j=1;j<N;j++){ h = o+a*y2[j-1]+b*h; lik += log(h)+y2[j]/h; } return(lik); }
R does not really have a good just-in-time (JIT) compiler so it is likely slow.
likelihood =function(o,a,b,y2,h,N){ lik=0 for(i in 2:N){ h=o+a*y2[i-1]+b*h lik=lik+log(h)+y2[i]/h } return(lik) }
Python is likely to be quite slow,
def likelihood(hh,o,a,b,y2,N): lik = 0.0 h = hh for i in range(1,N): h=o+a*y2[i-1]+b*h lik += np.log(h) + y2[i]/h return(lik)
but will be significantly sped up by using Numba.
from numba import jit @jit def likelihood(hh,o,a,b,y2,N): lik = 0.0 h = hh for i in range(1,N): h=o+a*y2[i-1]+b*h lik += np.log(h) + y2[i]/h return(lik)
(Octave’s syntax was designed to be largely compatible with MATLAB, as an open-source alternative)
function lik = likelihood(o,a,b,h,y2,N) lik=0; for i = 2:N h=o+a*y2(i-1)+b*h; lik=lik+log(h)+y2(i)/h; end end
function likelihood(o,a,b,h,y2,N) local lik=0.0 for i in 2:N h = o+a*y2[i-1]+b*h lik += log(h)+y2[i]/h end return(lik) end
We tried two versions of Matlab (2015a, 2018a), Octave 4.4, R 3.5, Python 3.6 and two versions of Julia (0.6 and 0.7). All runtime results are presented relative to the fastest (C). All code ran on a late model iMac.
In a practical implementation, the log-likelihood calculation is only a part of the total time. We also timed the total execution time, including the starting and stopping of the software package, and compile time in the case of C. This was done in the terminal with a command like
time python run.py
C, even when including the compile time remains fastest, but now followed by R.
Generally, languages having poorer just-in-time compiling performed worse. However, there exist many tricks that can shorten processing time significantly. For instance, Python’s Numba package allows for efficient just-in-time compiling with minimal additional code — implementing Numba led to the calculation here being 200 times faster. Cython is also possible, but it is much more involved than Numba. For all the languages, embedding C code for the loop is possible, and would lead to performance improvements.
Julia’s performance is impressive, reflecting its advantage due to features like just-in-time compiling. Moreover, the difference between 0.6 and 0.7 reflects the progress made in the language’s development.
The results for Octave and MATLAB 2015a/2018a are reflective of the improvements MATLAB has made in terms of speeding up its code processing, in particular the introduction of JIT compiling in MATLAB’s execution engine from MATLAB 2015b onward.
One can of course bypass many of those issues by just coding up the GARCH likelihood in C, including the optimisation, and calling that within any of the languages. This is indeed what we do in our own work via Rccp.
|
https://www.modelsandrisk.org/appendix/speed/
|
CC-MAIN-2019-09
|
refinedweb
| 750
| 56.45
|
Control: tags -1 - moreinfo > Are you sure you are seening the same bug? AFAICT, the > > mnt: Fix fs_fully_visible to verify the root directory is visible > > is as well included in the 3.16.7-ckt17-1 upload.
Advertising
Oh! That's a very good point indeed, thank you. I hadn't noticed. I tried 3.16.7-ckt17-1: still get EPERM when trying to mount /proc on a user namespace. For reference, I'm seeing the bug when using vagga, a tool to manage user namespaces. The bug seems awfully similar to. I'm going to leave a note in that bug pointing to here. I have no idea what's going on, but the symptoms are the same. Thanks! -d
|
https://www.mail-archive.com/debian-bugs-dist@lists.debian.org/msg1462280.html
|
CC-MAIN-2016-44
|
refinedweb
| 122
| 77.33
|
Subseries: Environmental Science
Series Editors: R. Allan • U. Förstner • W. Salomons
Michel De Lara · Luc Doyen
Sustainable Management
of Natural Resources
Mathematical Models and Methods
Michel De Lara Luc Doyen
Universite Paris-Est, CERMICS Centre National de la Recherche Scientifique
6-8 avenue Blaise Pascal CERSP, Muséum National d’Histoire Naturelle
77455 Marne la Vallee Cedex 2 55 rue Buffon
France France 75005 Paris
delara@cermics.enpc.fr lucdoyen@mnhn.fr
ISBN: 978-3-540-79073-0 e-ISBN: 978-3-540-79074-7
Environmental Science and Engineering ISSN: 1863-5520
Library of Congress Control Number: 2008928724
c 2008
9 8 7 6 5 4 3 2 1
springer.com
Preface
Nowadays, environmental issues including air and water pollution, climate
change, overexploitation of marine ecosystems, exhaustion of fossil resources,
conservation of biodiversity are receiving major attention from the public,
stakeholders and scholars from the local to the planetary scales. It is now
clearly recognized that human activities yield major ecological and environ-
mental stresses with irreversible loss of species, destruction of habitat or cli-
mate catastrophes as the most dramatic examples of their effects. In fact, these
anthropogenic activities impact not only the states and dynamics of natural
resources and ecosystems but also alter human health, well-being, welfare and
economic wealth since these resources are support features for human life.
The numerous outputs furnished by nature include direct goods such as food,
drugs, energy along with indirect services such as the carbon cycle, the water
cycle and pollination, to cite but a few. Hence, the various ecological changes
our world is undergoing draw into question our ability to sustain economic
production, wealth and the evolution of technology by taking natural systems
into account.
The concept of “sustainable development” covers such concerns, although
no universal consensus exists about this notion. Sustainable development em-
phasizes the need to organize and control the dynamics and the complex in-
teractions between man, production activities, and natural resources in order
to promote their coexistence and their common evolution. It points out the
importance of studying the interfaces between society and nature, and espe-
cially the coupling between economics and ecology. It induces interdisciplinary
scientific research for the assessment, the conservation and the management
of natural resources.
This monograph, Sustainable Management of Natural Resources, Mathe-
matical Models and Methods, exhibits and develops quantitative and formal
links between issues in sustainable development, decisions and precautionary
problems in the management of natural resources. The mathematical and nu-
merical models and methods rely on dynamical systems and on control theory.
VI Preface
The basic concerns taken into account include management of fisheries, agri-
culture, biodiversity, exhaustible resources and pollution.
This book aims at reconciling economic and ecological dimensions through
a common modeling framework to cope with environmental management prob-
lems from a perspective of sustainability. Particular attention is paid to multi-
criteria issues and intergenerational equity.
Regarding the interdisciplinary goals, the models and methods that we
present are restricted to the framework of discrete time dynamics in order to
simplify the mathematical content. This approach allows for a direct entry
into ecology through life-cycles, age classes and meta-population models. In
economics, such a discrete time dynamic approach favors a straightforward
account of the framework of decision-making under uncertainty. In the same
vein, particular attention has been given to exhibiting numerous examples,
together with many figures and associated computer programs (written in
Scilab, a free scientific software). The main approaches presented in the book
are equilibrium and stability, viability and invariance, intertemporal optimal-
ity ranging from discounted utilitarian to Rawlsian criteria. For these meth-
ods, both deterministic, stochastic and robust frameworks are examined. The
case of imperfect information is also introduced at the end. The book mixes
well known material and applications, with new insights, especially from via-
bility and robust analysis.
This book targets researchers, university lecturers and students in ecology,
economics and mathematics interested in interdisciplinary modeling related
to sustainable development and management of natural resources. It is drawn
from teachings given during several interdisciplinary French training sessions
dealing with environmental economics, ecology, conservation biology and en-
gineering. It is also the product of numerous scientific contacts made possible
by the support of French scientific programs: GDR COREV (Groupement de
recherche contrôle des ressources vivantes), ACI Ecologie quantitative, IFB-
GICC (Institut français de la biodiversité - Gestion et impacts changement cli-
matique), ACI MEDD (Modélisation économique du développement durable),
ANR Biodiversité (Agence nationale de la recherche).
We are grateful to our institutions CNRS (Centre national de la recherche
scientifique) and ENPC (École nationale des ponts et chaussées) for provid-
ing us with shelter, financial support and an intellectual environment, thus
displaying the conditions for the development of our scientific work within
the framework of extensive scientific freedom. Such freedom has allowed us to
explore some unusual or unused roads.
The contribution of C. Lobry in the development of the French network
COREV (Outils et modèles de l’automatique dans l’étude de la dynamique
des écosystèmes et du contrôle des ressources renouvelables) comprising biol-
ogists and mathematicians is important. We take this opportunity to thank
him and express our gratitude for so many interesting scientific discussions.
At INRIA (Institut national de recherche en informatique et automatique)
in Sophia-Antipolis, J.-L. Gouzé and his collaborators have been active in
we are grateful to O. It is a pleasure to thank our col- leagues there for the pleasant conditions of work. as well as new colleagues in Peru now contributing to such development.-P. Preface VII developing research and continue to influence our ideas on the articulation of ecology. mathematics and the framework of dynamic systems and control theory. Regarding biodiversity management. . Rotillon and K. who participated in the CEREMADE (Centre De Recherche en Mathématiques de la Décision) and CRVJC (Centre de Recherche Viabilité-Jeux-Contrôle) who significantly influenced our work on control problems and mathematical modeling and decision-making methods: D. Weber at IFB (Institut français de la biodiversité) has constituted a major motivation. At CIRED (Centre international de recherche sur l’environnement et le développement). Hourcade for all we learnt and understood through our contact with them regarding environmen- tal economics and the importance of action timing and uncertainties. Godard and J.-C. Gabay deserves special acknowledgment regard- ing natural resource issues. it is a pleasure to thank F. CERMICS (Centre d’enseignement et de recherche en mathématiques et calcul scientifique) hosts the SOWG team (Sys- tems and Optimisation Working Group). we are quite indebted to the team of mathematicians and automaticians at CAS (Centre automatique et systèmes) who developed a very creative en- vironment for exploring mathematical methods devoted to real life control problems. Our colleagues J. Rochet and O. Lévine.-P. At École nationale supérieure des mines de Paris. At the Université Paris-Dauphine. Thébaud at IFREMER (Institut français de recherche pour l’exploitation de la mer) for their active investment in im- porting control methods in the field. the stimulating interest and support shown for our work and modeling activities by J. Our friend and col- league J. A nice discussion with J. Mur- ray was influential in devoting substantial content to uncertainty issues. For the mod- eling in fisheries management and marine biodiversity. we are much indebted to the very active team of mathematicians headed by J. and his legitimate preoccupation with developing methods adapted and pertinent to given applied problems. Pereau. M.-C. Planes (CNRS and École pratique des hautes études) has always been fruitful and pleasant. Aubin. G. At ENPC. The CMM (Centro de Modelamiento Matemático) in Santiago de Chile has efficiently supported the development of an activity in mathematical methods for the management of natural resources. Schubert deserve special thanks for all the sound advice and challenging discussions concerning environmental economics and bio-economics to which this book owes so much. granting freedom to explore applied paths in the mathematics of sustainable management.-J. We are particularly grateful to the influence of J. The contributions of C. D. Blanchard. The cooperation with S. We also thank J. Béné (World Fish Center) are major and scattered throughout several parts of this monograph. Chancelier deserves a special mention for his readiness in helping us write Scilab codes and develop practical works available over the internet. Ferraris at IRD (Institut de recherche pour le développement).
Gilotte. Bouzidi. T.-P. M. Trigalo. Sebaoun. At ENPC. J. A. At MNHN (Muséum national d’histoire naturelle). Le Van. Tichit and F. We thank them for helping us explore new tracks and developing Scilab codes.-E. J. encouraged and helped the development of interdisciplinary activities are too numerous to be thanked individually. a very special thanks to M. who have allowed. C. I. Without the enthusiasm and work of young Master’s students like F. T. Mahé. Barbault and D. we want to point out the support of R. L. J. Those at the Ministère de l’Équipement and at the Ministère de l’Environnement. Their interest in dy- namic control and co-viability approaches for the management of biodiversity was very helpful. the CEREVE (Centre d’enseignement et de recherche eau ville en- vironnement) has been a laboratory for confronting environmental problems and mathematical methods with various researchers. Irisson and V. A. Ambrosi.VIII Preface At INRA (Institut national de recherche en agriculture). P. Rapaport deserves special mention for his long investment in control methods in the field of renewable resources management. Bourgoin. Ton That. Léger for fruitful collaboration despite the com- plexity of agro-environmental topics. this monograph would not have been the same. Michel De Lara April 2008 Luc Doyen . Guerbois. Sbai. Lebreton. A. Druesne. A. Guilbaud. Dun. M. P. Daghiri. C. and espe- cially within the Department Écologie et gestion de la biodiversité . M. Couvet. Paris. Rabbat. L. Bosseau.-O. Sabatier. At CEMAGREF. Barnier. Terreaux. R. Martinet should be emphasized. The very active and fruitful role played by young PhD and postdoc re- searchers such as P. L. Maure. C. we thank our colleague J. Dumas. M.
. . .1 Exploitation of an exhaustible resource . common property. . . 38 2. . . . . . . . . 47 3 Equilibrium and stability . . . . private property. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 2. . . . . . . . . . . . . . . . . . . . . . . .4 Stability of a stationary open loop equilibrium state . . . . . . . . . . . . 27 2. . . . . . . . . . . . .7 Economic growth with an exhaustible natural resource . . . . . . . .11 Decision tree and the “curse of the dimensionality” . . . . . .Contents 1 Introduction . . . . . . . . . 52 3. . . . . . . . . . . . . .10 Open versus closed loop decisions . . . . . . . . . .2 Some examples of equilibria . . . . . . . . . . . . . . . . . . . . . . . . . . 68 References . . . . . . . . . . 17 2. . . . . . . . . . . . . . . . 51 3. . . . . . . . . . . . . . . . . . . 35 2. . . . . . . . . 11 2 Sequential decision models . . . . . . . . . .4 A trophic web and sustainable use values . . . . 71 . . . . . . . instability and extinction . . 63 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . open access equilibria . . . . 24 2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 2. . 52 3.5 What about stability for MSE. . . . . . . . . . .9 State space mathematical formulation . . . . 66 3. . . . . . . . . . . . . . . .5 A forestry management model . . . . . . . . . . . . . . . . . . . . . . . . . 46 References . . . . . . . . . . 44 2. . . . . . . . . . . . . . . . . . . . . .3 Maximum sustainable yield. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 2. . . .3 Mitigation policies for carbon dioxyde emissions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6 Open access. . . . . . . . . . . 37 2. . . .8 An exploited metapopulation and protected area . PPE and CPE? . . . . . . .7 Competition for a resource: coexistence vs exclusion . 31 2. . . . . . . . . . . . . . . . . . . . . . . .2 Assessment and management of a renewable resource . . 1 References . . . . . .1 Equilibrium states and decisions . . . . . . . . . . 55 3. . . . . . . . . . . . 60 3.6 A single species age-classified model of fishing .
. . . . . . . . . . . .2 Resource management examples under viability constraints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162 6. . . . . . . . 76 4. . . . . . . . .9 Viable forestry management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80 4. . 131 5. . . . 148 References . . .1 Problem formulation .2 Decisions. . . 108 5. . . . . . . . . . 95 4. . . . . . . . . . . . . . . .8 The precautionary approach in fisheries management . .5 Management of multi-species harvests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122 5. . . . . . . . . . . . . . . .5 Over-exploitation. . . . . . . . . . . . . . 73 4. . . . . .6 A cost-effective approach to CO2 mitigation . . . . . solution map and feedback strategies . . . .10 Invariance or strong viability . . . . . . . . 144 5. . . . . . . . .1 The viability problem . . . . . . . . . 151 6 Sequential decisions under uncertainty . . . . . . . . . . . .6 Robust agricultural land-use and diversification . 141 5.2 Dynamic programming for the additive payoff case . . . . . 112 5. . . . . . . . . . . . . .3 Intergenerational equity for a renewable resource . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .12 Where conservation is optimal . . . . .X Contents 4 Viable sequential decisions . . . . . . . . . . . . . . . . .7 Discount factor and extraction path of an open pit mine . . . . . . . . . . . . . . . . . . . . . . . . 107 5. . . . . . . . 161 6. . . . . 83 4. . . . . . . . .15 Maximin for an exhaustible resource . . . . . . . . . . . . . . . 153 6. . . . . . . . . . . . . . . . . 140 5. 160 6. . . . . . . . . . . . . . . . . . . . . . 134 5. . . . . . 89 4. . . . . . . . . . . . . . . . . . . . . . .5 Viable control of an invasive species . . . . . . . . . . . . . . . .6 Viable greenhouse gas mitigation . . . . . . . . . . . . . . . . . . . . . . . . . .3 Probabilistic assumptions and expected value . . . . . . 100 References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .10 Optimal management of a renewable resource . . . . 136 5. . . . . . . . . . . . . . 105 5 Optimal sequential decisions . . . . . . . . . . . .4 Optimal depletion of an exhaustible resource . . . . . . . . . . . . . . . . .11 The Green Golden rule approach . . .13 Chichilnisky approach for exhaustible resources . . . . . . . . . . . . . . . . . . . 169 . .1 Uncertain dynamic control system . . . . . . . . . . . . 157 6. . . . . . . . . . .8 Pontryaguin’s maximum principle for the additive case .7 Mitigation policies for uncertain carbon dioxyde emissions . . . . . . . . . . . . . . . . . . . . . . . .7 A bioeconomic precautionary threshold . . . . . . . . .4 Decision criteria under uncertainty . . . . . . . . . . . . . . . . . . . . 117 5. 125 5. . . extinction and inequity . 139 5. . . 158 6. . . . . . . . . . . . . . . . . . . . . . . . . . 98 4. . . . . . . . . . . . . . . . . . . .14 The “maximin” approach . . . . . . . . . . . . 115 5.8 Economic growth with an exhaustible natural resource . . . . . . . .4 Viability in the autonomous case . . . . . . . . . . . . . . . . . . . . . 75 4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 4. . . . . . . . . 154 6. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163 6. . . . . . . . . . . . 119 5. .3 The viability kernel . . . . 90 4. . . . . . . . . . . .9 Hotelling rule . . . 166 References . . . . . . . . . . .
. . . . . . . . . . .6 Mathematical proofs of Chap. . . . . . . . . . . . . . . . .3 Mathematical proofs of Chap. . . . . . . . . . . . . . . . . . . . . . . . . . 210 8. . . . . . . . . . . . . . . . . . . . . . . . 200 8. . . . . . . . . . . . . . . . . . . . . . . . . . . .7 Stochastic management of a renewable resource . . . . . . 225 9. . . . 193 8. 9 . . . . . . 248 A. . . . . . . . . . . . . . . . . . . . . 205 8. . . . . . . . . . . . . . . . . . . . . . . .2 Mathematical proofs of Chap.6 From PVA to CVA . . . . . . . . . . . . . . . . . . . . 196 8. . . . . . . . . . . . . . . . .6 Precautionary effect in climate change mitigation . . . . . . . . . . . . . . . . . . . . . 252 A. . . . . . . . . . . . 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5 Monotone variation of the value of information and precautionary effect . . . .3 The robust additive payoff case . . . . . . . . . . . . . . . . . . . . . . . . . . . 221 9. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259 Index . 8 . . . . . . . . . 172 7.1 Dynamics. 237 A. . 231 9. . feedbacks and criteria . . Contents XI 7 Robust and stochastic viability . . . . . . . .1 Intertemporal decision problem with imperfect observation . . .9 Cost-effectiveness of grazing and bird community management in farmland . . . . . . . . . . . . . . 221 9. . . . . . . . . . . . 175 7. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261 . . . . . . . . .1 Mathematical proofs of Chap. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195 8. . . . . . . . . . . . . . . . . . . . . . . . . . . 185 References . . 191 8 Robust and stochastic optimization .2 The robust viability problem .4 Information effect in climate change mitigation . .8 Optimal expected land-use and specialization . . . . . . . . 253 A. . . . . . . . . . . . . . . . 7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233 References . . . . . . . . . . . . . . . . . . . . . . . .2 The robust optimality problem . . . . .4 Sustainable management of marine ecosystems through protected areas: a coral reef case study . . . . . .5 The robust “maximin” approach .4 Robust harvest of a renewable resource over two periods . . . . . . . . . . . . . . . . . . 201 8. . . . . . . . . . . . . . . . . . . . . . . . . constraints. . . . . . . . . . . . . . . . . . . . . . . . . . 172 7. . .6 The stochastic optimality problem . . . . 212 References . . . . . . . . . . . . . . . . . . . . . . . 244 A. . . . . . . . . . . . . . . . . . . . . . . .5 Mathematical proofs of Chap. . . . . . . . . 194 8. . . . . .3 Robust agricultural land-use and diversification . 254 References . . . . . . 183 7. . . . 225 9. . . . . . . . . . 229 9. . . . . . . . . . . . . 178 7. . . . . . . . . . Mathematical Proofs . . .5 The stochastic viability problem . . . . . . 171 7. . . . . . . . . . . . . . . 237 A. .1 The uncertain viability problem . . . . . . . . . . . . . . . . . . 235 A Appendix. . . . . . . . . . . . . . . . . . . . . . .3 Precautionary catches . . . . . . . .7 Mathematical proofs of Chap. . . . . . . . . . . . . . . . . . . . . . . .2 Value of information . . . . . 239 A. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 . . . . . . . .4 Robust and stochastic dynamic programming equations . . . . . . . . . . . . . . . . . . . . . . . . 3 . . . . . . . . . . . . . . . . . . 219 9 Sequential decision under imperfect information . . . . . . . . . . . . . . . . . . . . . . 199 8. . . . . . . . . . . . . .
We propose mathematical ap- proaches centered around dynamical systems and control theory to formalize and tackle such problems. produc- tion activities and natural resources. conservation and management of natural resources are induced by such preoccupations. and especially the coupling between economics and ecology. . have fostered public suspicion of the evolution of technology and economic growth while encouraging doubts about the ability of public policies to handle such problems in time. preservation of biodiversity and water resource management con- stitute important public preoccupations at the local. Interdisciplinary scientific studies and research into the assess- ment. Nowadays. state and even world scales. pollution control. degradation and risks affecting human health or the environ- ment. The problems confronted in sustainable management share certain charac- teristic features: decisions must be taken throughout time and involve systems marked by complex dynamics and uncertainties.1 Introduction Over the past few decades. Environmental management issues We review the main environmental management issues before focusing on the notions of sustainable development and the precautionary principle. The sus- tainable development concept and the precautionary principle both came on the scene in this context. Crises. climate change. along with the permanency of poverty. There is a need to study the interfaces between society and nature. environmental concerns have received growing attention. These concepts lead us to question the means of organizing and control- ling the development and complex interactions between man. over-exploitation of fisheries. trade.
Without any regulation. 38. In 1972. renewable resources are regulated using quantity or price instruments. 8] as a central element of future resource management. Uncertainty includes both scientific uncertainties related to resource dynamics or assess- ments and the uncontrollability of catches. The difficulties in the usual management of renewable resources have led some recent works to advocate the use of ecosystemic approaches [5. Among the many factors that contribute to failure in regulating renewable resources. Renewable resources Renewable resources are under extreme pressure worldwide despite efforts to design better regulation in terms of economic and/or control instruments and measures of stocks and catches. 39] have developed economic models to assess how the presence of an exhaustible resource might limit economic growth. both uncertainty and complexity play significant roles. 1992). 19. In the Convention on Biological Diversity (Rio de Janeiro. 7. The Food and Agricultural Organization [15] estimates for instance that. 15-18% are over- exploited and 9-10% have been depleted or are recovering from depletion. arguing that unlimited economic growth is impossible because of the exhaustibility of some resources. In this context. conservation and management of biodiversity is at stake. at present. Moreover the question of intergenerational equity appears as a central point in such works. Biodiversity More generally. the Club of Rome published a famous report. 41]. and especially for marine resources. limited entries or protected areas while others rely on taxing of catches or opera- tions [6. To mitigate pressure on specific resources and prevent over-exploitation. problems raised by non-compliance of agents or by by-catch related to multi-species management are important. These works have pointed out that substitutability features of natural resources are decisive in a production sys- tem economy. 20. 47-50% of marine fish stocks are fully exploited. the preservation. This framework aims at capturing a major part of the complexity of the systems in a relevant way encompassing. spatialization and uncertainty. . “The Limits to Growth” [28]. trophic webs. numerous economists [10. habitats. The continued decline in stocks worldwide has raised serious questions about the effectiveness and sustainability of such policies for the management of renewable resources. Some systems of management are thus based on quotas. in particular.2 1 Introduction Exhaustible resources One of the main initial environmental debates deals with the use and man- agement of exhaustible resource such as coal and oil. it is likely that numerous stocks will be further depleted or become extinct as long as over-exploitation remains profitable for individual agents. In response to this position.
economic and technological uncertainties. Pollution Pollution problems concerning water. 4. At the global scale. pro- tected areas or agro-environmental measures and actions are receiving growing attention to enhance biodiversity and the habitats which support it. stability.6% of vertebrates. Particular attention has been paid to stabilizing ghg concentration [23]. many efforts have been directed toward evaluating policies to control the atmospheric ac- cumulation of greenhouse gases (ghg). existence value (intrinsic value of nature) and option values (potential future use). . viability and productivity of ecosystems [24. especially carbon dioxide (co2 ). air. inter alia. if not the most. 33]? How does biodiversity promote the functioning. One main focus of biodiversity economics and management is to establish an economic basis for preservation by pointing out the advantages it procures. These discussions emphasize the need to take into account scientific. land or food occur at different scales depending on whether we are looking at local or larger areas. some estimates [27] indicate that endangered species encompass 11% of plants. marine and other aquatic ecosystems and the ecological complexes of which they are part. intense debate and extensive analyses still refer to both the timing and mag- nitude of emission mitigation decisions and policies along with the choice be- tween transferable permits (to emit ghg) or taxes as being relevant economic instruments for achieving such mitigation goals while maintaining economic growth. this includes diversity within species. Consequently. . Many questions arise. Instruments for the recovery and protection of ecosystems. little doubt now remains that the Earth’s biodiversity is de- clining [26]. . Population Viability Analysis [29] is a specific quantitative method used for conservation purposes. there is growing interest in assessing the value and benefit of biological diversity. How can biodiversity be measured [2. ecosystem ser- vices (carbon and water cycle. For instance. The concept of total economic value makes a distinction between use values (production and consumption). pollination. However. This is a difficult task because of the complexity of the systems under question and the non monetary values at stake. 24% of mammals and 11% of birds worldwide. between species and of ecosystems”. important issue facing the international community. Over the past decade. Within this context. 26]? What are the mechanisms responsible for perturbations ? How can the conse- quences of the erosion of biodiversity be evaluated at the level of society [4]? Extinction is a natural phenomenon that is part of the evolutionary cycle of species. terrestrial. viable land use management and regulation of exploited ecosystems refer to conserva- tion biology and bioeconomics. ). Anthropic activities and man’s development is a major cause of resource depletion and weakened habitat. However. climate change has now emerged as one. 1 Introduction 3 biodiversity is defined as “the variability among living organisms from all sources including.
” The debate currently focuses on the substitutability between the economy and the environment or between “natural capital” and “manufactured capital” – a debate captured in terms of “weak” versus “strong” sustainability. Precautionary principle Dangers. In particular. as listed by [32].and intergenerational equity. the basic concerns of sustainability are how to reconcile environmental. 1992) and the Kyoto protocol (Kyoto. the term sustainable development. the United Na- tions Framework Convention on Climate Change (Rio de Janeiro. these different points of view refer to the apparent antagonism between pre- occupations of most natural scientists – concerned with survival and viability questions – and preoccupations of economists – more motivated with effi- ciency and optimality. “Where there are threats of serious or irreversible damage. The precautionary principle first appeared in such a context. Such a concept questions whether humans are “a part of” or “apart from” nature. From the biological and ecological viewpoint. degradation and catastrophes affecting the environment or human health encourage doubt as to the ability of public policies to face such problems in time. the 15th Principle of the 1992 Rio Declaration on Environment and Development defines precaution by saying. 1992). At any rate. defined in the so-called Brundt- land report Our Common Future [40]. social and economic requirements within the perspectivies of intra. In economics. Their numbers reveal the large-scale mobilization of scientific and intellectual communities around this question and the economic and polit- ical interests at stake. Beyond their opposite assumptions. conferences and public decisions such as the Convention on Biological Diversity (Rio de Janeiro. For instance.4 1 Introduction Sustainable development Since 1987. the World Summit on Sustainable Devel- opment (Johannesburg 2002). lack of full scientific certainty shall not be used as a reason for postponing cost-effective measures to prevent environmental degradation”. has been used to articulate all previ- ous concerns. sustainability is gener- ally associated with a protection perspective. it is advanced by those who favor accounting for natural resources. Although the Brundtland report has received extensive agreement – and many projects. nowadays refer to this general framework – the meaning of sustainability remains controversial. The World Commission on Environment and Development thus called for a “form of sustainable development which meets the needs of the present without compromising the ability of future generations to meet their own needs”. . Many definitions of sustainable development have been introduced. 1997). it examines how economic instruments like markets. conservation or “sustainable use” of natural resources. crises. It is taken to mean alter- natively preservation. taxes or quotas are appropriate to tackling so called “environmental externalities.
to aid in finding solutions to environmental problems. modeling approaches and methods within an interdisciplinary and integrated perspective. their data. It is therefore vague and difficult to craft into workable policies. 1 Introduction 5 Yet there is no universal precautionary principle and Sandin [34] enumer- ates nineteen different definitions. the precautionary principle does not clearly specify what changes one can expect in the relations between science and decision-making. This observation raises at least two main questions. To quote but a few: at what level should co2 concentration be stabilized in the atmosphere? 450 ppm? 550 ppm? 650 ppm? What should the level of a carbon tax be? At what date should the co2 abatements start? And according to what schedule? What indicators and prices should be used for bio- diversity? What viability thresholds should be considered for bird population sustainability? What harvesting quota levels for cod. attempts to address these issues of sustainability and natural resource management using mathematical and numerical modeling appear relevant. and to mobilize the different specialized disciplines. we observe that concepts such as sustainable development and precaution – initially conceived to guide the action – are not directly operational and do not mix well in any obvious manner. In such a context. Unfortunately. hake and salmon? What . amplitudes and tim- ing of decisions. Why does indecision exist a priori ? How can such indeci- sion be overcome? At this stage. costs and benefit values. decisions. the contrary of an abstention rule. or how to translate the requirements of precaution into operating standards. What seems to be characteristic of the precaution context is that we face both ex ante indecision and indeterminacy. the impact of the resolution of uncertainties on the timing of action appears as a touchstone of precaution. qualitative and quantitative analyzes are not easy to perform on scientific grounds. Decision-making perspective Actions. He argues that the principle calls for prompt protective action rather than delay of prevention until scientific uncertainty is resolved. Mathematical and numerical modeling From this brief panorama of numerous issues related to the management of natural resources. Such is the purpose of the present textbook. At this stage. regulations and controls often have to rely on quantitative contexts and numerical information as divers as effectiveness. This fact may be damaging both for decision-making support and production of knowledge in the environmental field. precautionary indicators and reference points. however. Graham [17] attempts to summarize the ideas and associates the principle with a “better safe than sorry” stance. We believe that there is room for some mathematical concepts and methods to formulate decisions. The precautionary principle is.
required for the management of natural resources. two modeling orientations may be followed. social and economic objectives may be contradictory. difficulties may occur in defining common scales of time or space. Unfortunately. the models of each scientific area do not combine in a straightforward man- ner. How may compromises be found? How can one build decision rules and indicators based on multi- ple observations and/or criteria? What should the coordination mechanism to implement heterogeneous agents exploiting natural resources be? We hope that this book favors and facilitates links between different scientific fields. numerical simulations are generally the best way to display quantitative or qualitative results.6 1 Introduction size reserves will assure the conservation of elephant species in Africa and where should they be located? What land-use and degree of intensification is appropriate for agro-environmental policies in Europe? How high should compensation payments be for the biodiversity impact and damage caused by development projects? In meeting such objectives of decision-making support. These models are more or less sophisticated and complex. which allows for very general results and a better understanding of the mechanisms under concern. Interdisciplinary perspective Many researchers in ecology. Integrated models are. . simple nu- merical code can be developed. stylized or global mod- els. reference points and strategies. Such an approach may be very demanding and time consuming because such a model depends on a lot of parameters or mecha- nisms that may be uncertain or unknown. They are very dependent upon the calibration and estimation of parameters and sensitivity analysis is necessary to convey robust assertions. solve and analyze their scientific problems. biology. Another path for modeling to follow consists in constructing a low- dimensional model representing the major features and processes of the com- plex problem. In this case. One may speak of compact. One class of models aims at capturing the large-scale complexity of the problems under concern. The results of the compact models should guide the analysis of more extended models in order to avoid sinking into a quagmire of complexity created by the numerous parameters of the model. Furthermore. economics and environment use math- ematical models to study. however. the addition of several models extends the dimensions of the problem and makes it complicated or impossible to solve. Moreover. aggregated. Using this small model and code to elaborate a more complex code with numerical simulations is certainly the second step. For instance. on this basis. Ecological. an initial. Their mathematical study may be partly performed. It can also serve directly in decision-making by providing relevant indicators.
accumulation effects and intertemporal externalities are important points to deal with. viability. that is to say the temporal dimension of the problem. On the basis of the previous considerations. is to remain at a safe or satisfying state. Cost-benefit and cost-effectiveness approaches are related to intertempo- ral optimal control [6. by referring to regulation and prevention. The sustainability perspective combined with in- tergenerational equity thus highlights the role played by the time horizon. Hence it mobilizes a huge part of the scientific research effort. More specifically. A relevant situation is thus steady state. although quantitative informa- tion. damage. The basic idea encompassed in the equilibrium approach. . 1 Introduction 7 Major mathematical material The collection and analysis of data is of major interest for decision-making support and modeling in the concerned fields. although stability allows for some dynamical processes around the equilibria. Temporal and dynamic considerations First of all. invariance and effectiveness for- mulations. cost-effectiveness. Nevertheless. admissibility and feasibility along the time line in opposition to dangers. the sustainability and precautionary approaches are clearly decisional or control problems where the timing of action is of utmost importance. natural resource management and pre- cautionary principles in some formal way are: temporal and dynamic con- siderations. Indeed. the dif- ferent modeling approaches dealing with such issues can be classified into equilibrium. as in the max- imum sustainable yield for fisheries of Gordon and Schaefer [16. Another important feature of sustainability and precautionary actions re- lies on safety. Decisions. respectively. values and data are needed and indispensable. intertemporal optimality and via- bility as concepts which may shed interesting light on sustainable decision requirements. 35]. we want to insist on the importance of mobilizing concepts and methods to formalize decisional problems. many works clearly point out the dynamical features involved in these problems. we consider that the basic elements to combine sustainability. crises or irreversibility. we present equilibrium. it is clear that the problems of sustainable management are in- trinsically dynamical . 9] and optimal control under constraints. By linking precaution with effects of irre- versibility and flexibility. decision criteria and constraints and uncertainty management. At this stage. cost-benefit. These dynamics are generally nonlinear (the logistic dynamics in biological modeling being a first step from linear to nonlinear growth models). constraints & criteria Secondly. delays.
The safe minimum standards (sms) [31]. by dealing with ambi- guity. Such a framework makes it possible to cover the important issues mentioned above. more exotic approaches regarding sustain- ability include Maximin and Chichilnisky criteria [21]. the simple fact of exhibiting and distinguishing between . there is risk. it clearly accounts for dynamical mechanisms. Uncertainty management Thirdly. 12] indicate that tolerable margins should be maintained or reached.8 1 Introduction In the cost-benefit case. In the optimal control framework. 14]. the danger might be taken into account through a so-called monetary damage function that penalizes the intertemporal decision criteria. although. 25. there are cases presenting ambiguity or uncertainty with unknown probability or with no probability at all. Content of the textbook In this textbook. pessimistic. the issue of uncertainty is also fundamental in environmental man- agement problems [1. First. State constraints or targets are thus a basic issue. Most precaution and environmental problems involve ambiguity in the sense of controversies. Second. 11. tolerable window approach (TWA) [36]. irreversibility generally means decision and control constraints. In contrast. To deal with risk uncertainty. 22. On the one hand. 30. Similarly. which is an event with known probability. the cost-effectiveness approach aims at minimizing in- tertemporal costs while achieving to maintain damages under safety bounds. the usual approach is based on the expected value of utility or cost-benefits while the general method is termed stochastic control. policy makers have created a process called risk assessment which can be useful when the probability of an outcome is known from experience and statistics. population viability analysis (pva) [29]. In the framework of dynamic decision-making under uncertainty. 13. On the other hand. total risk-averse or guaranteed and robust control frameworks may also shed interesting light. the present textbook proposes to introduce ambiguity through the use of “total” uncertainty and robust control. beliefs and irreducible scientific uncertainties. we advocate that concepts and methods from control theory of dynamical systems may contribute to clarifying. multi-prior models may appear relevant alternatives for the precaution issue. analyzing and providing mathematical and/or numerical tools for theoretical and applied environmen- tal decision-making problems. We shall focus on two kinds of uncertainty. worst-case. viability and invariance ap- proaches [3. in this context. The so-called irreversibility constraints in the referenced works and their influence also emphasize the role played by constraints in these problems. Maximin is of interest for intergenerational equity issues while Chichilnisky framework offers insights about the trade-off between future and present preferences. In this sense. As a first step in such directions.
precaution and sustainability. Many practical works pre- senting management cases with Scilab computer programs can be found on the internet at the address. the different fundamental methods of control theory – that include stability. results and tech- niques. Furthermore. For more complex models. the integration of coordination mechanism. This option helps both to “grasp” the situation from a control-theoretical point of view and also to make easier both mathematical and numerical resolution. calibration and identification pro- cesses constitute another important lack. both deterministic. They may help the comprehension and serve for teaching. the models and methods that we present are restricted to the framework of discrete time dynamics. In economics. estimation. This should favor an easy and faster understanding of the main ideas. planning and manage- ment issues. The emphasis in this book is not on building dynamical models. aggregated models with few dimensions. age classes and meta-population models. This is not because we do not aim at tackling such complex issues but our approach is rather to start up with clear models and methods before climbing higher mountains. in order to simplify the mathematical content. we only pave the way for their study by providing examples of Scilab code in this perspective. Similarly. For these methods. invariance and optimality – encompass the main ele- ments of normative approaches for natural resource management. By using this approach. global.fr/~delara/BookSustain. Another major interest of control theory is to focus on decision. such a discrete time dynamics ap- proach favors a straightforward account of the framework of decision under uncertainty. we avoid the in- troduction of too many sophisticated mathematics and notations. It should enable direct entry into ecology through life-cycle. we are aware that a lot of frustration may appear when read- ing this book because many important topics are not handled in depth. multi-agents and game theory is an important issue for environmental decisions and planning which is not directly developed here. intertemporal optimality (going from discounted utilitarian to Rawlsian criteria). Approaches presented in the book are equilibrium and stability. together with many figures and associated computer pro- grams (written in Scilab. a free scientific software). but on the formalization of decisional issues. In the same vein. 18] for useful warnings and to [37] for a mathematical point of view.enpc. uncertainties and observations among all variables of a sys- tem is already a structuring option in the elicitation of many models. stochastic and . we shall rely on existing models without commenting them. hence taking distance with complex- ity in the first place. We are aware of ongoing debate as to the validity and the empirical value of commonly used models. These concerns represent challenging perspec- tives. Moreover. Still. Regarding the interdisciplinary goal. we had to set limits to our work. controls. particular attention has been given to exhibiting numerous examples. We must confess that most of our examples are rather compact. the use of data. For instance. 1 Introduction 9 states. For this reason. viabil- ity and invariance. We send the reader to [42.
The stochastic and robust dynamic programming methods are pre- sented for viability purposes in Chap. In Chap. All the numerical ma- terial may be found in the form of Scilab codes on the internet site. introducing the dynamic programming method. we introduce the natu- ral extension of controlled dynamics to the uncertain setting. The book mixes well known material and applications with new insights. especially from viability. robust and precaution analysis. Chap- ter 3 examines the issues of equilibrium and stability. . The case of imperfect information is also in- troduced at the end.fr/~delara/BookSustain. The textbook is organized as follows. In Chap. Proofs are relegated to Appendix A. the prob- lem of state constraints is particularly studied via viability and invariance tools. In Chap. 2. 7 and for optimization in Chap. 8. we first present some generic examples of environment and resource management detailed all along the text. Chapter 9 is devoted to the case where information about the state sys- tem is partial. 4. then give the general form of control models under study. Chapter 5 is devoted to the optimal control question. 6.enpc. and we present different decision-making approaches including both robust and stochastic criteria. still treated by dynamic programming but also by the so-called maximum principle.10 1 Introduction robust frameworks are exposed.
J. Wiley.-J. L. 2000. C. Hachette. M. 41:1–28. Environmental Modeling and Assessment. second edition. 64(4):761–767. M. Cambridge University Press. [13] K. 2005. New York. 88:312–319. W. Resource Economics. Nature. [8] N. Daan. Ecological Economics. Quarterly Journal of Economics. Pelletier. Pauly. De Lara. De Lara. M. Heal. L.. Biodiversité. 1999. and M. V. 2007. 1974. Oxford. T. Clark. February 2006. J. Béné. 61:169–185. [12] L. Environmental preservation. uncertainty. 1982. [2] R. Review of Economic Studies. E. Christensen and D. 1992. ICES J. 2001. 36:385–396. [9] P. Is a management framework based on spawning-stock biomass indicators sustainable? A viability approach. [3] C. Mathematical Bioeconomics. Doyen. Quantitative ecosystem indica- tors for fisheries management. Rochet. Kropp. Christensen. 1974. [5] V. Paris. [6] C. November 2007. Fisher. Symposium on the Eco- nomics of Exhaustible Resources. Conrad. 62:307– 614. and D. Sheffran. T. Zavaleta. and D. [10] P. Dasgupta. 1990. and irreversibity. Doyen. 11(1):69–79. Basil Blackwell. 1997. Eviner. and V. A viability analysis for a bio-economic model. ICES Journal of Marine Science. The viability analysis of manage- ment frameworks for fisheries. . S. Doyen. Ferraris. Ecological Modelling. The optimal depletion of exhaustible resources. Chapin. J. 405:234–242. Arrow and A. Barbault. Sci. Sustainability of ex- ploited marine ecosystems through protected areas: a viability model and a coral reef case study. Gabay. Ecological Modelling. [4] F. Consequences of changing biodiversity. 208(2-4):353–366. [11] M. The Control of Ressources. Eisenack. Mar. and P. and J.References [1] K. Guilbaud. Dasgupta and G. ECOPATH II–a software for balancing steady-state models and calculating network characteristics. [7] J. Cury.
W. 1954. 1974. American Economic Review. Randers. American Economic Review. 62:124–142. New York. 95:186– 214. Investment decisions under uncertainty: The “irreversibility effect”. [29] W. 2005. [28] D. Morris and D. 21:269–283. Resource and Energy Economics. McCann. [15] FAO.aspx. Heal. and L.stability debate. [18] C. and D. Harper and Row. Ecological Modelling. [26] K. S.org/en/index. Mullon. Hartwick. Economic analysis of sustainable growth and sustainable de- velopment. [25] V. Epstein. Purvis and A.fao. 2004. An assessment of several of the historically most influential theoretical models used in ecology and of the data provided in their support. L. Loreau. Getting the measure of biodiversity. United Kingdom. Available on line. H. M. F. [19] J. Shannon. [30] C. Available on. Sustainable management of an exhaustible resource: a viable control approach. Natural Resource Modeling. [27] MEA. Inchausti. 2000. The state of world fisheries and aquaculture. Behrens. Columbia University Press. Meadows. 1998.. Rome. Universe Book. The diversity . Washington DC. G. Journal of Economic Theory. Nature. [22] C. World Bank. Quantitative Conservation Biology: Theory and Practice of Population Viability Analysis. Santanu. 1988. Intergenerational equity and the investing of rents from exhaustible resources. Environment Department WP 15. New York. D. 2000. S. Dynamic efficiency of conservation of renew- able resources under uncertainty. second edition. 2001. 17:27–58. Oxford University Press. Economic Theory and Sustainability. The Limits to Growth. and P. Martinet and L. Doyen. Olson and R. Henry. Cury. S. Technical report. Olewiler. Naeem. 64(6):1006–1012.org. [21] G. Oxford. [17] J. 2002. J. 29(1):p. 67:972–974.maweb. P. 1980. New York. Gordon. [33] A. Doak. . Millennium Ecosystem Assessment.17–39. Graham. The economic theory of a common property resource: the fishery. 2000. 405:212–219. 43(1-2):5–31. J. Journal of Risk Research. Pezzey. [24] M. [20] J. Nature. Journal of Political Economy. Sinauer Associates.ipcc. D. Decision making and temporal resolution of uncertainty. Valuing the Future.ch/. 1977. 1972. [16] H. Decision-analytic refinements of the precautionary prin- ciple. 2007. The Economics of Natural Resource Use. Viability model of trophic interac- tions in marine ecosystems. F.12 References [14] L. 2000. 2003. [32] D. 4(2):127–141. [23] IPCC. International Economic Review. Hall. 1998. Hector. 405:228–233. [31] L. Biodiversity and ecosystem func- tioning: synthesis and perspectives. Meadows. Hartwick and N. 1992.
E. 1974. 41:123–137. Some aspects of the dynamics of populations important to the management of commercial marine fisheries. On the differential equations of species in competition. B. Oxford University Press. Our common Future. [38] R. 1999. Solow. Yodzis. Schaefer. Journal of Mathematical Biology. Smale. Sandin. Bulletin of the Inter- American tropical tuna commission. Wenzel. Dimensions of the precautionary principle. Journal of Environmental Economics and Management. Ecological Applications. February 1994. References 13 [34] P. Renewable resource economists and policy: What difference have we made. Growth with exhaustible natural resources: Efficient and opti- mal growth paths. Springer. Earth System Analysis. 41:29–45. . 1974. M. 1954. 1987. Symposium on the Economics of Exhaustible Resources. Human and eco- logical risk assessment. 39:306–327. [35] M. Predator-prey theory and management of multispecies fish- eries. J. Sym- posium on the Economics of Exhaustible Resources. [39] J. Review of Economic Studies. 2000. [42] P. [40] WCED. Schellnhuber and V. 3(1):5–7. Review of Economic Studies. 4(1):51–58. 1988. Stiglitz. [41] J. 1976. Integrating Science for Sustainability. Wilem. Intergenerational equity and exhaustible resources. [36] H. 5:889–907. 1:25–56. [37] S.
.
Each decision may influence a so-called state of the system: such a mechanism mainly refers to the dynamics or transitions. Such . In the framework of control theory. 11. capital accumulation dynamics and the carbon cycle. let us mention [1]. Some major contributions in this vein are [3. including population dynamics. A sequential decision model captures a situation in which decisions are to be made at dis- crete stages. dynamics. From the mathematical point of view. models then correspond to sequential decision-making problems. we avoid the introduction of too many sophisticated mathematics and notations. to quote but a few. desirability or effective- ness conditions to satisfy. 20]. there may be admissibility. their main structures are quite similar. As explained in the introduction. this monograph restricts all the models and methods to discrete time dynamics. They turn out to be decision-making problems where time plays a central role. contrarily to the continuous time case. control. First. corresponding to the constraints of the system.2 Sequential decision models Although the management of exhaustible and renewable resources and pollu- tion control are issues of a different nature. 10. 8. such as days or years. three main ingredients are generally combined: state dynamics. Furthermore. viability or optimality appear relevant for environ- mental and sustainability purposes. Control theory of dynamic systems is well suited to tackling such situations and to building up mathematical models with analytic. al- gorithmic and/or numerical methods. In this manner. it directly copes with decision-making. such an approach clearly ac- counts for evolution and dynamical mechanisms. planning and management issues. control theory proposes different methods to rank and select the decisions or controls among which stability. Constraints At each stage. the specific framework of discrete time dynamics is not often treated by itself. viability. 9. acceptability constraints and optimality criterion. Among rare references. State. Second. In this context.
The usual model [21] is in continuous time with an infinite horizon but here we adapt a discrete time version with a finite horizon. t = t0 . h(T − 1) produces the sequence of stocks S(t0 ). it should be understood that it runs from t0 to T − 1. The dynamics of the resource is simply written S(t + 1) = S(t) − h(t) . 8. . . or from t0 to T . When the range of time t is not specified. . accordingly. The modeling on this topic is often derived from the classic “cake eating” economy first studied by Hotelling in [21]. about decision strategies in Sect. . the sequence of extractions h(t0 ). . It is first assumed that the extraction decision h(t) is irreversible in the sense that at every time t . desirable consumption levels. They include models for exhaustible resources. fitness or welfare constitute the usual examples. end the chapter. . minimal ecosys- tem services or basic needs.11. introduces the general mathemat- ical framework for sequential decisions in the certain case. .e. Some remarks. Criterion optimization An intertemporal criterion or performance may be optimized to choose among the feasible solutions. oil. t + 1[ and h(t) the extraction during [t. We start with very stylized and aggregated models. S(T ). . renewable resources. The first sections are devoted to examples and models inspired by resource and environmental management in the deterministic case. . ). guaranteed catches. h(t0 + 1). More complex models are then exposed. related to consumption in the economy. “maximin” assessments stand for more exotic criteria which are also of inter- est for sustainability and equity purposes as will be explained in Chap. t0 + 1.9. . The present chapter is organized as follows. 2.16 2 Sequential decision models constraints may refer to non extinction conditions for populations. .1) where S(t) is the stock of resource at the beginning of period [t. T − 1 (2. . discounted util- ity of consumption. . S(t0 + 1). Net present value of cost-benefit or rent. However.10 and about the curse of dimensionality in Sect. biodiversity and pollution mitiga- tion. 2. 2. Such acceptability issues will be examined in detail in Chaps. Sect. 5 and Chap. When T < +∞. A second part.1 Exploitation of an exhaustible resource We present a basic economic model for the evaluation and management of an exhaustible natural resource (coal. t + 1[. 2. pollution standards. without uncertainty. i. Consider an economy where the only commodity is an exhaustible natural resource. Time t is an integer varying from initial time t = t0 to horizon T (T < +∞ or T = +∞). S(T − 1). 4 and 7. .
Generally 0 ≤ ρ < 1 as ρ = 1+r 1 f is built from the interest rate or risk-free return rf . then include harvesting à la Schaefer and finally introduce management criteria. . such a requirement cannot be fulfilled with a finite resource S(t0 ). −1 T max ρt L h(t) h(t0 ).6) along the generations t? This sustainability concern can be written in terms of utility in a form close to “maximin Rawls criterion” [33]. . A very common optimization problem is to maximize the sum1 of dis- counted utility derived from the consumption of the resource with respect to extractions h(t0 ). h(T − 1).4) More generally.2 Assessment and management of a renewable resource 17 0 ≤ h(t) .. . (2. An important question is related to intergenerational equity. Of course.3) and that 0 ≤ S(t) . when T = +∞..h(T −1) t=t0 where L is some utility function of consumption and ρ stands for a (social) discount factor. we start from a one-dimensional aggregated biomass dy- namic model. we could consider a stronger conservation constraint for the resource as follows S ≤ S(t) . h(t0 + 1).. but we may also consider the case ρ = 1 when T < +∞. 2. .5) where S > 0 stands for some minimal resource standard.2 Assessment and management of a renewable resource In this subsection. (2.. i. (2.2) Physical constraints imply that h(t) ≤ S(t) . 1 The sum goes from t = t0 up to T − 1 because extractions run from t0 to T − 1 while stocks go up to T . 2. (2.e. . Can we im- pose some guaranteed consumption (here the extraction or consumption) level h 0 < h ≤ h(t) (2.
Such a model may account for the demographic structure (age. 3. In many models. fishery) are built upon the framework of a biological model. 2.1. (2. The linear model g(B) = RB . biologists have often found it necessary to introduce various degrees of sim- plification to reduce the complexity of the analysis.11) K where again K represents the carrying capacity. 1. (2. is considered globally as a single unit with no consideration of the structure population. the stock. The Beverton-Holt model RB g(B) = . 4. In discrete time. (2. (2. measured through its biomass.8) where r = R − 1 is the per capita rate of growth. which of course does not make sense. However. Its growth is materialized through the equation B(t + 1) = g B(t) . examples of g are given by [23. The logistic model B g(B) = B + rB 1 − . stages or size classes.10) (1 + r)K Such a logistic model in discrete time can be easily criticized since for biomass B greater than the capacity K the biomass becomes negative. We shall also use the equivalent form rB g(B) = (1 + r)B 1 − .7) where B(t) stands for the resource biomass and g : R+ → R+ is taken to satisfy g(0) = 0. (2. 8] and illustrated by Fig. see [5]) of the exploited stock or may attempt to deal with the trophic dimension of the exploited (eco)system. The Ricker model B g(B) = B exp r(1 − ) .12) 1 + bB R−1 where the carrying capacity now corresponds to K = b . 2. . 2 The carrying capacity K is the lowest K > 0 which satisfies g(K) = K.9) K where r ≥ 0 is the per capita rate of growth (for small populations).18 2 Sequential decision models Biological model Most bioeconomic models addressing the problem of renewable resource ex- ploitation (forestry. and K is the carrying capacity 2 of the habitat. (2. agriculture.
Dynamics are computed with the Scilab code 1. satisfying f (B) ≥ (B) for B ∈ [0. Indeed. g(B) < B whenever B < B and some Allee effect occurs in the sense that small populations decline to extinction. 2.1. . 2.9. K = 10. Biomass dynamics 20 Identity 18 Ricker Logistic 16 Beverton−Holt Depensation 14 Biomass B(t+1) 12 10 8 6 4 2 0 0 2 4 6 8 10 12 14 16 18 20 Biomass B(t) Fig. Comparaison of distinct population dynamics g for r = 1. (2. in 3. the Ricker dynamics. K[ stands for some minimum viable population threshold. as illustrated by Fig. the Beverton-Holt recruitment. The choice among the different population dynamics deeply impacts the evolution of the population. K].2.13) where α > 0 and f is any of the previous population dynamics.2 Assessment and management of a renewable resource 19 5. the logistic model. In ⊕. a depensation model. 2. The depensation models g(B) = B + α(f (B) − B)(B − B ) . and B ∈]0. in ×. in . B = 2. The Beverton-Holt dynamics generates “stable” behaviors while logistic or Ricker may induce oscillations or chaotic paths.
2. . K = 10.20 2 Sequential decision models Ricker Trajectories Logistic Trajectories 20 20 18 18 16 16 14 14 12 12 Biomass B(t) biomas B(t) 10 10 8 8 6 6 4 4 2 2 0 0 0 1 2 3 4 5 6 7 8 9 10 0 1 2 3 4 5 6 7 8 9 10 time (t) time (t) (a) Ricker (b) Logistic Beverton−Holt Trajectories Depensation Trajectories 20 20 18 18 16 16 14 14 12 12 Biomass B(t) Biomass B(t) 10 10 8 8 6 6 4 4 2 2 0 0 0 1 2 3 4 5 6 7 8 9 10 0 1 2 3 4 5 6 7 8 9 10 time (t) time (t) (c) Beverton-Holt (d) Depensation Fig. Trajectories are computed with the Scilab code 1. B = 2 and same initial conditions B0 . Trajectories for different population dynamics with common parameters r = 1.9. 2.
hence the constraints 0 ≤ h(t) ≤ B(t) right above..B)’..*exp(r*(1-B/K)) y_Logistic=ode("discrete".3). b=(R-1)/K . harvesting takes place at the beginning of the year t. y=B. // opening windows // Population dynamics parameters for i=1:N_simu k=R*K/(R-1).2.5]).1000). "Depensation"].4). etc.2 Assessment and management of a renewable resource 21 Scilab code 1.2*K. ’Biomass B(t)’) plot2d(B. B(t + 1) = g B(t) − h(t) .0.sce // N_simu=30. to identify the curves xtitle(’Beverton-Holt Trajectories’. B=linspace(0. endfunction y_BH=ode("discrete". // Computation of trajectories starting from B0 function [y]=Beverton(t.B)’].2*K]).B+(Beverton(t.B_0.[y_BH’]..Depensation).B)’. xset("window". 2. Depensation(0.0. // y=max(0. plot2d(time.4."Logistic".rect=[0. (R*B).4.0).B_0.rect=[0.*(B-MVP)) endfunction xset("window"."Ricker". // drawing diamonds.9.Beverton).time. in the above sequential model. endfunction // random initial conditions function [y]=Ricker(t..[B’ Ricker(0. 3 A formulation where regeneration occurs at the beginning of the year while har- vesting ends would give B(t + 1) = g(B(t)) − h(t). R = 1+r .. // Dynamics plot2d(time.[y_D’].-[1. K= 10.1:4).B)’ Logistic(0. 2.’time (t)’.’Biomass B(t+1)’) ’Biomass B(t)’) // Comparaison of the shapes of population dynamics end // end simulation loop T=10. r = 0..B)’])..B) xtitle(’Ricker Trajectories’. with 0 ≤ h(t) ≤ g(B(t)).B_0. 1.2*K])."Beverton".’time (t)’.2*K]).rect=[0.2*K]).[B’ Ricker(0.B)’ Beverton(0.T. plot2d(time.T.time.. (2..Ricker).T.-[1. xset("window".B+(Beverton(t. MVP=K/5..’time (t)’.30).1). xtitle(’Logistic Trajectories’.2*K.. crosses.xbasc(0)..y_Logistic. Notice that.0..Logistic).3... legends(["Identity".5]. xbasc(1:4).B)-B). regeneration takes place at the end3 of the year t. xtitle(’Depensation Trajectories’.. ’Biomass B(t)’) B=linspace(0.T. Depensation(0. // exec dyn_pop.7) above becomes the Schaefer model.rect=[0.0.B) // along distinct population dynamics y=(R*B).’Biomass B(t)’. // N_simu=50.B)’ Beverton(0.14) where h(t) is the harvesting or catch at time t.B) y=max(0. function [y]=Depensation(t. plot2d(time.B_0. y_D=ode("discrete". plot2d(B. xset("window"..0. time=0:T.time. // simulation loop function [y]=Logistic(t./(1 + b*B) endfunction xset("window".time. the model (2..’ul’).*(B-MVP)/MVP) ’biomas B(t)’) y=max(0.3.0. 0 ≤ h(t) ≤ B(t) .2...0. originally introduced for fishing in [31].[y_Ricker’].’time (t)’.0. .B) y_Ricker=ode("discrete". // Number of simulations lines(0).5*K.B)-B). // Time horizon // Harvesting When harvesting activities are included.B)’ Logistic(0. xset("window". xtitle(’Biomass dynamics’.2).*(1-B/k) ) B_0=rand(1)*1.
This issue is examined in Chap. (2. B) := ∂H e ∂B (e. and q ≥ 0 is a catchability coefficient. From the ecology point of view. e) = H(B.15) where e stands for the harvesting effort (or fishing effort. namely h = qeB . In this context. such a relation H relies on a functional form of predation. is defined as the difference between benefits and cost R(e. whenever C is smooth enough.16) where the catch function H is such that • H(0. an index related for instance to the number of boats involved in the activity). the well-known Schaefer model gives the so-called sustainable yield associated to the fishing effort by solving the implicit relation B = g(B − h) giving h. (2. 0) = 0 • H increases in both arguments biomass B and effort e. The economic model which is directly derived from the Schaefer model is the Gordon model [17. At this stage. 8] which integrates the economic aspects of the fishing activity through the fish price p and the catch costs C(e) per unit of effort. when the a station- ary exploitation induces a steady population. whenever H is smooth enough.18) where the cost function is such that • C(0) = 0. (2. The static Gordon-Schaefer model A first approach consists in reasoning at equilibrium. B) . it is thus assumed that ⎧ ⎨ 0 ≤ HB (e. The rent.22 2 Sequential decision models It is frequently assumed that the catch h is proportional to both biomass and harvesting effort. the harvesting is related to the effort and the biomass through some relation h = H(e.17) where the exponents α ≥ 0 and β ≥ 0 stand for the elasticities of production. B) = qeα B β . Ecology and economics have two distinct ways to characterize the function H. or profit. B) − C(e) . B) . it is thus assumed that C (e) ≥ 0. B) := pH(e. B) . • C increases with respect to effort e. . More generally. while from the economics viewpoint H corresponds to a production function. (2. B) := ∂H ∂B (e. it is worth pointing out the case of a Cobb-Douglas production function H(e. ⎩ 0 ≤ H (e. 3.
2 Assessment and management of a renewable resource 23 It is frequently assumed that the costs are linear in effort.. an economic model may be formulated as the intertemporal maximization of the rent with respect to the fishing effort.e. that it has been regularly used as the underlying frame- work by optimal control theory since the latter was introduced in fisheries sciences [8].. along with its indisputable normative character. B)). Although it suffers from a large number of unrealistic assumptions. T −1 max ρt pH e(t). that is T −1 max ρt L h(t) + ρT L B(T ) (2. Intertemporal profit maximization Assuming a fixed production structure.. e(t0 ). The welfare optimized by the planner is represented by the sum of updated utilities of successive harvests h(t) (assumed to be related to consumption.. i. the Gordon model displays a certain degree of concordance with the empirical histories of fisheries . 2. in an optimal way. Notice that the final term L B(T ) corresponds to an existence or inheritance value of the stock.h(T −1) t=t0 where ρ ∈ [0. of the renewable natural resource over T periods. Ecological viability or conservation constraint can be integrated by requiring that B ≤ B(t) ..19) h(t0 ). where B > 0 is a safe minimum biomass level. one can compute the effort e maximizing the rent R(e. Once given the cost function C. Intertemporal utility maximization We can also consider a social planner or a regulating agency wishing to make use. 1[ is a discount factor and L is a utility function. ... B(t) − C e(t) . An important constraint is related to the limit effort e resulting from the fixed production capacity (number of boats and of fishermen): 0 ≤ e(t) ≤ e . namely: C(e) = ce with c>0. It is probably for this reason. B) under the constraint that B = g(B − H(e. stationary capital and labor.e(T −1) t=t0 where ρ represents a discount factor (0 ≤ ρ ≤ 1).. for instance).
measured in monetary units. • the parameter δ stands for the natural rate of removal of atmospheric co2 to unspecified sinks (δ ≈ 0. The goal of the policy makers is to minimize intertempo- ral discounted abatement costs while respecting a maximal sustainable co2 concentration threshold at the final time horizon: this is an example of a cost-effectiveness problem. Gigatonnes of carbon (about 7. measured in ppm.3 Mitigation policies for carbon dioxyde emissions Let us consider a very stylized model of the climate-economy system.20) where • M (t) is the co2 atmospheric concentration.and is measured in GtC. . namely the atmospheric co2 concen- tration level denoted by M (t) and some economic production level such as gross world product gwp denoted by Q(t). for the co2 emis- sions. or “business as usual” (bau). the stock externality reaches a maximum and co2 accumulation is irreversible.GtC−1 sums up highly complex physical mechanisms. 4 Two polar cases are worth being pointed out: when δ = 1. namely a highly simple dynamical model M (t + 1) = M (t) + αEbau (t) 1 − a(t) − δ M (t) − M−∞ . Carbon cycle model The description of the carbon cycle is similar to [27]. • the parameter α is a conversion factor from emissions to concentration. α ≈ 0. δ accounts for the inertia of a natural system. (2.2 GtC per year between 2000 and 2005). The decision variable related to mitigation policy is the emission abatement rate denoted by a(t).24 2 Sequential decision models 2.21) thus representing the anthropogenic perturbation of a natural system from a pre-industrial equilibrium atmospheric concentration M−∞ . • Ebau (t) is the baseline. on the contrary. Notice that carbon cycle dynamics can be reformulated as M (t + 1) − M−∞ = (1 − δ) (M (t) − M−∞ ) + αEbau (t) 1 − a(t) (2. It is described by two aggregated variables. parts per million (379 ppm in 2005). when δ = 0.01 year−1 ). • the abatement rate a(t) corresponds to the applied reduction of co2 emis- sions level (0 ≤ a(t) ≤ 1). • M−∞ is the pre-industrial atmospheric concentration (about 280 ppm).471 ppm. Hence. carbon cycle inertia is nil and therefore co2 emissions induce a flow externality rather than a stock one. and is a most uncertain parameter4 .
Q) increases with abatement rate a. It can be assumed that bau emissions increase with production Q.Q) ∂a is smooth enough. ∂Q∂a As a result. This means that the availability and costs of tech- nologies for carbon switching improve with growth. we can assume that growth lowers marginal abatement costs. 2. that is for smooth C: ∂C(a. (2.22) This dynamic means that the economy is not directly affected by abatement policies and costs. a rising emissions base- line is given. if the marginal abatement cost ∂C(a. it decreases with production in the sense: ∂ 2 C(a. 550 ppm. Of course. The cost-effectiveness problem faced by the social planner is an optimiza- tion problem under constraints. The emissions depend on production Q because growth is a major determinant of energy demand [24]. (2. this is a restrictive assumption. 650 ppm) at a specified date T > 0 (year 2050 or 2100 for instance): M (T ) ≤ M . The global economics dynamic is represented by an autonomous rate of growth g ≥ 0 for the aggregated production level Q(t) related to gross world product gwp: Q(t + 1) = (1 + g)Q(t) . dQ Combined with a global economic growth assumption. it is assumed that the abatement cost C(a. where the function Ebau stands for the emissions of co2 resulting from the economic production Q in a “business as usual” (bau) scenario and accumulating in the atmosphere. following for instance [18]. The cost-effectiveness criteria A physical or environmental requirement is considered through the limita- tion of concentrations of co2 below a tolerable threshold M (say 450 ppm. It consists .3 Mitigation policies for carbon dioxyde emissions 25 Emissions driven by economic production The baseline Ebau (t) can be taken under the form Ebau (t) = Ebau (Q(t)). Q) <0. when E is smooth enough. ∂a Furthermore. the costs of reducing a ton of carbon decline. namely. Thus. Q) >0. Hence. dEbau (Q) >0.23) The reduction of emissions is costly.
The parameter ρ stands for a discount factor. the problem can be written as . Q(t) while reaching the concen- tration tolerable window M (T ) ≤ M .T −1 in minimizing the discounted in- tertemporal abatement cost t=t0 ρt C a(t). Therefore.
3 together with the ceiling target M = 550 ppm. 2.20) and (2.24) a(t0 ). (2. a viable medium sta- tionary abatement a(t) = 0.a(T −1) t=t0 under the dynamics constraints (2. the non viable “business as usual” path abau (t) = 0 and. In 3.6. 2. Trajectories are computed with the Scilab code 2. Concentration CO2 1200 viable 1100 BAU green 1000 threshold 900 800 M(t) (ppm) 700 600 500 400 300 200 100 1980 2000 2020 2040 2060 2080 2100 t Fig.. Some projections are displayed in Fig...26 2 Sequential decision models −1 T inf ρt C a(t). The path in ⊕ relies on a total abatment a(t) = 1. The “business as usual” path abau (t) = 0 does not display satisfying concentrations since the ceiling target is exceeded at time t = 2035.6 provides a viable path. The other path corresponding here to a medium stationary abatement a(t) = 0.. in .23). . Projections of co2 concentration M (t) at horizon 2100 for different mit- igation policies a(t) together with ceiling target M = 550 ppm in black.3. Q(t) .22) and target constraint (2. They are built from the Scilab code 2.
2.4 A trophic web and sustainable use values 27
Scilab code 2.
// L_g=[L_g M_g];
clear
Q=(1+taux_Q)*Q;
E = sigma * Q * (1-u(t-t_0+1));
// PARAMETERS // L_E=[L_E E];
// Emissions CO2
// initial time M = M* (1-absortion) + alphaa* E;
t_0=1990; // dynamics concentration CO2
// Final Time
t_F=2100; E_bau = sigma * Q ;
// Time step L_Eb=[L_Eb E_bau];
delta_t=1; // Emissions Business as usual (BAU)
M_bau = M_bau* (1-absortion) + alphaa* E_bau;
taux_Q=0.01; // dynamics BAU
// economic growth rate
alphaa=0.64; E_g = 0;
// marginal ratio marginal atmospheric retention L_Eg=[L_Eg E_g];
// (uncertain +- 0.15) // Green: no emissions
sigma=0.519; M_g = M_g* (1-absortion) + alphaa* E_g;
absortion=1/120 ; // dynamics without pollution
// concentration target (ppm) end,
M_sup=550;
// Initial conditions // Results printing
t=t_0;
M=354; //in (ppm) long=prod(size(L_t));
M_bau=M; M_g=M; step=floor(long/20);
Q = 20.9; // in (T US$) abcisse=1:step:long;
E = sigma * Q ; xset("window",1);xbasc(1)
plot2d(L_t(abcisse),[L_E(abcisse)’ L_Eb(abcisse)’ ...
L_Eg(abcisse)’],style=-[4,5,3]) ;
legends(["viable";"BAU";"green"],-[4,5,3],’ul’);
// Distinct abatment policies xtitle(’Emissions E(t)’,’t’,’E(t) (GtC)’);
u = 1*ones(1,t_F-t_0+1); // Strong mitigation
u = 0*ones(1,t_F-t_0+1); // No mitigation (BAU) xset("window",2);xbasc(2)
u = 0.6*ones(1,t_F-t_0+1); // medium mitigation plot2d(L_t(abcisse),[L_M(abcisse)’ L_bau(abcisse)’ ...
//u = 1*rand(1,t_F-t_0+1); // random mitigation L_g(abcisse)’ ones(L_t(abcisse))’*M_sup],...
style=-[4,5,3,-1]) ;
// Initialisation (empty lists) legends(["viable";"BAU";"green";"threshold"],...
L_t=[]; L_M=[]; L_bau=[]; L_E=[]; -[4,5,3,-1],’ul’);
L_Eg=[];L_Eb=[]; L_Q=[];L_g=[]; xtitle(’Concentration CO2’,’t’,’M(t) (ppm)’);
// System Dynamics
for (t=t_0:delta_t:t_F) xset("window",4); xbasc(4)
plot2d(L_t(abcisse),L_Q(abcisse));
L_t=[L_t t]; xtitle(’Economie: Production Q(t)’,’t’,’Q(t) (T US$)’);
L_M=[L_M M];
L_Q=[L_Q Q]; //
L_bau=[L_bau M_bau];
2.4 A trophic web and sustainable use values
Consider n species within a food web. An example of trophic web is given
in Sect. 7.4 for a large coral reef ecosystem. To give some feelings of the
numbers, 374 species were identified during a survey in the Abore reef reserve
(15 000 ha) in New Caledonia, differing in mobility, taxonomy (41 families)
and feeding habits. The analysis of species diets yielded 7 clusters, each cluster
forming a trophic group; the model in [14] restricts them to 4 trophic groups
(piscivors, macrocarnivors, herbivors and other fishes) plus coral/habitat.
Denote by Ni (t) the abundance (number of individuals, or approximation
by a continuous real) or the density (number of individuals per unit of surface)
of species i ∈ {1, . . . , n} at the beginning of period [t, t + 1[. The ecosystem
dynamics and the interactions between the species are depicted by a Lotka-
Volterra model:
28 2 Sequential decision models
n
Ni (t + 1) = Ni (t) Ri + Sij Nj (t) . (2.25)
j=1
• Autotrophs grow in the absence of predators (those species i for which
Ri ≥ 1), while consumers die in the absence of prey (when Ri < 1).
• The effect of i on j is given by the term Sij so that i consumes j when
Sij > 0 and i is the prey of j if Sij < 0. The numerical response of
a consumer depends on both the number of prey captured per unit of
time (functional response) and the efficiency with which captured prey
are concerted into offspring. In this model, we represent prey effect j on
consumers i by Sij = −eij Sji , where eij is the conversion efficiency (e < 1
when the size of the consumer is larger than that of its prey).
• The strength of direct intra-specific interactions is given by Sii < 0. Pos-
sible mechanisms behind such self-limitation include mutual interferences
and competitions for non-food resources. When the index i labels group
of species (trophic groups for instance), it may account for intra-group
interactions.
The ecosystem is also subject to human exploitation. Such an anthro-
pogenic pressure induced by harvests and catches h(t) = h1 (t), . . . , hn (t)
modifies the dynamics of the ecosystem as follows
n
Ni (t + 1) = Ni (t) − hi (t) Ri + Sij Nj (t) − hj (t) , (2.26)
j=1
with the constraint that the captures do not exceed the stock values
0 ≤ hi (t) ≤ Ni (t) .
Note that many catches can be set to zero since the harvests may concentrate
on certain species as top predators. We consider that catches h(t) provide a
direct use value through some utility or payoff function L(h1 , . . . , hn ). The
most usual case of a utility function is the separable one
n
L(h1 , . . . , hn ) = p i h i = p1 h 1 + · · · + p n h n ,
i=1
where pi plays the role of price for the resource i as the marginal utility value
of catches hi . Other cases of substitutable and essential factors may impose
the consideration of a utility function of the form
n
i = h1 × · · · × hn .
hα α1 αn
L(h1 , . . . , hn ) = i
i=1
An interesting problem in terms of sustainability, viability and effectiveness
approaches is to guarantee some utility level L at every time in the following
sense:
2.5 A forestry management model 29
L h1 (t), . . . , hn (t) ≥ L , t = t0 , . . . , T − 1 . (2.27)
Let us remark that the direct use value constraint (2.27) induces the conser-
vation of part of the resource involved since5
L(N (t)) ≥ L(h(t)) ≥ L > 0 =⇒ ∃i ∈ {1, . . . , n}, Ni (t) > 0 .
However, along with the direct use values, conservation requirements related
to existence values may also be explicitly handled through existence con-
straints of the form
Ni (t) ≥ Ni > 0 , (2.28)
where Ni stands for some quasi-extinction threshold.
2.5 A forestry management model
An age-classified matrix model
We consider a forest whose structure in age6 is represented in discrete time
by a vector N of Rn+
⎛ ⎞
Nn (t)
⎜ Nn−1 (t) ⎟
⎜ ⎟
N (t) = ⎜ .. ⎟,
⎝ . ⎠
N1 (t)
where Nj (t) (j = 1, . . . , n − 1) represents the number of trees whose age,
expressed in the unit of time used to define t, is between j − 1 and j at the
beginning of yearly period [t, t + 1[; Nn (t) is the number of trees of age greater
than n − 1. We assume that the natural evolution (i.e. under no exploitation)
of the vector N (t) is described by a linear system
N (t + 1) = A N (t) , (2.29)
where the terms of the matrix A are nonnegative which ensures that N (t)
remains positive at all times. Particular instances of matrices A are of the
Leslie type (see [5])
⎡ ⎤
1 − mn 1 − mn−1 0 ··· 0
⎢ . ⎥
⎢ 0 0 1 − mn−2 . . 0 ⎥
⎢ ⎥
⎢ .. ⎥
A=⎢ . 0 ⎥ (2.30)
⎢ ⎥
⎢ .. ⎥
⎣ 0 ... 0 . 1 − m1 ⎦
γn γn−1 ··· ··· γ1
5
As soon as L(0) = 0.
6
Models by size classes are commonly used, because size data are more easily
available than age.
30 2 Sequential decision models
where mj and γj are respectively mortality and recruitment parameters be-
longing to [0, 1]. The rate mj is the proportion of trees of age j − 1 which die
before reaching age j while γj is the proportion of new-born trees generated
by trees of age j − 1. In coordinates, (2.29) and (2.30) read
⎧
⎪ Nn (t + 1) = (1 − mn )Nn (t) + (1 − mn−1 )Nn−1 (t) ,
⎪
⎪
⎨
Nj (t + 1) = (1 − mj−1 )Nj−1 (t) , j = 2, . . . , n − 1 , (2.31)
⎪
⎪
⎪
⎩ N (t + 1) = γ N (t) + · · · + γ N (t) .
1 n n 1 1
Harvesting and replanting
Now we describe the exploitation of such a forest resource. We assume the
following main hypotheses:
1. only the oldest trees may be cut (the minimum age at which it is possible
to cut trees is n − 1);
2. new trees of age 0 may be planted.
Thus, let us introduce the scalar decision variables h(t), representing the trees
harvested at time t, and i(t), the new trees planted. The control is then the
two dimensional vector
h(t)
u(t) = .
i(t)
Previous assumptions lead to the following controlled evolution
N (t + 1) = A N (t) + Bh h(t) + Bi i(t) , (2.32)
where ⎛ ⎞ ⎛ ⎞
−1 0
⎜ 0 ⎟ ⎜0⎟
⎜ ⎟ ⎜ ⎟
⎜ ⎟ ⎜ ⎟
Bh = ⎜ ... ⎟ and Bi = ⎜ ... ⎟ .
⎜ ⎟ ⎜ ⎟
⎝ 0 ⎠ ⎝0⎠
0 1
Furthermore, since one cannot plan to harvest more than will exist at the end
of the unit of time, the control variable h(t) is subject to the constraint
0 ≤ h(t) ≤ CAN (t) ,
where the row vector C is equal to (1 0 0 · · · 0), which ensures the non nega-
tivity of the resource N . Thus, we have assumed implicitly that the harvesting
decisions h(t) are effective at the end7 of each time interval [t, t + 1[.
7
If the harvesting decisions h(t) are effective at the beginning of each unit of time
t, we have 0 ≤ h(t) ≤ C N (t) = Nn (t).
2.6 A single species age-classified model of fishing 31
Cutting trees is costly, but brings immediate benefits, while planting trees
is costly and will bring future income. All this may be aggregated in a per-
formance function L(h, i) and the planner objective consists in maximizing
the sum of discounted performance of successive cuts h(t) and replanting i(t),
that is8
+∞
max ρt L h(t), i(t) ,
h(·),i(·)
t=t0
where again ρ is a discount factor chosen in [0, 1[.
2.6 A single species age-classified model of fishing
We present an age structured abundance population model with a possibly non
linear stock-recruitment relationship derived from fish stock management [28].
Time is measured in years, and the time index t ∈ N represents the begin-
ning of year t and of yearly period [t, t + 1[. Let A ∈ N∗ denote a maximum
age9 , and a ∈ {1, . . . , A} an age class index, all expressed in years. The pop-
ulation is characterized by N = (Na )a=1,...,A ∈ RA + , the abundances at age:
for a = 1, . . . , A − 1, Na (t) is the number of individuals of age between a − 1
and a at the beginning of yearly period [t, t + 1[; NA (t) is the number of
individuals of age greater than A − 1. The evolution of the exploited popula-
tion depends both on natural mortality, recruitment and human exploitation.
Hence, for ages a = 1, . . . , A − 1, the following evolution of the abundances
can be considered
Na+1 (t + 1) = Na (t) exp − (Ma + λ(t)Fa ) , (2.33)
where
• Ma is the natural mortality rate of individuals of age a;
• Fa is the mortality rate of individuals of age a due to harvesting between
t and t + 1, taken to remain constant during yearly period [t, t + 1[; the
vector (Fa )a=1,...,A is termed the exploitation pattern;
• the control λ(t) is the fishing effort multiplier, taken to be applied in the
middle of yearly period [t, t + 1[.
Since NA (t) is the number of individuals of age greater than A − 1, an
additional term appears in the dynamical relation
NA (t + 1) = NA−1 (t) exp − (MA−1 + λ(t)FA−1 ) + NA (t)π exp − (MA + λ(t)FA ) .
(2.34)
8
h(·) = (h(t0 ), h(t0 + 1), . . .) and i(·) = (i(t0 ), i(t0 + 1), . . .).
9
To give some ideas, A = 3 for anchovy and A = 8 for hake are instances of
maximum ages. This is partly biological, partly conventional.
• B Beverton-Holt: ϕ(B) = α+βB ....33).36) where the function ϕ describes a stock-recruitment relationship. .34) and (2. −βB • Ricker: ϕ(B) = αBe . (2.35) a=1 that sums up the contributions of individuals to reproduction. ⎜ ⎟ + ⎝ NA−1 (t) ⎠ NA (t) we deduce from (2. Denoting ⎛ ⎞ N1 (t) ⎜ ⎟ N2 (t) ⎜ ⎟ ⎜ ⎟ . where (γa )a=1. We write N1 (t + 1) = ϕ SSB N (t) . The recruits N1 (t + 1) are taken to be a function of the spawning stock biomass SSB defined by A SSB(N ) := γa υa Na . 1} is related to the existence of a so-called plus-group: if we neglect the survivors older than age A then π = 0.. • linear: ϕ(B) = rB. ⎜ . (2. ⎟ ⎜ ⎟ ⎜ .. else π = 1 and the last age class is a plus group10 .32 2 Sequential decision models The parameter π ∈ {0. for instance. of which typ- ical examples are • constant: ϕ(B) = R. Recruitment involves complex biological and environmental processes that fluctuate in time and are difficult to integrate into a population model.. ⎟ ⎜ ⎟ ⎜ ⎟ ⎜ ⎟ ⎜ NA−2 (t) exp− MA−2 + λ(t)FA−2 ⎟ ⎜ ⎟ ⎝ ⎠ NA−1 (t) exp − MA−1 +λ(t)FA−1 +π exp − MA +λ(t)FA NA (t) 10 π = 0 for anchovy and π = 1 for hake..... (2.A are the weights at age (all positive).36) the global dynamics of the stock controlled by catch pressure λ(t): ⎛ ⎞ ϕ SSB N (t) ⎜ ⎟ ⎜ ⎟ ⎜ ⎟ ⎜ N1 (t) exp − M1 + λ(t)F1 ⎟ ⎜ ⎟ ⎜ ⎟ ⎜ ⎟ ⎜ N2 (t) exp − M2 + λ(t)F2 ⎟ ⎜ ⎟ ⎜ ⎟ N (t + 1) = ⎜ ⎟ .A are the proportions of mature individuals (some may be zero) at age and (υa )a=1. N (t) = ⎜ ⎟ ∈ RA .
2. (g) and (h). The catches are the number of individuals captured over one year: λFa Ha (λ. (2.6 A single species age-classified model of fishing 33 Examples of trajectories may be found in Fig.4 (c) and (d) correspond to medium constant recruitment while Figs. They are built thanks to the Scilab code 3.38) a=1 where we recall that υa is the mean weight of individuals of age a.4 (a) and (b) correspond to low constant recruitment.4 for the Bay of Biscay anchovy. 2. Figs. (2. SSB N (t) ≥ B . N (t) − cλ(t) . Figs. stand for a linear recruitment form.4 (e) and (f) show a Ricker rela- tion. . Sustainability of the resource may focus more on species conservation con- straints. re- spectively defined for a given vector of abundance N and a given control λ by the Baranov catch equations [28]. 2. The last Figs. N ) = 1 − exp − (Ma + λFa ) Na . 2. N (t) ≥ Y . N ) . λ(·) t=t0 where p are unit prices while c are unit costs. 2. as with the International Council for the Exploration of the Sea (ices) precautionary approach. N ) = υa Ha (λ. The yearly exploitation is described by catch-at-age ha and yield Y . 2. A decision problem may be to optimize discounted rent +∞ max ρt pY λ(t).37) λFa + Ma The production in terms of biomass at the beginning of year t is A Y (λ. upon spawning stock biomass for instance. Sustainability of the exploitation may stress guaranteed production Y λ(t).4.
0e+008 1.0e+09 4.5 2.8e+10 ages 1−−2 3.0e+09 1.0e+09 4.0e+000 time t (years) 0 1 2 3 4 5 6 7 8 9 10 (c) Abundances N (t) (d) Total biomass B(t) Projections for the 3 age−classes with catch pressure u(t)=0.0e+10 4.0e+007 0.5e+008 ages 2−− 1.0e+09 1.0e+09 1.6e+10 3.6e+10 3.0e+09 1.0e+09 5.8e+10 ages 1−−2 3. .5 total biomass B(t) (kg) Projections total biomass with catch pressure u(t)=0.0e+10 4.0e+09 5.34 2 Sequential decision models Projections for the 3 age−classes with catch pressure u(t)=0. Figs. (g) and (h).0e+000 time t (years) 0 1 2 3 4 5 6 7 8 9 10 (e) Abundances N (t) (f) Total biomass B(t) Projections for the 3 age−classes with catch pressure u(t)=0.0e+09 1.0e+00 0 1 2 3 4 5 6 7 8 9 10 time t (years) 0.0e+008 8..5 2.0e+10 2.5 total biomass B(t) (kg) Projections total biomass with catch pressure u(t)=0. (a) and (b) correspond to low constant recruitment.0e+10 2.0e+00 0 1 2 3 4 5 6 7 8 9 10 time t (years) 0.0e+008 1.0e+10 4.5e+008 1.0e+09 4.0e+008 1.4e+10 abundances N_a(t) 1.0e+007 0. (e) and (f) show a Ricker relation.0e+008 ages 0−−1 1. 2.4. stand for a linear recruitment form.5e+008 6.5.0e+09 5.5 2.0e+10 4.6e+10 3.0e+008 2. The last Figs.5e+008 6.0e+09 1.2e+10 2.0e+09 1.5e+008 6.0e+00 0 1 2 3 4 5 6 7 8 9 10 time t (years) 0.5e+008 ages 2−− 1.0e+008 8. They are built thanks to the Scilab code 3.0e+008 2.5 total biomass B(t) (kg) Projections total biomass with catch pressure u(t)=0.0e+09 1.0e+008 ages 0−−1 1.0e+000 time t (years) 0 1 2 3 4 5 6 7 8 9 10 (a) Abundances N (t) (b) Total biomass B(t) Projections for the 3 age−classes with catch pressure u(t)=0.5 total biomass B(t) (kg) Projections total biomass with catch pressure u(t)=0.0e+09 4.0e+000 time t (years) 0 1 2 3 4 5 6 7 8 9 10 (g) Abundances N (t) (h) Total biomass B(t) Fig. Bay of Biscay anchovy trajectories for different stock-recruitment rela- tionships with same initial condition and fishing effort multiplier λ(t) = 0.2e+10 2.0e+008 2.8e+10 ages 1−−2 3.0e+00 0 1 2 3 4 5 6 7 8 9 10 time t (years) 0.8e+10 ages 1−−2 3.0e+007 0.6e+10 3.0e+09 5.5e+008 1.0e+008 2.0e+10 2. (c) and (d) correspond to medium constant recruitment while Figs.4e+10 abundances N_a(t) 1.0e+008 ages 0−−1 1.0e+008 ages 0−−1 1.0e+008 1.5 2.2e+10 2.0e+007 0.5e+008 ages 2−− 1.5e+008 1. Figs.2e+10 2.5e+008 ages 2−− 1.5e+008 6.0e+10 2.0e+008 8.4e+10 abundances N_a(t) 1.5e+008 1.0e+008 8.4e+10 abundances N_a(t) 1.
end endfunction // total_biomass= weight * traj . xbasc(i). // proportion of matures at ages N2001=10^6*[6575 1632 163]’.’ur’) xtitle(’Projections for the 3 age-classes. // Spawning biomass // drawing diamonds. function y=mean_constant(x) stock_recruitment=list(). 2. // Ndot= mat*N + [phi(SSB(N)) .-[1.i) .’abundances N_a(t)’) mat=diag( exp(-M .lambda. y= r * x . crosses.lambda * F(1:($-1)) ) .traj’. N2000=10^6*[7035 1033 381]’. endfunction stock_recruitment(2)=mean_constant.2*10^10]). // Ricker coefficients for tons // selecting a stock-recruitment relationship traj=[N1999]. // kg RR= 10^6 * [14016 7109 3964 696] . etc. // // RICKER STOCK-RECRUITMENT for i=1:4 do a=0. stock_recruitment(1)=mini_constant.2.rect=[0. // horizon in years endfunction multiplier=0.0. // kg // F_lim=Inf. function y=Ricker(x) for t=0:(T-1) xx=10^{-3}*x // xx measured in tons traj=[traj.5 * 10^{-5} . endfunction legends([’ages 0--1’. stock_recruitment(4)=linear.0.-1 ) +.style=-[1. F=[0.7 Economic growth with an exhaustible natural resource 35 Scilab code 3. xtitle(’Projections total biomass. stock_recruitment(3)=Ricker. +string(multiplier). // maximum age // ICES values // STOCK-RECRUITMENT RELATIONSHIPS B_pa = 10^6 * 33 .4 0.total_biomass. dynamics(traj(:.4*10^8]) r= (500* 10^3) *21* 0. xbasc(10+i). // mean weights at ages (kg) N2002=10^6*[1406 1535 262]’. the classic cake eating economy first studied by Hotelling in [21] is expanded through a model of capital accumulation and consumption processes in the form of [29]... phi=stock_recruitment(i) . Following [12] or [33]. function y=linear(x) with catch pressure u(t)=’.T.’ages 1--2’. A=sum(ones(F)).’time t (years)’.$).2.*weight) * N . plot2d(0:T.’ages 2--’].phi) with catch pressure u(t)=’.multiplier.8*10^(-5).. // exec anchovy.4 0.. zeros(N(2:$)) ] . y= a *( xx .5.lambda * F($)) ]). b=1. T=10. . mature=sex_ratio*[1 1 1]. pi=0 . // Population dynamics +string(multiplier). y= RR(1) . // sub diagonal terms // diagonal terms // 2. plot2d(0:T.sce endfunction // ANCHOVY // initial values // parameters for the dynamical model N1999=10^6*[4195 2079 217]’.5 ..rect=[0.* exp(-b* xx ) ).7 Economic growth with an exhaustible natural resource Let us introduce a model referring to the management of an economy using an exhaustible natural resource as in [20].79*10^6... sex_ratio = 0. function Ndot=dynamics(N. endfunction ’total biomass B(t) (kg)’) xset("window".’time t (years)’. to identify the curves y= (mature.. // no plus-group // N0=10^6*[1379 1506 256]’. // exploitation pattern N2004=10^6*[2590 254 43]’. end diag( [zeros(F(1:($-1))) pi*exp(-M .. function y=SSB(N) plot2d(0:T.phi)] . F_pa=1.. // // CONSTANT STOCK-RECRUITMENT // TRAJECTORIES function y=mini_constant(x) y= mini(RR) . M=1.4].10+i) .3]).. // // // LINEAR STOCK-RECRUITMENT xset("window".3].T.traj’. weight=10^(-3)*[16. // R_mean R_gm R_min 2002 (ICES) R_min 2004 (ICES) B_lim=21000 * 10^3 .. 36].. 28. // natural mortality N2003=10^6*[1192 333 255]’.2.
41) We take into account the scarcity of the resource by requiring 0 ≤ S(t) . The extraction r(t) is irreversible in the sense that 0 ≤ r(t) . (2. (2. (2. (2.44) A sustainability requirement can be imposed through some guaranteed con- sumption level c along the generations: 0 < c ≤ c(t) .39) K(t + 1) = (1 − δ)K(t) + Y K(t). (2. t + 1[). We also assume the investment in the reproducible capital K to be irre- versible in the sense that 0 ≤ Y K(t). Parameter δ is the rate of capital depreciation. K(t) represents the accumulated capital. referring to a strong sustainability concern whenever it has a strictly positive value. We also consider that the capital is non negative: 0 ≤ K(t) .43) We thus ensure the growth of capital if there is no depreciation. r(t) stands for the extraction flow per discrete unit of time. we can consider a stronger conservation constraint for the resource as follows S ≤ S(t) . The most usual example of production function is the so-called Cobb-Douglas Y (K. the economy with the exhaustible resource use is then described by the dynamic S(t + 1) = S(t) − r(t) . (2. Additional constraints can be taken into account. (2. The controls of this economy are levels of consumption c(t) and extrac- tion r(t) respectively. More generally. r(t) − c(t) .40) where the exponents α > 0 and β > 0 represent the elasticities of production related to capital and resources respectively. r) = AK α rβ .36 2 Sequential decision models In a discrete time version.42) where S > 0 stands for some guaranteed resource target. where S(t) is the exhaustible resource stock (at the beginning of period [t. c(t) stands for the consumption and the function Y represents the technology of the economy.45) The optimality problem exposed in [12] is . r(t) − c(t) .
(2. each biomass would follow sepa- rately Nj (t+1) = g Nj (t) as in (2.47) . better habitat. One model with migration and catches hj (t) is. often on the order of 20 − 30% of the coast- line. 2. . This change in scale coincided with several important papers on fisheries management. t + 1[ in this model. Let us now present mono-specific metapopulation modeling. 2. The main effects expected from the establishment of reserves are increased abundances and biomasses of spawn- ing stocks and recruitment inside the protected area and. Without interference and harvesting. k=j k=1. n. n n Nj (t + 1) = g Nj (t) + τk. Such a model questions how technology impacts the feasible or optimal extraction and consumptions paths. . in surrounding areas through spillover. that conventional methods were to blame. Notice that catches hj (t) take place at the end of period [t. call- ing for modest areas in which ecologists could examine unexploited systems. rebuilding of ecosystems and protection of habitat. for any j = 1. Several models have been developed to investigate the effectiveness of MPA in terms of stock conservation and catches. and that a new approach to management was required.r(·) t=t0 where ρ ∈ [0. The idea of closing areas as a fishery management instrument appeared two decades ago among marine ecologists. . By the early 1990s. c(·). Other potentially significant conservation and resource-enhancement benefits also include enhanced biodiversity. . 1[ is a discount factor.8 An exploited metapopulation and protected area Many works advocate the use of reserves as a central element of ecosys- tems and biodiversity sustainable management.k < 1 measures the migration rate from area j to patch k and hj (t) stands for the catches in area j. a major harvesting constraint becomes 0 ≤ hj (t) ≤ qj . The first proposals focused on protected areas as laboratories. the idea had evolved into a larger vision that called for significant areas to be set aside. If protected area requirements are introduced. Most of these studies claimed that the world’s fisheries were in a state of crisis. An extensive review of the litera- ture can be found in [32. 19].8 An exploited metapopulation and protected area 37 +∞ max ρt L(c(t)) .46) k=1.7). increased catches and a hedge against management failures. k=j where 0 ≤ τj.j Nk (t) − τjk Nj (t) − hj (t) (2. Consider n biomasses Nj located in n patches which may diffuse from one patch to the other.
. 0≤hj (t) 0≤hj (t)≤qj t=t0 j=1 t=t0 j=1 In this framework. . a classical approach of control theory considers such problems through a state space formulation where decisions. . . 1[ is a discount factor. up (t) . . 0≤hj (t)≤qj t=t j=1 0 where ρ ∈ [0. They are basically decision-making problems where time plays a central role. t = t0 . u(t) . In a compact form. . x(t). . In a discrete time context. n explicit. Control theory of dynamic systems is well suited to tackling such situations and building up mathematical models with analytic. . In par- ticular. xi (t0 ) = xi0 . . t0 + 1. t ≥ t0 . T − 1 . t0 + 1. . A decision problem is to maximize the utility derived from the catches as follows +∞ n max ρt L hj (t) . . . . . algorithmic and/or numerical methods. T − 1.48) x(t0 ) = x0 .38 2 Sequential decision models where qj = 0 if the area is closed. Basically. commands or actions influence the evolution of a state variable in a causal way. 2. x1 (t). and in specific terms making the components i = 1. specifying the formulation of the dynamical model is the first phase of the analysis.1 The dynamics In the usual approach to a control problem. . the role played by the geometry of the reserve in relation to the diffusion characteristics is a challenging issue. xn (t). this is a difference equation11 : xi (t + 1) = Fi t. . a reserve effect on catches means that +∞ n +∞ n ∃ qj = 0 such that max ρt L hj (t) < max ρt L hj (t) . (2. the dynamic is represented by the differential equation ẋ(t) = F t. . . a dynamical model or dynamical system is: x(t + 1) = F t. . In this perspective.9 State space mathematical formulation Although the models previously introduced for the management of exhaustible and renewable resources and pollution control are different. Here we denote by: 11 In the continuous time context.9. x(t). t = t0 . . their main struc- tures are quite similar. u1 (t). . the purpose of control the- ory is to find relevant decision or control rules to achieve various goals. 2. u(t) .
. chosen by the decision- maker and which causes the dynamic evolution of the state x according to the transition equation (2. . • F : N × X × U → X. the time index. . .49) 2. • x(t) = x1 (t).2 The trajectories A state trajectory. x(t0 + 1). . one considers instead sequences x(·) := (x(t0 ). . u(T − 1) with u(t) ∈ U . u(T − 1) . xn (t) . . . thus t runs from t0 to T . namely X = Rn . u) = F (t)x + G(t)u. 1. . u(t − 1). namely U = Rp . the initial state or initial condition. u(·) := x(t0 ). . the ultimate control u(T − 1) generates a final state x(T ). x(T ) with x(t) ∈ X (2. • u(t) = u1 (t). . x(t0 + 2). of particular interest are those x(·).50) and a control trajectory.48). in many cases. is any sequence x(·) := x(t0 ).48). .) and the trajectories space is XN × UN . consisting of state and control trajectories x(·). . this state is an element of some state space denoted by X. . this decision belongs to some decision space denoted by U. and G is a matrix with n rows and p columns. x. . . or state path. the dynamic F does not depend on time t and is said to be autonomous or stationary. x(t0 + 1). . where F (t) is a square matrix of size n. of the state are generated by this initial state and the sequences of controls via the transition equation (2.48). u(t0 ). . . giving x(t + 1) = F (t)x(t) + G(t)u(t) . When T = +∞. .51) T −t0 The trajectories space is X T +1−t0 ×U . we shall consider a finite dimensional space.9. . . . 2. observe that all subsequent values x(t0 + 1). .. . x(T − 1). up (t) . (2. . . . . u(t0 + 1). . . . we shall restrict ourselves to the usual case corresponding to finite dimensional space. . (2. belonging to the set of integers N.) and u(·) := (u(t0 ). (2.9 State space mathematical formulation 39 • t. the control or decision. . x(t) is a function of the initial condition x(t0 ) and of past controls u(t0 ). is any sequence u(·) := u(t0 ). be it finite (T < +∞) or infinite (T = +∞). The linear case corresponds to the situation where the dynamic F can be written in the form F (t. u(·) which satisfy the dynamical equation (2. .48). t0 is the initial time and the integer T > t0 stands for the time horizon. the dynamics-mapping representing the system’s evolution. . considered at initial time t = t0 ∈ {0. • x0 . x(T ). . T − 1}. or control path. . . u(t0 + 1). u(t0 + 1). the state. x(t0 + 1). Notice that when T < +∞ there are T controls and T + 1 states: indeed. . embodying a set of variables which sum up the information needed together with the control to pass from one time t to the following time t+1. . by (2.52) Among all trajectories.
bik t. and/or equality form ae1 t. . State constraints. . bel are real-valued. t = t0 . x(t). Frequently. the usual case corresponds to a constant set of feasible state values A which does not depend on time in the sense that we require x(t) ∈ A. u(t − 1). x(t). .3 The feasible decisions Each value u(t) of u(·) specifies the control that will be chosen at time t: such a control is called a decision at time t. by u(t) ∈ B t. described as follows. . As displayed by previous examples. x(t). . T − 1 .. and/or equality form be1 t. x(t) ≥ 0 . . (2. . aim t. u(t) = 0 . at each time t. . . . . . .40 2 Sequential decision models 2. . x(t). . including the states and the decisions. x(t) = 0 . As shown in the examples above. . u(t) ≥ 0 . (2. . the state belongs to a non empty state domain A(t) ⊂ X x(t) ∈ A(t). It is required that. we may need to impose conditions or constraints on the system. Decision or control constraints. .. u(t) = 0 . at each time t. . . . . u(t) ≥ 0 . t = t0 . . x(t) ≥ 0 . . we con- sider a constant set of feasible control values B and we ask for u(t) ∈ B. . x(t) . . The admissible decisions are described. .. .53b) generally specified under the inequality form ai1 t. especially when a decision at time t depends on the past states x(t0 ).9. bel t. A rule that assigns a sequence of decisions is called a policy or a strategy. . x(t) = 0 .. . . where the functions bi1 . x(t) ⊂ U is some non empty subset of the control space U. . T − 1 . . bik .53a) where B t. This subset is generally specified under the inequality form bi1 t. . aeq t. . . be1 . x(t) and controls u(t0 ). .
u(·) = L t. u(t) dt. . • Additive criterion (without inheritance). we shall rather deal with maximization problems where the criterion is a payoff. The so-called viability or invariance approach focuses on the role played by these different admissibility constraints. It is the most usual crite- rion defined12 in the finite horizon case by the sum −1 T π x(·). The usual selection of a decision sequence consists in optimizing (minimiz- ing or maximizing) some π criterion. representing the total cost or pay- off/gain/utility/performance of the decisions over T + 1 − t0 stages. x(t).9. . . A criterion π is a function π : XT +1−t0 × UT −t0 → R which assigns a real number to a state and control trajectory. and/or equality form ae1 T. u(·) = t0 L t.4 The criterion and the evaluation of the decisions Now. the above statements may be understood as limits when time goes to infinity. the usual present value 12 Whenever time is considered continuous. one may try to se- lect a sequence of control variables among the feasible and tolerable ones. When T = +∞. They are studied especially in Chap. 2. Admissible equilibria shed a particular light on such feasibility issues. aeq T. . u(t) . called the target. x(T ) = 0 . 4. Following the classification of [20] in the context of sustainability. we distinguish the following criteria.54) t=t0 Function L is referred to as the system’s instantaneous payoff or gain. . etc. utility. . This target issue is closely related to the controllability concept studied in the control system literature [15]. (2. This point is examined in more detail in Chap. . profit. benefit. . Here it is required that the final state reaches some non empty state domain A(T ) ⊂ X. x(T ) ≥ 0 . In economics or finance.9 State space mathematical formulation 41 Final state constraints. Here- after. x(t). x(T ) = 0 . given an initial state x0 and an initial time t0 . T the intertemporal criteria is defined by the following integral π x(·). 2. (2. x(T ) ≥ 0 . aim T. that is x(T ) ∈ A(T ) . 3.53c) generally specified under the inequality form ai1 T. .
u(t) . The present value with inheritance will also be pre- sented in the Chichilnisky type criterion definition. (2. The instantaneous gain L x(t).. u) = x R(t)x + u Q(t)u... u(·) = ρt L x(t). For instance. In economics literature. u(·) = min min L t.. giving: −1 T π x(·). as in [30].. Other references include [13. x(t). u(·) = ρt L x(t). will be seen later. the Maximin approach has been discussed as an equity criterion [2. x(T ) . u(t) may be a profit or a utility. 34]. t=t0 . u(t) .. it has been used in environmental economics to deal with sustainability and intergenerational equity [4]. 26. In the infinite horizon case. 25. This approach favors the present through the discount of future value and is sometimes qualified as “dictatorship of the present” because it neglects the future needs as soon as ρ < 1.... In the infinite horizon. u(t) .. u(·) = min L t. u(t) . (2.+∞ The ultimate generation T may also be taken into account by considering π x(·). we obtain π x(·). (2.42 2 Sequential decision models (PV) approach corresponds to the time separable case with discounting criterion in the form of [16.. u(t) . u(·) = inf L t.56) t=t0 The quadratic case corresponds to the situation where L and M are quadratic in the sense that L(t. [33] examines the optimal and equitable allocation of an exhaustible resource. where R(t) and Q(t) are positive matrices. In particular.57) t=t0 .. M T. • The Maximin.55) t=t0 where ρ stands for a discount factor (0 ≤ ρ ≤ 1).58) t=t0 . with the addition of a final payoff at final time T . x(t). 30]. The Rawlsian or maximin form in the finite horizon is π x(·). t=t0 The case with inheritance. x.T −1 . 22] −1 T π x(·). (2.T −1 The criterion focuses on the instantaneous value of the poorest genera- tion. x(t). we consider +∞ π x(·). u(·) = x(t) R(t)x(t) + u(t) Q(t)u(t) .
(2. As the state x generally refers to the natural resource. u(·) = lim inf M T. u(·) = L t. 2. u(·) = M T.62) t=t0 Let us remark that such a case with scrap value can be associated with a Chichinilsky formulation for θ = 1/2. settle the set of all possible and feasible state and decision trajectories. (2. it corresponds to π x(·). x0 ) ⊂ XT +1−t0 × UT −t0 . x(T ) . x(T ) (2.61) t=t0 where θ ∈ [0. denoted by T ad (t0 .59) which puts weight only on the final payoff associated with the state x(T ) of the resource. x(t). Originally formulated in the infinite hori- zon. (2. combined with the dynamics (2. u(t) + (1 − θ)M T. x(T ) . Such a feasibility set.60) T →+∞ • Chichilnisky type criterion. x(T ) .9 State space mathematical formulation 43 • Green Golden type criterion.53b) and (2. the so-called Chichilnisky criterion is a convex combination of present value and Green Golden criteria [6]. 1] stands for the coefficient of present dictatorship. is defined by .53c) specified beforehand. Originally formulated in infinite horizon. u(·) = θ L t.53a). This criterion makes it possible to avoid both the dictatorship of the present and the dictatorship of the future. This approach considers only the far future and is qualified as “dictator- ship of the future” because it neglects the present needs.9. In our discrete time framework when the horizon T is finite. the so-called “Green Golden” form introduced by [7] and discussed in [20] puts emphasis on the ultimate payoff. (2. we shall label of Chichilnisky type a criterion of the form −1 T π x(·). when the horizon T is finite. such an approach may also fa- vor the ecological or environmental dimensions justifying the term “green rule. we label Green Golden a criterion of the form π x(·).” In the infinite horizon case. 2.48). u(t) + M T. It is defined in the finite hori- zon case by the sum: −1 T π x(·). x(t). In our discrete time framework. • Additive criterion (with inheritance).5 The optimization problem The constraints (2.
x(t) . possibly. the optimal control problem is defined as the following optimization problem: sup π x(·). u (T − 1) denotes a feasible optimal decision trajectory and x (·) = x (t0 ). t = t0 . T (2. u(·) .x0 ) 2. T − 1 T ad (t0 .63). . x (T ) an optimal state trajectory.53b)−(2. (2. . we generally assume that the supremum is achieved. . such as solutions of (2. u (·) ∈ arg max π x(·).67) x(·). u (t0 + 1). x (t0 +1). . x0 ) := x(·).64) reads π x (·). .44 2 Sequential decision models x(·).x0 ) where u (·) = u (t0 ). .10 Open versus closed loop decisions We point out two distinct approaches to compute relevant decision sequences.u(·) ∈T ad (t0 . t = t0 . ⎧ ⎫ ⎪ x(t0 ) = x0. (2. x0 ) defined in (2. .63) We now aim at ranking the admissible paths according to a given criterion π previously defined. .x0 ) Abusively.65) u(·) Since we are interested in the existence of optimal admissible decisions. u(t) . u(·) satisfies (2. u(·) .53c) .66) x(·).u(·) ∈T ad (t0 . ⎪ ⎪ ⎨ ⎪ ⎬ x(t + 1) = F t. . (2. (2. . T − 1 ⎪ ⎪ ⎩ ⎭ x(t) ∈ A(t). . By relevant is meant at least admissible decisions. . u(·) . optimal ones. u(·) . we shall often formulate the hereabove optimization problem in the simplified form sup π x(·). u(·) . x0 ) ⇐⇒ x(·). the following notation is used: x (·). and. . . x(t). that is to say elements of the set T ad (t0 .48)−(2. . u(·) ∈ T ad (t0 . . . Hence. t = t0 . In other words. ⎪ ⎪ u(t) ∈ B t.64). . . . u (·) = max π x(·).u(·) ∈T ad (t0 . Hence the supremum sup becomes a maximum max (or inf = min for minimization) and the prob- lem (2.64) x(·). . Of particular interest is an optimal solution.53a)−(2. Equivalently.
the key concept is to manipulate control trajectories depending only on time u : t . 2.10 Open versus closed loop decisions 45 Open loop In this case.
then compute the state by the dynamical equation (2.64). called feedback. For the maximization problem (2. u(t) . x) . . Closed loop A second approach consists in searching for a control rule.48): x(t + 1) = F t. if every control u(t) lies in a finite dimensional space Rp it follows that we are coping with an optimization problem on Rp(T −t0 ) . u(t0 + 1). . Thus. . u(T − 1)). x(t). a mapping13 u depending on both the time t and the state x: u : (t. it boils down to maximizing the criterion π with respect to T −t0 variables (u(t0 ). when the horizon T is finite. .→ u(t) .
u(t). u(t − 1). 4 and 5 where we introduce the dynamic programming method. but only for the predictable x(t). . the mapping u(t. This second approach is more difficult in the sense that we now look for a function of the state and not only a sequence u(t0 ). 13 Note that u denotes a mapping from N × X to U. . . . 7 and 8. Furthermore. . . A solution is developed in Chaps. u(T − 1). x) ∈ U . looking for feedbacks turns out to be a relevant method for imple- mentation in real time. Hence. x(t) and x(t + 1) = F t. u(t) . x(t). one can specify more restrictive conditions on the feedback. Such ideas will be scrutinized in Chaps. Let us indicate that in the deterministic caseclosedand open loops are closely related because the state x(t) in u(t) = u t. linear or continuous or smooth feedbacks may yield interesting additional properties for the control and decision laws.→ u(t. For instance. x) is not used for all values of x. . In fact. Then the control and state trajectories are recovered by the relations u(t) = u t. . x(t). 6. . whenever the system is under disturbances or uncer- tainty x(t + 1) = F t. while u denotes a variable belonging to U. w(t) not directly taken into account by the modeling. x(t) is completely computed from the dynamic F and the previous x(t0 ) and u(t0 ).
1} illustrate this configuration.5. So if a computer’s ram has 8 GBytes = 8 (1 024)3 bytes = 233 bytes. .5. corresponding to an annual problem with a weekly step size. ∃u ∈ B(t. 2. we can: • represent the set of all feasible trajectories x(·) generated by (2.11 Decision tree and the “curse of the dimensionality” x(2) ua x(1) b b ub ua b b b b x(2) x(0) @ x(2) @ ua"" ub@ " @ "" @ x(1) @ @ ub @ @ @ x(2) Fig. . Binary decisions where u ∈ U = {0.48) starting from x(0) by a tree. 1} on horizon T . To get a taste of it. x) such that y = F (t.46 2 Sequential decision models 2. u(T − 1)) ∈ {0. Binary decision tree Whenever the time horizon term T along with the set of controls U are finite. consider a binary decision u ∈ {0. it may yield a difficult numerical situation and a so-called curse of the dimen- sionality. a double-precision real requires 8 bytes = 23 bytes. we can store up to 230 double-precision reals. Indeed. u) . . providing 2T possible sequences (u(0). the graph theory together with operational research constitute relevant frameworks to handle dynamical decision issues. 1}T . as in Fig. Although this method seems useful and easy to implement on a computer. On a computer. . 2. One can thus imagine the difficulties implied by the comparison of 252 criterions’ final values for a horizon T = 52. x. . • evaluate the performance and the criterion on every admissible path in order to choose the optimal one. given an initial condition x(0) at initial time t0 = 0. where the states x(t) are associated with nodes and decisions u(t) correspond to edges of the graph defined by the relation xRy ⇐⇒ ∃t ≥ 0 .
References [1] D. Social Choice and Welfare. 13(2):219–248. Nichols. Doyen. Caswell. [4] R. M. 2000. 1990. Natural Resource Economics. and M. [9] J. 2002. Heal. Analysis and Management of Animal Populations. [10] J. Burmeister and P. G. and D. Massachusets. [11] P. 1977. 45(4):853–870. Chichilnisky. 1982. second edition. and M. Sustainability of ex- ploited marine ecosystems through protected areas: a viability model and . 1999. 41:1–28. Cairns and N. P. Long. Resource Economics. Beltratti. 49:175–179. New York. J. Review of Economic Studies. Byron. 11:275–300. Basil Blackwell. Sunderland. De Lara. Bertsekas. Hammond. second edition. The Control of Resources. 47:551–556. Cambridge University Press. [13] A. V. Ferraris. Maximin paths of heterogeneous cap- ital accumulation and the instability of paradoxical steady states. 1996. Dynamic Programming and Optimal Control. Dixit. The Green Golden rule. J. Econo- metrica. 1980. [6] G. W. Massachussetts. second edition. Volumes 1 and 2. The optimal depletion of exhaustible resources. Clark. Review of Economic Studies. D. and A. Wiley. 1974. Eco- nomics Letters. Hammond. [7] G. [14] L. P. Oxford. Sinauer Associates. Matrix Population Models. Dasgupta and G.J. [5] H. Conrad. Pelletier. Chichilnisky. [2] E. Maximin: a direct approach to sustainability. Clark. M. J. Conrad and C. Cambridge University Press. W. 2001. Environment and Development Economics. An axiomatic approach to sustainable development. 1987. 2006. On Hartwick’s rule for regular maximin paths of capital accumulation and resource depletion. Belmont. Symposium on the Eco- nomics of Exhaustible Resources. Heal. Mathematical Bioeconomics. Academic Press. 1995. Hoel. Athena Scientific. [12] P. [8] C. M. [3] K. Conroy. Dasgupta.
J. [15] B. Friedland. Deriso.48 References a coral reef case study. 542 pp. Biological Resource Management Series. Martinet and L. E. Richels. 1954. Cambridge University Press. B. Control System Design. [22] T. Oxford. New York. 107:356–376. Schaefer. New York. Koopmans. [19] R. 2007. Optimal co2 abatement in the presence of induced technical change. 39:1–38. 1:25–56. Rawls. [24] A. D. 39:137–175. A mathematical theory of saving. Journal of Environmental Economics and Management. Q. Kot. Resource and Energy Economics. Goulder and K. 62:124–142. Energy Policy. 1928. In Decision and Organization. [27] W. Journal of Political Economy. [21] H. Some aspects of the dynamics of populations important to the management of commercial marine fisheries. B.17–39. Journal of Bioeco- nomics. The economic theory of a common property resource: the fishery. 1972. [30] J. and V. [18] L. The economics of exhaustible resources. [23] M. Elements of Mathematical Ecology. New York. [29] F. . Gollier. 23:17–34. MIT Press. [17] H. Heal. Economic Theory and Sustainability. Jour- nal of Economic Theory. Journal of Environmental Economics and Management. [31] M. 38:543–559. Valuing the Future. and R. 1995. [20] G. H. 2002. 2001. [32] M. 2000. merge: A model for evaluat- ing regional and global effects of ghg reduction policies. The Economics of Risk and Time. T. Economic impacts of marine reserves: the importance of spatial behavior. November 2007. pages 79–100. 1994. [26] T. Ramsey. 208(2-4):353–366. The bioeconomics of marine reserves: A selected review with policy implications. Smith and J. 46:183–206. 1986. Gordon. Cambridge. Schneider. Mitra. Quantitative Fish Dynamics. 2001. 2003. Wilen. Mac Graw-Hill. Nordhaus. 7(2):161–178. Hotelling. Bulletin of the Inter- American tropical tuna commission. [25] V. MIT Press. april 1931. S. Clarendon. 29(1):p. Quinn and R. North-Holland. 1998. C. Oxford University Press. Doyen. Managing the Global Commons. Mendelsohn. A theory of Justice. [16] C. 1999. Grafton. Representation of preference orderings over time. Cambridge. 1971. Mathai. Cambridge. 1954. Sustainable management of an exhaustible resource: a viable control approach. The Economic Journal. Columbia University Press. Journal of Political Economy. Kompas. D. R. 2005. Manne. Ecological Modelling. [28] T. Intertemporal equity and efficient allocation of resources.
Solow. Review of Economic Studies. Characterizing sustainability: the converse of Hartwick’s rule. References 49 [33] R. . 23:159– 165. 1974. Journal of Economic Dynamics and Control. 41:29–45. Asheim. Symposium on the Economics of Exhaustible Resources. [34] C. M. 1998. Withagen and G. Intergenerational equity and exhaustible resources.
.
In particular. the dynamics behaves. Usual tools of linear algebra including eigenvalues can then be invoked. the notions of maximum sustainable yield. similarly to its linear ap- proximation involving the first order derivatives. A second part is devoted to the concept of stability in the context of open-loop decisions. . Designed for autonomous systems. A first Sect. The basic idea of linearization is that.e.4 and applied to some examples in the remaining sections.2. detailed concepts and results dealing with stability can be found in [8.3. In Sect.3 Equilibrium and stability A key concept for the study of dynamical systems is stability. 9] and [6] for results on stability property and the Lyapunov approach. The present chapter is organized as follows. in a small neighborhood of an equilibrium. Here we restrict the methods to the use of linearized dynamics. Equilibria highlight sustainability concerns in an interesting way as empha- sized by the sustainable yield approach used for the management of renewable resources [2. 3. From the mathematical viewpoint. 3. 4. The method of linearization is exposed in Sect. Examples coping with ex- haustible and renewable resources or pollution management illustrate the con- cept in Sect. Basically. particular emphasis is given to different bioe- conomic issues related to the notion of sustainable yield. The most commonly tracked trajectory is that of equi- librium. a dynamical system is stable with respect to a given desired trajectory if weak perturbations cause only small variations in the trajectories with respect to the one being tracked. 5]. an equilibrium of a dynamical system corresponds to a sta- tionary state and is associated with fixed points of the dynamics in the discrete time case. 3. i. private property or common property equilibria capture important ideas for bioeconomic modeling. when dynamics does not directly depend on time. in most cases. 3.1 introduces the notion of equilibrium for controlled dynamics.
(3. . The resource stock Se and harvesting he are stationary whenever . . . t0 + 1. (3.1) under constraints (3. The state xe ∈ X is an admissible equilibrium.1 Exploitation of an exhaustible resource We recall the system introduced in Sect. ue ) is an admissible equilibrium. of the autonomous dynamical system (3. .1. . 3. Basically. 2. this means that we face problems of fixed points.2) u(t) ∈ B x(t) .2. . .3) By extension. Similarly.1) where x(t) ∈ X = Rn represents the state of the system and u(t) ∈ U = Rp stands for the decision vector as in (2. ue ) = xe with ue ∈ B(xe ) and xe ∈ A . (3. namely: x(t + 1) = F x(t). u(t) . with x(t0 ) = x0 . . we shall also say that (xe . . in the sense that the dynamics does not depend directly on time t. For the discrete time case on which we focus. or stationary dynamics. we describe the equilibria if any exist. 1 .48). such an equilibrium is related to both a stationary admissible state and a stationary decision. we deal with autonomous dynamics.52 3 Equilibrium and stability 3.1 Equilibrium states and decisions In this section. Definition 3. s = 0. t0 + 1. t = t0 . 3. an equilibrium of a dynamical system corresponds to a situation where the evolution is stopped in the sense that the state becomes steady: x(t + s) = x(t) . decision and state constraints are time independent: x(t) ∈ A . In the framework of controlled dynamical systems. or steady state. x0 ∈ X is the initial condition at initial time t0 ∈ N.1 for the management of an ex- haustible stock S(t): S(t + 1) = S(t) − h(t) . t = t0 .2) if there exists a decision ue ∈ U satisfying F (xe .2 Some examples of equilibria For some of the models presented in Chap. 2.
the only equilibrium solution for any resource level Se is zero extraction: he = 0. in absence of a plus-group. and any equilibrium (Me . ⎟ ⎜ . αEbau αEbau we see that the level of abatement to stabilize concentration at Me is sensitive to carbon removal rate δ.6. . ae ) satisfies αEbau (1 − ae ) Me = M−∞ + with 0 ≤ ae ≤ 1 .9.2. 5. λe ) such that g(Ne . NA . This observation means that the only equilibrium config- uration is without exploitation.3. 3. the dynamic (2.. 3. .20) becomes M (t + 1) = M (t) + αEbau 1 − a(t) − δ(M (t) − M−∞ ) .2.2 Mitigation policies for carbon dioxyde emissions Assuming stationary emissions Ebau ≥ 0 in the carbon cycle model of Sect. 2. 3. this is not a challenging result in terms of management. ⎟ ⎜ ⎟ ⎜ ⎟ ⎜ ⎟ ⎜ NA−2 exp − (MA−2 + λFA−2 ) ⎟ ⎝ ⎠ NA−1 exp − (MA−1 + λFA−1 ) . The equilibrium approach is of little help. where the dynamic g is given. λ) =⎜ ⎟ ⎜ . . 2. The opti- mality approach is more fruitful and will be examined in Sect.3 Single species equilibrium in an age-structured fish stock model The model. Of course. is derived from fish stock man- agement. As expected. . by ⎛ ⎞ ϕ SSB(N ) ⎜ ⎟ ⎜ N1 exp − (M1 + λF1 ) ⎟ ⎜ ⎟ ⎜ ⎟ ⎜ ⎟ ⎜ N2 exp − (M2 + λF2 ) ⎟ ⎜ ⎟ ⎜ ⎟ g(N1 . We compute an equilibrium (Ne . δ When we write it as δ(Me − M−∞ ) δ(Me − M−∞ ) ae = 1 − when 0≤ ≤1. already introduced in Sect.2 Some examples of equilibria 53 Se = Se − he . λe ) = Ne .
e (λ) = Z(λ) and Na. . . gives N1.54 3 Equilibrium and stability with spawning stock biomass SSB defined by A SSB(N ) := γa υa Na . a=1 and ϕ a stock-recruitment relationship. for λ ≥ 0. . .e (λ) = sa (λ)Z(λ) . The computation of an equilibrium Ne (λ). .4) is the proportion of equilibrium recruits which survive up to age a (a = 2. The number Z(λ) of recruits at equilibrium is a nonnegative fixed point of the function z . . a = 1. A where sa (λ) := exp − M1 + · · · + Ma−1 + u(F1 + · · · + Fa−1 ) (3. . A) while s1 (λ) = 1. .
b spr(λ) 3. re − ce . as we have seen in Subsect. 0 .7 is governed by the evolution of S(t + 1) = S(t) − r(t) . As soon as resource r is needed for production. the solution can be specified as follows: R spr(λ) − 1 Z(λ) = max . then Y (K. the overall system has no other equilibrium than with re = 0. The equilibrium approach is of little help in terms of management in this case. We do not go into detail on existence results of such a fixed point. K(t + 1) = (1 − δ)K(t) + Y K(t). Even if the second equation has. re ) ∈ R3+ solution of 0 = −δKe + Y Ke . However. r(t) − c(t) . in the Beverton-Holt case where the recruitment mechanism corresponds to RB ϕ(B) = 1+bB .1. namely A spr(λ) := γa υa sa (λ) .4 Economic growth with an exhaustible natural resource Recall that the economy in Sect.→ ϕ zspr(λ) where spr corre- sponds to the equilibrium spawners per recruits. an equilibrium (Ke .2. .2. ce . a=1 Being a fixed point means that Z(λ) is the solution of the equation: Z(λ) = ϕ Z(λ)spr(λ) . 0) = 0 and the only global admissible equilibrium is re = ce = Ke = 0 and the economy collapses. above right. 3. 2. by itself.
the Schaefer model (2. the renewable resource case is more interesting. for given Be . One obtains the so-called sustainable yield σ(Be ) by an implicit equation whenever. 3. Notice that if the dynamic g and the sustainable yield function B . giving: σ(Be ) := he ⇐⇒ Be = g(Be − he ) and 0 ≤ he ≤ Be .2 corresponds to: B(t + 1) = g B(t) − h(t) . common property.3 Maximum sustainable yield 55 3. Despite considerable criticism.14) introduced in Sect.6) The relation may also be written as he = g(Be − he ) − (Be − he ) ≥0. p. the harvesting he induces a steady population Be whenever Be = g(Be − he ) and 0 ≤ he ≤ Be . 1]. 3. 0 ≤ h(t) ≤ B(t) .3. Other equilibria deriving from different property rights on the resource are also presented.3 Maximum sustainable yield. he can be harvested forever. Indeed. (3.1 Sustainable yield for surplus model Designed for the management of renewable resources. 2. !"#$ ! "# $ ! "# $ surplus regeneration biomass after capture meaning that “a surplus production exists that can be harvested in perpetuity without altering the stock level” [2. The concept of maximum sustainable yield [2] is one of the cornerstones of the management of renewable resources.5) At equilibrium. (3. there exists a unique he satisfying the above equation. it remains a reference. private property. open access equilibria In contrast to the exhaustible resource management case where the equilib- rium approach does not bring challenging results. while the biomass is maintained indefinitely at level Be .
6) the marginal relation g B − σ(B) − 1 σ (B) = . it is worth distinguishing particular cases of such sustainable yields that play an important role in the economics literature for the manage- ment of renewable resources. (3. As in [5]. .7) g B − σ(B) Thus. the sustainable yield σ is the solution of a differential equation.→ σ(B) are differentiable. we can deduce from Be = g Be − σ(Be ) in (3.
8) B≥0. h=σ(B) B≥0 The maximum catch hmse is called the maximum sustainable yield (msy). hmse ) of σ(Bmse ) = hmse = max h = max σ(B) . (3.2 Maximum sustainable equilibrium The maximum sustainable equilibrium (mse) is the solution (Bmse .3. Whenever the sustainable yield function B .56 3 Equilibrium and stability 3.
Bppe ) = max R(h.9) It should be emphasized that such a steady state depends only on the biological features of the stock summarized by the function g. The economic rent or profit R(h. hppe ) which maximizes such a rent as follows: R(hppe . B). the ppe satisfies the following marginal conditions: p − Ch (hppe . B) are smooth. hmse ) solves g (Bmse − hmse ) = 1 and g(Bmse − hmse ) = Bmse . income and growth values.10) B≥0.3 Private property equilibrium Assuming a constant price p per unit of harvested biomass. h=σ(B) Assume that the harvesting costs C(h.7). Harvesting costs are C(h. B) denote the partial derivatives. using (3.7) when the dynamic g is supposed to be differentiable. The so-called private property equilibrium (ppe) is the equilibrium solution (Bppe . the maximum sustainable biomass (Bmse .11) p − Ch (hppe . Bppe ) g (Bppe − hppe ) = . (3. B) := ph − C(h. the total revenue resulting from harvesting h is ph. Beverton-Holt or logistic growth relations.3. .→ σ(B) is differentiable. the first order optimality condition reads σ (Bmse ) = 0 . Bppe ) It can be pointed out that ppe equilibrium combines ecological and eco- nomic dimensions through the marginal cost. More specific computations of mse are displayed in the following paragraphs for linear. Consequently. B) . Bppe ) − CB (hppe . (3. By writing first order optimality con- ditions and using (3. 3. (3. B) and CB (h. B) . and let Ch (h. B) provided by the management of the resource is defined as the difference between benefits and harvesting costs: R(h.
3. σ(Bcpe ) of R(hcpe . which can be written ch C(h. by (3. hcpe = σ(Bcpe ) and phcpe = C(hcpe . unlike the private property equilibrium which also depends on dy- namic g. hcpe ) = captures Bcpe . that is. what- ever the natural dynamic g. we obtain that • the sustainable yield function is R−1 σ(B) = B. The harvesting costs are assumed to be proportional to effort as in (3. only on economics parameters (unitary cost c and price p).3. 3. the sustainability and conservation re- quirements are in jeopardy through the cpe as soon as unit costs c decrease or price p strongly increases since Bcpe may then drop. 2. The so-called common property equilibrium (cpe) this situation of zero-profit as a solution (Bcpe . Bcpe ) = 0 . In this case. R • the maximum sustainable equilibrium does not contain much information since Bmse = hmse = +∞ . Bcpe ) . (3.5 Examples for different population dynamics We follow here the material introduced in Sect. and q a catchability coefficient. pq Under the open access assumption.15)).12).13).12) For the sake of simplicity. we assume that the harvesting costs are propor- tional to effort e = h/(qB) (see (2. In this case.6 shows how this concept can be derived from an equilibrium perspective on an extended dynamic with one additional state component. 3. 25].4 Common property equilibrium In the open access perspective. . apart from the catchability coefficient q. The linear model Consider g(B) = RB with R ≥ 1. (3.2. p.13) qB with c a unit cost of effort. A forthcoming Subsect. it is assumed that any positive rent is dis- sipated [2. the common property equilibrium Bcpe satisfies. c Bcpe = .3 Maximum sustainable yield 57 3.3. B) = . Notice that the common property equilibrium depends.3.
. (3./ ( R_BH .K. K = K_tuna. p_tuna=600. The last inequality ensures an admissibility requirement 0 ≤ σ(B) ≤ B...b_BH *B ) ) . SY=B-( B .58 3 Equilibrium and stability • neither is the private property equilibrium a useful concept since Bppe = hppe = +∞ . // private property equilibrium // SUSTAINABLE YIELD FUNCTION cost=c_tuna.1.. // discrete-time intrinsic growth // maximum sustainable yield R=R_tuna.sqrt(R_BH) ) / b_BH .sqrt(R_BH . xtitle("Sustainable yield for the . B_PPE = .H_MSY. b_BH = (R_BH-1) / K .20). // B_MSE = ( R_BH .15) b . R_tuna=2.(b_BH * cost / price) ) ) / b_BH .1). (3..style=-6)..1. abcisse=linspace(0. // BEVERTON-HOLT DYNAMICS Beverton-Holt model (tuna)".sust_yield(abcisse).K. Scilab code 4. 1 + b(Be − he ) and the sustainable yield corresponds therefore to B R−1 σ(B) = B − for 0 ≤ B ≤ K := . K_tuna = 250000.. The notation K stems from the fact that R−1 b is the carrying capacity of the biological dynamic. // unit cost of effort in dollars per standard fishing day H_MSY=linspace(0.14) R − bB b This is illustrated in Fig. xbasc(). "biomass (metric tons)". 3. he ) satisfies R(Be − he ) Be = and 0 ≤ he ≤ Be .100). • A first order optimality condition gives the mse: √ R− R Bmse = .1*MSY]).rect=[0. function [SY]=sust_yield(B) price=p_tuna. // // maximum sustainable equilibrium // exec sustainable_yield_tuna.25. Of course."catches (metric tons)"). • Any admissible equilibrium (Be . The Beverton-Holt model RB Assume that g(B) = 1+bB with growth R > 1 and saturation b > 0 parameters. c_tuna=2500. plot2d(abcisse. the biomass K = R−1 b is the only strictly positive equilibrium of the natural dynamic without harvesting. In other words. // market price in dollars per metric ton plot2d(B_MSE*ones(H_MSY). endfunction ( R_BH . harvesting decision constraints may more stringently restrict the domain of validity for this last relation. // carrying capacity in metric tons xset("window".sce MSY=sust_yield(B_MSE) .MSY. R_BH = R_tuna .0.
the private property equilibrium is % bc R− R− p Bppe = . Any equilibrium (Be . b Remark that ppe biomass is always larger than maximum sustainable equilibrium biomass in the sense that Bppe > Bmse . (3. κ By (3. The maximum sustainable equilibrium is achieved at Bmse = 150 000 metric tons. • Whenever the common property equilibrium solution of (3. i. 3. Sustainable yield for Beverton-Holt model with tuna data. 3. and provides the maximum sustainable yield hmse = 50 000 metric tons. 0 ≤ pc ≤ K or bc p ≤ R − 1.9).12) is admis- sible. The logistic model Consider g(B) = RB(1 − B κ ).16) In this sense.1. the mse (Bmse . The curve comes from Scilab code 4.3 Maximum sustainable yield 59 Sustainable yield for the Beverton−Holt model (tuna) 50000 40000 catches (metric tons) 30000 20000 10000 0 0 50000 100000 150000 200000 250000 biomass (metric tons) Fig. he ) satisfies (Be − he ) Be = g(Be − he ) ⇐⇒ Be = R(Be − he ) 1 − . the ppe equilibrium is more conservative than the mse.e. Biomass and catches are measured in metric tons. hmse ) solves in addition .
we have g(B) = B exp(r(1 − K B )). may generally be tested by a simple matrix analysis. ee ) satisfies c p c Be = and ee = σ( ) . any non trivial equilibrium (Be .17) e(t + 1) = e(t) + αR e(t). In this formulation. κ giving (R − 1)2 R2 − 1 hmse = κ and Bmse = κ. . Such an equilibrium (Be . B(t) .4 Stability of a stationary open loop equilibrium state By stationary open loop. the effort becomes a state of the dynamical system and there is no longer control in the dynamical system (3.17). 3. 2.60 3 Equilibrium and stability Bmse − hmse g (Bmse − hmse ) = R(1 − 2 )=1.18) pq c pq where σ stands for the sustainable yield function. The state follows a discrete-time dynamic. B = pqBe−ce. Then.3.6 Open access dynamics The open access situation occurs when no limitation is imposed on the harvest- ing effort. ee ) is termed Gordon’s Gordon’s bionomic equilibrium. and numerical solvers are required. the sustainable yield he = −he ) σ(Be ) is given by the implicit relation Be = (Be − he ) exp(r(1 − (BeK )). Consider any model of assessment and management of a renewable resource as in Sect. we mean that the control u(t) is set at a stationary value ue : u(t) = ue . We now postulate that the variations of harvesting effort are proportional to the flow of economic rent B(t + 1) = g B(t) − qe(t)B(t) . Of particular importance is the concept of asymptotic stability which. In this case. (3. assuming that the rent is defined by R e. 4R 4R The Ricker model Now. though subtle. (3. for which traditional notions of stability are presented. where parameter α > 0 measures the sensitivity of the agents possibly exploit- ing the resource with respect to profits. 3.2.
Consider state xe and decision ue satisfying (3. stability requirements are easy to characterize using linear algebraic calculus and. x(t0 ) = x0 . The basin of attraction of an equilibrium state xe is the set of initial states x0 ∈ X from which a solution x(t) of (3.2. one speaks of a globally asymptotically stable equilibrium state. Definition 3. for any neighborhood M(xe ) of xe .19) appears as a deterministic difference equation without control or decision.19) Equation (3.20) where A is a real square matrix of size n. Formal definitions dealing with the stability of the equilibrium state xe read as follows. in particular.1 General definition Stability of an equilibrium (xe . ∀t ≥ t0 . the so- lution x(t) of (3.19) turns out to be linear.19) approaches xe while t → +∞ ∀x0 ∈ N (xe ).4. it defines a dynamic linear system x(t + 1) = Ax(t) . 3.4. In this case. 3. x(t) ∈ M(xe ) . 1 This last property defines an attractive point.4 Stability of a stationary open loop equilibrium state 61 3. . (3.19) starts converging towards xe when t → +∞. a local property. Being stable means that any trajectory x(t) starting close enough to xe remains in the vicinity of xe . ue ) . 3.2 Stability of linear systems Whenever the dynamic (3.2. there exists a neighborhood N (xe ) of xe such that for every x0 in N (xe ). lim x(t) = xe . (3. Being asymptotically stable means that any trajectory x(t) starting close enough to xe remains in the vicinity of xe and converges towards xe as illustrated by Fig.3). When the basin of attraction of an equilibrium state xe is the whole state space X. to begin with. ue ) is. t→+∞ • unstable if it is not stable. • asymptotically stable if it is stable and if there exists a neighborhood N (xe ) of xe having the following property1 : for any x0 in N (xe ). ∀x0 ∈ N (xe ) . We consider the dynamics on a neighborhood of the equilibrium state xe with the fixed equilibrium decision ue as follows x(t + 1) = F (x(t).19) belongs to N (xe ) for every t ≥ t0 . The equi- librium state xe is said to be • stable if. the solution x(t) of (3.
62 3 Equilibrium and stability
eigenvalues2 . Let us recall how the asymptotic behavior of the trajectories for
the linear system (3.20) depends on the modulus3 of the eigenvalues (possibly
complex) of the matrix A. The set of all eigenvalues of the square matrix A is
the spectrum spec(A). The sketch of the proof of the following Theorem 3.3
is recalled in Sect. A.1 in the Appendix.
Theorem 3.3. The zero equilibrium state for the linear system (3.20) is
asymptotically stable if the eigenvalues λ ∈ spec(A) of the matrix A have
modulus strictly less than one:
max |λ| < 1 ⇐⇒ 0 is asymptotically stable for (3.20) .
λ∈spec(A)
Thanks to this result, we obtain a very simple criterion characterizing the
asymptotic stability of the equilibrium state xe = 0 of the linear system (3.20).
3.4.3 Linearization around the equilibrium
Unfortunately, in many cases, the dynamics around the equilibrium do not
display linear features. However, whenever dynamic F is continuously differ-
entiable, the linearization of the dynamics around the equilibrium generally
enables derivation of the local stability behavior of the system around this
equilibrium. This result stems from the fact that, close to the equilibrium
xe , dynamic F (x, ue ) behaves like its first order (or linear) approximation
involving the derivatives ∂F
∂x (xe , ue ) since
∂F
F (x, ue ) ≈ xe + (x − xe ) (xe , ue ) .
∂x
The linearized system associated with the dynamic (3.19) is
ξ(t + 1) = A ξ(t) , (3.21)
∂F
where the square matrix A = ∂x (xe , ue ) is the Jacobian matrix of the dynamic
⎛ ⎞
F 1 (x1 , x2 , . . . , xn , u)
⎜ .. ⎟
F (x, u) = ⎝ . ⎠
F n (x1 , x2 , . . . , xn , u)
at the equilibrium (xe , ue ):
2
Recall that an eigenvalue of the square matrix A is a complex λ such that there
exists a non zero complex vector v satisfying Av = λv. Eigenvalues are solutions
of the equation 0 = Det(A − λI), where I is the identity matrix.
3
For any complex z = a + ib ∈ C where i2 = −1, a ∈ R represents √ the real part,
b ∈ R stands for the imaginary part while the modulus is |z| = a2 + b2 .
3.5 What about stability for MSE, PPE and CPE? 63
⎛ ⎞
∂F 1 ∂F 1 ∂F 1
(x , u ) (xe , ue ) · · · (xe , ue )
⎜ ∂x1 e e ∂x2 ∂xn ⎟
∂F ⎜ ⎟
A= (xe , ue ) = ⎜
⎜
..
.
..
.
..
.
..
.
⎟ . (3.22)
⎟
∂x ⎝ ∂F n n n ⎠
∂F ∂F
(xe , ue ) (xe , ue ) · · · (xe , ue )
∂x1 ∂x2 ∂xn
We can obtain asymptotic stability results using linearized dynamics [10].
Theorem 3.4. Let xe be an equilibrium state of the dynamical system (3.19)
where F is continuously differentiable in a neighborhood of (xe , ue ). If the zero
equilibrium of the linearized system (3.21)-(3.22) is asymptotically stable, then
xe is asymptotically stable. In other words
∂F
max{|λ| , λ ∈ spec (xe , ue ) } < 1 =⇒ xe asymptotically stable.
∂x
If none of the eigenvalues of the Jacobian matrix (3.22) have a modulus exactly
equal to one, and if at least one eigenvalue has a modulus strictly greater than
one, then xe is unstable.
3.5 What about stability for MSE, PPE and CPE?
Due to the practical importance of management based on maximum sustain-
able yield management, private property, common property, or open access
equilibria, we provide an analysis of the stability of their equilibria.
We consider surplus models (3.5) for the management of a renewable re-
source. From Theorem 3.4, a sufficient condition for asymptotic stability of
(Be , he ) relies on the marginal condition
|g (Be − he )| < 1 .
We saw in (3.9) that the maximum sustainable equilibrium (Bmse , hmse ) sat-
isfies g (Bmse − hmse ) = 1, when Bmse > 0. The maximum sustainable equilib-
rium thus lies at the boundary between asymptotic stability and instability.
As far as the private property equilibrium ppe is concerned, it is asymp-
totically stable under some assumptions on the signs of the following partial
derivatives:
• Ch (h, B) ≤ p, meaning that an increment in catches increases the rent
since Rh (h, B) = p − Ch (h, B) ≥ 0;
• CB (h, B) ≤ 0, meaning that the harvesting costs decrease with the
biomass.
Indeed, from (3.11) we deduce that
p − Ch (hppe , Bppe )
0 ≤ g (Bppe − hppe ) = ≤1,
p − Ch (hppe , Bppe ) − CB (hppe , Bppe )
64 3 Equilibrium and stability
Abundances trajectories Abundances trajectories
400000 400000
350000 350000
300000 300000
abundances (whales)
abundances (whales)
250000 250000
200000 200000
150000 150000
100000 100000
50000 50000
MSE MSE
0 0
50 100 150 200 250 300 350 400 450 500 50 100 150 200 250 300 350 400 450 500
years years
(a) CPE Equilibrium: instability and ex- (b) PPE Equilibrium: stability
tinction from below
Fig. 3.2. Local stability of PPE and instability of CPE equilibria for Beverton-
Holt recruitment for Antartic blue whale data from [7]: intrinsic growth R = 1.05,
carrying capacity K = 400 000 whales, cost c = 600 000 $ per whale-catcher year,
catchability q = 0.0 016 per whale-catcher year and p = 7 000 $ per whale. Trajec-
tories are obtained by Scilab code 5. The straight line is the maximum sustainable
equilibrium mse.
and the private property equilibrium ppe is asymptotically stable.
Let us now examine the stability of the equilibria for the Beverton-Holt
RB
g(B) = 1+bB recruitment dynamic. Let (Be , he ) be an admissible equilibrium,
namely 0 ≤ Be ≤ R−1
b and he = σ(Be ) given by (3.14). We have
d R (R − bBe )2
g(B − he ) = 2 = .
dB |B=Be 1 + b(Be − he ) R
Thus, any equilibrium (Be , he ) is asymptotically stable if
(R − bBe )2 < R .
Since Be ≤ R−1 b , we obtain that R − bBe 0 ≥ 1 and we find the stability
requirement: √
R− R
< Be .
b
Consequently, equilibria Be need to be small enough for a feasible harvesting
to exist (Be ≤ K by (3.14)) while large enough for asymptotic stability to
hold true. Using (3.15), we thus establish the following requirements for an
equilibrium to exist and to be asymptotically stable.
Result 3.5 For the Beverton-Holt population dynamic, an equilibrium Be is
asymptotically stable if it lies between the maximum sustainable biomass and
the carrying capacity
Bmse < Be ≤ K .
3.5 What about stability for MSE, PPE and CPE? 65
Fig. 3.2 illustrates the stability results for the Antartic blue whale. Both
common property and private property equilibria are examined from data
provided in [7]: intrinsic growth is set to R = 1.05 per year, carrying ca-
pacity is K = 400 000 whales, unit cost is c = 600 000 $ per whale-catcher
year, catchability is q = 0.0 016 per whale-catcher year and p = 7 000 $
per whale. Trajectories are obtained by Scilab code 5. Computations for
equilibrium states give Bmse ≈ 197 560 whales, Bppe ≈ 224 962 whales and
Bcpe ≈ 53 571 whales. From inequality (3.16) Bmse < Bppe , we deduce that
the sole owner equilibrium Bppe is asymptotically stable whereas the maxi-
mum sustainable equilibrium is not. The stability of cpe depends on costs
c
and prices: a low fraction = Bcpe displays instability as one might then
pq
have Bcpe ≤ Bmse . Such is the case for blue whale data as depicted by Fig. 3.2
(a). Let us point out that instability of cpe also means extinction, in the
sense that B(t) →t→+∞ 0 for initial states B(t0 ) starting from below the
equilibrium Bcpe .
Scilab code 5.
// // Private property equilibrium PPE
// exec stab_BH.sce ; clear NCPE=c_e/(p*q) ;
// Common property equilibrium CPE
////////////////////////////////////////////////////
// Antartic Blue whales data hMSE= Sust_yield(NMSE) ;
//////////////////////////////////////////////////// hPPE= Sust_yield(NPPE) ;
hCPE= Sust_yield(NCPE) ;
// Biological parameters and functions
R_B=1.05; ////////////////////////////////////////////////////
// Intrinsic rate of growth 5% per year // Trajectories simulations
k = 400000; ////////////////////////////////////////////////////
// Carrying capacity (whales)
b = (R_B-1)./k; // Only the last line counts. Change it.
Ne=NCPE // unstable case
function [y]=Beverton(N) Ne=NPPE // stable case
// Beverton-Holt population dynamics
y=(R_B*N)./(1 + b*N) he=Beverton(Ne)-Ne
endfunction
Horizon=500; time=1:Horizon;
function [h]=Sust_yield(N) // Time horizon
// sustainable yield
h=Beverton(N)-N epsil=20000;
endfunction // Perturbation level around the equilibrium
function [y]=Beverton_e(t,N) xset("window",2); xbasc(2);
he=Sust_yield(Ne); plot2d2(time,ones(1,Horizon)*NMSE,rect=[1,0,Horizon,k]);
y=max(0,Beverton(N) - he); Time=linspace(1,Horizon,20);
endfunction plot2d2(Time,ones(Time)*NMSE,style=-4);
legends("MSE",-4,’lr’)
// Plot of the MSE
// Economic parameters
for (i=1:10) // trajectories loop
c_e=600000; // cost in $ per whale catcher year N0=Ne + 2*(rand(1)-0.5)*epsil;
p=7000; // price in $ per blue whale unit // perturbation of initial state
q=0.0016; // catchability per whale catcher year Nt=ode("discrete",N0,0,time,Beverton_e);
// computation of the trajectory
plot2d2(time,Nt,rect=[1,0,Horizon,k]);
// plot of the trajectory
//////////////////////////////////////////////////// end
// Equilibria and yields
//////////////////////////////////////////////////// xtitle(’Abundances trajectories’,’years’,...
’abundances (whales)’)
NMSE= (sqrt(R_B) - 1)/b ;
// Maximum sustainable equilibrium MSE //
NPPE= ( sqrt( R_B * (1 + (b*c_e/(p*q)) ) ) - 1 ) / b ;
66 3 Equilibrium and stability
3.6 Open access, instability and extinction
For the open access model, the Jacobian matrix of dynamics (3.17) at equi-
librium xe = (Be , ee ) is
& '
dF (1 − qee )g Be (1 − qee ) ; −qBe g Be (1 − qee )
A= (xe ) = ,
dx αpqee ; 1
c
where we use the property (3.18) that Be = . In the linear case g(B) = RB
pq
R−1
where ee = , stability cannot be performed as illustrated by Fig. 3.3.
Rq
This situation stems from the fact that the Jacobian matrix reads as follows:
& ' & '
R(1 − qee ) ; −RqBe 1 − Rc
p
A= = .
αpqee ; 1 αp R−1
R 1
The two eigenvalues (λ1 , λ2 ) of matrix A are the solution of
0 = Det(A − λI2 ) = (1 − λ)2 + αc(R − 1) .
( (
Since R > 1, we deduce that λ1 = 1−i αc(R − 1) and λ2 = 1+i αc(R − 1).
Therefore, the modulus of each eigenvalue is
(
|λ1 | = |λ2 | = 1 + αc(R − 1) ,
strictly greater than 1 whenever α > 0. Consequently, stability cannot occur
as illustrated in the Figs. 3.3 for the specific parameters p = 1, q = 1, c = 2,
α = 10−2.5 , g(B) = (1 + r)B, r = 0.1. Note that such an instability relies
on oscillations that display greater and greater amplitude through time. This
process ends with the collapse of the whole system, including extinction of the
resource. Other illustrative numerical examples can be found in [3] for logistic
dynamics.
08 0.08 0.32 0.5 .04 0.12 0.40 0. 3. .1).20 0. c = 2. Open access: a case of instability and non viability (p = 1.32 0.12 0.36 0. R = 1. 3.20 0.24 0.04 0.36 0.28 0.28 0.40 0.3.24 0. q = 1. g(B) = RB.16 0. instability and extinction 67 fort Phase e(t) portrait biomass B(t) 0.6 Open access.16 0.00 0 10 20 30 40 50 (a) Phase diagram B(t) − e(t) mass iomass B(t) trajectory time t 50 40 30 20 10 0 0 1000 2000 3000 4000 5000 6000 7000 8000 9000 10000 (b) Biomass trajectory B(t) fort Effort e(t)trajectory time t 0.00 0 1000 2000 3000 4000 5000 6000 7000 8000 9000 10000 (c) Effort trajectory e(t) Fig. The trajectories were generated by Scilab code 6. α = 10−2.
Tilman [11] has introduced a new approach based on a mechanistic resource-based model of competition between species and uses the resource requirements of the com- peting species to predict the outcome of species competition.Linear(N-q*e*N)) y(2. p=1..:))*1. // Jacobian matrix time=0:Horizon.’biomass B(t)’). y=y*(y>NV) // Computation of the trajectory endfunction xset("window". R=p*q*e*N-c*e endfunction xset("window".1)*N_CPE xt(1. we here expose a discrete time version and study the stability of the equilibrium.. In this setup. Species competition is an issue of fundamental importance to ecology. function R=Rent(N. the system is driven to mono-culture and the equilibrium outcome of species competition is the survival of the species which is the superior competitor for the limiting resource. xt(2.. in this sense..(e+eta*Rent(N. in the context of a multi-species competition for a limiting factor.5]). . eta*p*r/R 1]. that is.:))*1. y=zeros(2. .. This principle states that.5]).2)..x) // Open access dynamics xset("window".1)=max(0.e))) // endfunction 3.0.1) rect=[0..’biomass B(t)’.’time t’.q=1.5)/100.1.Open_access). the species with the lowest resource requirement in equilibrium will competitively displace all other species.. biodiversity.. In the past few decades.max(xt(1.3).:))*1. plot2d(time. As shown in [1]. The state variables are .[ones(Horizon+1.’time t’.e) rect=[1.max(xt(2. The strength of the resource-based model lies in an exclusion principle. eta=10^{-2. r=0. N=x(1.4).0.max(xt(2.rect=[1.4). // Linear population growth with Allee effect // initial condition around CPE function [y]=Linear(N) xt=ode("discrete". xtitle(’Biomass trajectory’. xbasc(3).0.1) plot2d(xt(1.x0. clear // graphics xset("window".3).5..// Divergent case for open access xset("window". function y=Open_access(t. A=[1 -R*c/p. xbasc(4). xbasc(2)..5}.7 Competition for a resource: coexistence vs exclusion We end this Chapter with the exclusion principle in ecology coping with a community competing for a limited resource.5]).0.time.. spec(A) // Spectrum of Jacobian matrix x0=[N_CPE.:)’]. N_CPE=c/(p*q) xtitle(’Phase portrait’. This model has been examined from a bioeconomic perspective for the management of renewable resources.Horizon. an exclusion process again occurs.E_CPE]+(rand(1)-0.e=x(2.’effort e(t)’) E_CPE=r/q // trajectories R=1+r.68 3 Equilibrium and stability Scilab code 6. Numerous studies are now aiming at relaxing the model to allow for the coexistence of species.xt(2. NV=%eps*10^10 // Minimum viable population xtitle(’Effort trajectory’.1)=max(0. .time+1)’.c=2. condemning.max(xt(1.:))*1. y=N*(1+r). the species with the lowest resource requirement. y(1. However. The model is generally described in a continuous time framework.2).:)’.1). // // exec open_access.time+1).’effort e(t)’) xset("window". Horizon=10000.sce . The classical theory makes use of the Lotka-Volterra competition model.Horizon. // rent of the catches plot2d(time.
23a) n R(t + 1) = R(t) + Δt S(t) − aR(t) − wi fi R(t)Ni (t) . n. . 3. . (3. for which the species compete. . We consider the dynamic Ni (t + 1) = Ni (t) + Δt Ni (t)(fi R(t) − di ) . N5 are driven to extinction.23a). the rate of growth Ni (t + 1) − Ni (t) = Ni (t)(fi R(t) − di ) Δt of species i density is linear in Ni (t) with per capita rate of growth fi R(t) − di where • fi R(t) is the resource-based per capita growth of species i. . (3.4.7 Competition for a resource: coexistence vs exclusion 69 Densities trajectories N1 N2 12 N3 N4 10 N5 R 8 N(t) 6 4 2 0 1000 2000 3000 4000 5000 6000 7000 8000 9000 10000 time t Fig. n . The other species N1 . N2 .23b) i=1 In (3. for i = 1. • species i density Ni (t). An example of the exclusion principle of a resource-based model: the only stable equilibrium contains only the species (here N3 ) with lowest resource requirement at equilibrium Re . . 3. . • the limited resource. . . represented by R(t). i = 1. The time interval between t and t + 1 is Δt . the higher fi > 0. the more species i can exploit the resource R(t) for its own growth. N4 . . • di > 0 is the natural death rate.
Result 3.23a)-(3.6 Suppose that input S(t) is stationary. the rate of growth R(t + 1) − R(t) n = S(t) − aR(t) − wi fi R(t)Ni (t) Δt i=1 of the resource R(t) is decomposed in three terms: • S(t) is the input of the resource. The following Result states the so-called exclusion principle.n fi fie ⎨ ⎧ ⎪ ⎨ Se − Re a > 0 if (3. also illus- trated by Fig.1 in the Appendix. set to value Se .e ⎩ 0 if i = ie .23b). supposed to be known and taken as stationary in what follows. the ex- pression S(t) − aR(t) stands for the natural evolution of the resource with- out interactions with species..4.. where wi > 0 is the impact rate of species i on resource R.70 3 Equilibrium and stability In (3. .23b) is given by ⎧ ⎪ di di ⎪ ⎪ Re = min = e . 3.. the only asymp- totically stable equilibrium of (3. • −aR(t) corresponds to self-limitation of the resource with a > 0. If Se is large enough. ⎪ ⎪ N = Re wie fie ⎩ i.24) ⎪ ⎪ i = ie . 4 And excluding the exceptional case where di /fi = dj /fj for at least one pair i = j. A proof is given in Sect. A. and if the time unit Δt > 0 is small enough4 . ⎪ ⎪ i=1.. • −wi fi R(t)Ni (t) represents the effect of competition of species i on the resource.
Nonlinear Systems. volume 2. M. 1973. W. 2001. 1988. Clark. 1954. M. Kot. [5] J. second edition. Gordon. Optimal ecosystem management when species compete for limiting resources. Olewiler. Elements of Mathematical Ecology. Harper and Row. Princeton. New York. Mawhin. [2] C. The economic theory of a common property resource: the fishery. Mathematical Bioeconomics. Cambridge. Resource Economics. Cambridge University Press. Masson. volume 1. [9] N. Journal of Political Economy. 1999. [8] N. [6] H. Stability. [11] D. S. Wiley. K. Journal of Environmental Eco- nomics and Management. Sastry. Rouche and J. Englewood Cliffs. D. and Control. Tilman. 2002. second edition. [10] S. second edition. Princeton Univ. [3] J.References [1] W. Xepapadeas. 62:124–142. Press. Mawhin. 1990. Rouche and J. 1998. [7] M. Équations différentielles ordinaires. . Prentice-Hall. The Economics of Natural Resource Use. Analysis. Hartwick and N. Équations différentielles ordinaires. Khalil. Paris. 44:189–220. Paris. 1999. 1995. Masson. Nonlinear Systems. Brock and A. Cambridge University Press. Conrad. Plant Strategies and the Dynamics and Structure of Plant Communities. New York. [4] H. Springer- Verlag. 1973.
.
4 Viable sequential decisions Basically. preserving biodiversity or ecosystems. avoiding or mitigating climate change are all examples of sustainability issues where via- bility plays a major role. sustainability is defined as the ability to maintain the system within some satisfying normative bounds for a large or indefinite time. 24] or a viability problem [1]. in these cases. By extension. In the same vein. Equilibrium and . a tolerable mitigation policy is often represented by a ceiling threshold of co2 concentration (for instance 450 ppm) not to be violated [16]. the ices precautionary framework [15] aims at conserving fish stocks and fisheries on the grounds of several indi- cators including spawning stock biomass or fishing effort multiplier. the quantitative method of conservation biology for the survival of threatened species is termed Population Viability Analysis (pva) [19]. Regarding these issues. preventing ex- tinction of rare species. Similarly. or effectiveness in the sense of cost-effectiveness in economics. Such a mathematical problem is termed weak or controlled invari- ance [6. safety. viability may also refer to perennial situations of good health. environmental or ecological economics or conser- vation biology. physical and economical dynamics and constraints or targets accounting for economic and/or ecological objectives. a major challenge is to study the compatibility be- tween controlled biological. reference points not to be exceeded for these bioeconomic indicators stand for management objectives. namely the capacity for a sys- tem to maintain conditions of existence through time. the question of constraints has mostly been neglected to concentrate rather on steady state equilibria or optimization concepts. Of major interest are viability concerns for the sustainability sciences and especially in bioeconomics. Safe Minimum Standards (sms) [4] have been proposed with the goal of preserving and maintaining a renewable resource at a level that precludes irreversible extinction except in cases where social costs are prohibitive or immoderate. Basically. for greenhouse gas issues. For instance. viability means the ability of survival. In this context. Such preoccu- pations refer to the study of controlled dynamical systems under constraints and targets. Harvesting a resource without jeopardizing it. In applied mathematics and the systems theory.
11. 21] proposes a similar framework. The chapter is organized as follows. Moreover. By dynamic programming. 4. in Sect. 10.3 together with the dynamic programming method. 4. the dynamic viability decision problem is solved sequentially: one starts at the final time horizon and then applies some backward induction mechanism at each time step. 5. the so-called population viability analysis (pva) and conservation biology display concerns close to those of the viable control approach by focusing on extinc- tion processes in an uncertain (stochastic) framework. selecting a single trajectory. the viable control approach is deeply connected with the Rawlsian or maximin approach [14] important for intergenerational equity as will be explained in Chap. Indeed. 13. to restrict the mathemat- ical content to a reasonable level. A specific Sect. . we present the viability problem on the consistency between a controlled dynamic and acceptability constraints. In Sect. especially in the economic and environmental fields. Works [2. We end with invariance. 4. The ideas of all the mathematical statements presented in this Chapter are inspired mainly by [1] in the continuous case. 18.1. introduced in Sect. in general. 3 are only a partial response to via- bility issues. The main concept to tackle the viability problem is the via- bility kernel. 20] cope with renewable resource management and especially fisheries. Furthermore. as emphasized in [17].2. Although dynamics optimization problems are usually formulated under con- straints as will be seen in Chap. 5. we focus on the discrete time framework as in [8. Agricultural and biodiversity issues are especially handled in [23. From the ecological point of view.10. the role played by the constraints poses difficult technical problems and is generally not tackled by itself. We illustrate the mathematical concepts or results through simple examples taken from the environmental and sustainability topics. Resource management examples under viability constraints are given in Sect. 22]. 9. the optimization procedure reduces the diversity of feasible forms of evolution by.74 4 Viable sequential decisions stability depicted in the previous Chap. mainly focusing on cli- mate change issues. 4. 7. 7 dealing with stochas- tic viability. equilibria are clearly “viable” but such an analysis does not take into account the full diversity of possible transitions of the system. This is a very demanding concept which refers to the respect of given constraints whatever the admissible options of decisions or controls taken at every time. Here. 3. The tolerable win- dows approach [5. We refer for instance to [17] for exhaustible resource management. The aim of this Chapter is to provide the specific mathematical tools to deal with discrete time dynamical systems under state and control constraints and to shed new light on some applied viability problems. or strong viability. Links between pva and the viable control approach will be examined in Chap.4 is dedicated to viability in the autonomous case. 4. 24]. Following sections are devoted to examples.
The most usual case occurs when the set of admissible controls is constant i. and x0 ∈ X is the initial condition at initial time t0 ∈ {0. 4. (4. ae t. as in Sect. catch. .e. u(t) = 0 . . biomass. .1) where x(t) ∈ X = Rn is the state (co2 concentration. Decision constraints We consider the conditions u(t) ∈ B t. The dynamics We consider again the following nonlinear dynamical system. Generally. . T − 1 .9. safety or effectiveness of a system. x(t). x(t) = 0 . ef- fort. ). . . B(t. t = t0 . x(t) ≤ 0 . and coin them as ex ante or a priori viability conditions. x(t). . . u(t) .1 The viability problem The viability problem relies on the consistency between a controlled dynamic and acceptability constraints applying both to states and decisions of the system. t = t0 . 2. . . . u(t) ∈ U = Rp is the control or decision (abatement. . . abun- dances. . Viability is related to preservation. T − 1}.2a) The non empty control domain B t. x(t) ⊂ U is the set of admissible and a priori acceptable decisions. T ∈ N∪{+∞} corresponds to the time horizon which may be finite or infinite. . . (4. T − 1 . State constraints The safety.2b) The usual example of such a tolerable window A(t) concerns equality and inequality (vectorial) constraints of the type ai t. permanence and sustainability of some conditions which represent survival. . . . these constraints are associated with equality and inequality (vec- torial) requirements of the form bi t. x(t + 1) = F t. T − 1 with x(t0 ) = x0 . . (4. the admissibility or the effectiveness of the state for the system at time t is represented by non empty state constraint domains A(t) ⊂ X in the sense that we require x(t) ∈ A(t) . x(t). .1 The viability problem 75 4. ). x) = B for every state x and time t. t = t0 . We introduce both decision and state constraints. be t. u(t) ≤ 0 . x(t) .
T . t = t0 . u(t) . it is a multi-criteria approach sometimes known as co-viability. . 4. t = t0 . u(·) (4. and then exhibiting its elements.76 4 Viable sequential decisions Target constraints Target problems are specific state requirements of the form x(T ) ∈ A(T ) . Moreover. . T − 1 ad T (t0 . . . let us stress that an intergenerational equity feature is naturally integrated within this framework as the viability requirements are identical along time without future or present preferences. x(t) .2c) and state constraints (4. . ⎧ ⎫ ⎪ x(t0 ) = x0 . (4.1) and constraints (4.2a)–(4. More specifically. ⎪ ⎪ ⎨ ⎪ ⎬ x(t + 1) = F t. (4. x0 ) = x(·).63)). the viability problem consists in identifying conditions under which the following set of state-control trajectories (already introduced in (2. T is not empty. . . . . .2d) form a set of relations for which there may or may not exist a global solution because some requirements and processes may turn out to be contradictory along time. viability may capture the satisfaction of both economic and environmental constraints. . t = t0 . T − 1 ⎪ ⎪ ⎩ ⎭ x(t) ∈ A(t) . . as soon as the constraints do not explicitely depend on time t and the horizon is infinite (T = +∞). Mathematically speaking.2 Resource management examples under viability constraints We provide simple examples in the management of a renewable resource. target constraints (4. in the management of an exhaustible resource and of forestry.2c) Hereafter. x(t). t = t0 . in climate change mitigation. In this sense. .2d) The question of consistency between dynamics and constraints Dynamics (4. . . .3) ⎪ ⎪ u(t) ∈ B t. Viability or weak or controlled invariance issues focus on the initial states for which at least one feasible solution combining dynamics and constraints exists.2b) are unified through the following constraints x(t) ∈ A(t) . . in the sustainability context.
1 Viable management of a threatened population Suppose that the dynamics of a renewable resource. as in Sect. The co2 emission function Ebau (Q) > 0 represents a “business as usual” scenario and depends on production level Q(t). The concentration has to remain below the tolerable level at the horizon T in a target framework: . The har- vesting of the population is constrained by the biomass 0 ≤ h(t) ≤ B(t) . Elephant populations in Africa or predator fish species like Nile Perch are significant examples. presented in Sect. . 2.2. Here. Production Q(t) grows at rate g. . control a(t) ∈ [0. 1] is the abatement rate of co2 emissions. t = 0. we can also require guaranteed harvests that provide food or money for local human populations in the area under concern: 0 < h ≤ h(t) .2 Resource management examples under viability constraints 77 4. 4. . Think of a population which may have extinction threats for small popu- lation levels because of some Allee effect while it can be dangerous for other species or the habitat from some higher level.2. We require the abatement costs C(a. where g is some natural resource growth function. 2. namely between conservation and maximal safety values. characterized by its biomass B(t) and catch level h(t). The question that arises is whether conservation.3. . 0 < B ≤ B(t) ≤ B . 4. at all times. habitat and harvesting goals can all be met simultaneously. is governed by B(t + 1) = g B(t) − h(t) . T . Q(t) ≤ c . We look for policies which maintain the biomass level within an ecological window. Let us consider the following dynamics of co2 concentration M (t) and economic production Q(t): M (t + 1) = M (t) + αEbau Q(t) (1 − a(t)) − δ(M (t) − M∞ ) .2.2 Mitigation for climate change The following model. Q) not to exceed a maximal cost threshold: C a(t). For social ra- tionale. deals with the management of the interaction between economic growth and greenhouse gas emissions as in [12]. Q(t + 1) = (1 + g)Q(t) .
3 Management of an exhaustible resource Following [17] in a discrete time context. (4. (4. . t=t0 . K represents the accumulated capital.T −1 This equivalence comes from the fact that a utility function is strictly increas- ing1 in consumption c.. A more demanding requirement consists in constraining the concentration over the whole period: M (t) ≤ M .7) This constraint refers to sustainability and intergenerational equity since it can be written in terms of utility in a form close to Rawl’s criteria: L(c ) ≤ inf L c(t) . we describe an economy with ex- haustible resource use by S(t + 1) = S(t) − h(t) . .7. 2. First it is assumed that extraction h(t) is irreversible in the sense that 0 ≤ h(t) . 1 We shall say that f is an increasing function if x ≥ x ⇒ f (x) ≥ f (x ).78 4 Viable sequential decisions M (T ) ≤ M . Now let us consider the state-control constraints..6) We may choose to impose a requirement related to some guaranteed consump- tion level c > 0 along the generations: c ≤ c(t) . T . 4. where S is the exhaustible resource stock. as in Sect.4) We also consider that the capital is nonnegative 0 ≤ K(t) . h stands for the extraction flow. . . (4. Letting S > 0 stand for some minimal resource target.. h(t) − c(t) . c stands for the con- sumption and the function Y represents the technology of the economy. . the decision or controls of this economy are levels of consumption c and ex- traction h respectively.5) We take into account scarcity of the resource by requiring 0 ≤ S(t) .2. while f is a strictly increasing function if x > x ⇒ f (x) > f (x ). Hence. (4.. t = 0. K(t + 1) = K(t) + Y K(t). we can more generally consider a stronger conservation constraint for the resource as follows: S ≤ S(t) .
1 − m⎦ γ γ γ . 1] is a mortality parameter and γ plays the role of the recruit- ment parameter. of the vector N (t) is described by a linear system N (t + 1) = A N (t) . Now we describe the exploitation of such a forest resource. ⎟ ∈ Rn+ . 0 ⎥ . . is between j − 1 and j at the beginning of yearly period [t. that each time a tree is cut. ⎥ A=⎢ . .. Nn (t) is the surface of trees of age greater than n − 1.. 0 ⎥ ⎢ ⎥ ⎢ .4 Forestry management A detailed version of the following model with age classes is exposed in [20].. Furthermore. . introducing the scalar variable decision h(t) which represents the surface of trees harvested at time t.8) where the terms of the matrix A are nonnegative. Particular instances of matrices A are of the Leslie type ⎡ ⎤ 1 − m 1 − m 0 ··· 0 ⎢ . n − 1) represents the surface used by trees whose age. which ensures that N (t) remains nonnegative at any time. the decision or control variable h(t) is subject to the constraint 2 The superscript stands for transposition. ⎝ . 2. Thus. As described in Sect. .. i. γ where m ∈ [0. ⎥ ⎢ 0 0 1 − m . t + 1[. .9) ⎢ ⎥ ⎢ . We assume that the natural evolution.. where B is equal to the column2 vector −1 0 · · · 0 1 .2 Resource management examples under viability constraints 79 4. we consider a forest whose structure in age is rep- resented in discrete time by a vector of surfaces ⎛ ⎞ Nn (t) ⎜ Nn−1 (t) ⎟ ⎜ ⎟ N (t) = ⎜ . 4. (4.5. since one cannot plan to harvest more than exists at the beginning of the unit of time.. it is immediately replaced by a tree of age 0. second. ⎠ N1 (t) where Nj (t) (j = 1. (4. first. expressed in the unit of time used to define t. without exploitation. we assume. that the minimum age at which trees can be cut is n and..e. we obtain the following controlled evolution N (t + 1) = A N (t) + B h(t) .2. ⎥ ⎣ 0 . For the sake of simplicity. 0 ..
which ensures the non- negativity of the resource. a first idea to generate viable behaviors is to consider the set of states from which at least one trajectory starts together with a control sequence. . . (4. 4 One consists in enlarging the constraints and corresponds to the viability envelope concept.2b)–(4. T } for dynam- ics (4. as illustrated in Fig.80 4 Viable sequential decisions 0 ≤ h(t) ≤ Nn (t) = CN (t) . Notice that. .1) and constraints (4. while the idea of forcing is to modify the dynamics by introducing new regulations or controls.1. we asso- ciate the harvesting h(t) with an income. both satisfying the dynamical system equations and the constraints through- out time.1) and constraints (4. where the row vector C is equal to 1 0 · · · 0 0 . 4. viability or weak invariance issues refer to the consistency between dynamics (4. T − 1} . This harvesting is required to exceed some minimal threshold h > 0 at any time: h ≤ h(t) .2a)–(4. . . Among different ideas4 to display viability. a utility or a service. 4.10) ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ dynamics (4. defined by: ⎧ ⎫ ⎪ there exist decisions u(·) ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎨ and states x(·) starting from x at time s ⎪ ⎬ Viab(s) := x ∈ X satisfying for any time t ∈ {s. .2c) at final time T.2d). Definition 4. 4. t + 1[.1 The viability kernel Indeed.2a)–(4. denoted by Viab(s). To encompass the economic or social feature of the exploitation.1) and constraints (4.3 The viability kernel Mathematically. .3.2c) is the subset of the state space X. we have implicitly assumed that the harvesting decisions h(t) are effective at the be- ginning3 of each period [t.2a)–(4. The viability kernel at time s ∈ {t0 . Viab(s) ⊂ A(s) 3 Harvesting decisions effective at the end of each unit of time t would give 0 ≤ h(t) ≤ CAN (t). .1.2b) ⎪ ⎪ ⎩ ⎭ and satisfying (4. Notice that by choosing this constraint. we focus on the largest viable part of the state constraints: this corresponds to the viability kernel concept that we develop hereafter. .
we now describe how Viab(t0 ) is given by a backward induction involving the other viability kernels Viab(T ). Viab(t0 + 1). For viability prob- lems.2c): Viab(T ) = A(T ) . 4. .2 and 4. .2. the dynamic programming principle means that the dynamics decision-making problem is solved sequentially: one starts at the final time horizon and then applies some backward induction mechanism at each time. The state constraint set A is the large set. T }.2b) is satisfied at time s. 4. . Indeed. . Fig. .2 in the Appendix. 4. . . It includes the smaller viability kernel Viab.3 The viability kernel 81 because the state constraint (4.2 Maximality and Bellman properties As in dynamics optimization problems5 . the Bellman/dynamic programming principle (DP) can be obtained within the viable control framework. .1. We distinguish the infinite and finite horizons. Proposition 4. Basically. It can also be em- phasized that the viability kernel at horizon T is the target set (4.3 can be found in Sect. The proofs of the two following Propositions 4. this principle can be described through both geometrical and functional formulations. The viability kernel Viab(t) satis- fies the backward induction. A.3. where t runs from T − 1 down to t0 : 5 See Chaps. we have introduced all the Viab(s) for s ∈ {t0 . A geometric characterization in the finite horizon case is given by the following Proposition 4. Assume that T < +∞.2. Although we are especially interested in the viability kernel Viab(t0 ) at initial time t0 . Viab(T − 1). . 5 and 8.
To achieve this. (4.3.12) +∞ otherwise. F (t. Similarly. we introduce the extended6 characteristic function of a set K ⊂ X: 0 if x ∈ K ΨK (x) := (4. The extended function V : (t.82 4 Viable sequential decisions Viab(T ) = A(T ) . an equivalent functional characterization can be derived in the finite horizon case.11) Viab(t) = {x ∈ A(t) | ∃u ∈ B(t. x. u) ∈ Viab(t + 1)} . Assume that T < +∞. x) . Proposition 4. x) .
we mean that a real valued function may take the values −∞ and +∞. x) for all (t. A viable feedback is a function u : N × X → U such that u(t. x) = inf ΨA(t) (x) + V t + 1. (4. consequently. Thus. Any u ∈ Bviab (t.1. the boundary of viability ker- nels stands for security barriers with respect to initial viability bounds which are larger.3. or dynamic programming equation. the following viable regulation set Bviab (t.→ ΨViab(t) (x) is the solution of the Bellman equation. x). there exists an admissible control u which yields a future state F (t. In other words. for every point x inside the corridor Viab(t). u) ∈ Viab(t + 1)} (4. in A(t). x. At this stage. x. 6 By extended. F (t. x) = ΨA(T ) (x) .13) ⎪ ⎩ V (t. 4. x) ∈ Bviab (t. u) . x) | F (t. x. where t runs from T − 1 down to t0 : ⎧ ⎪ ⎨ V (T. u∈B(t. . as depicted by Fig. u) remaining in Viab(t + 1) and.14) is not empty. This situation explains why we may speak of ex post viability.x) This Proposition may provide an approximation algorithm by replacing ΨA(t) with a function taking a large value on A(t) and zero elsewhere. 4.3 Viable controls and feedbacks The previous characterizations of the viability kernels point out that. let us note that the viability kernels elicit the “true” state constraints of the problem because the viable strategies and controls are de- signed to make sure that the state remains within the viability kernels Viab(t) instead of the initial state constraints A(t). x) := {u ∈ B(t. x) is said to be a viable control.
. t0 + 1. 4. Viability kernels and viable controls make a characterization of the feasi- bility problem as exposed in Subsect. (4. Reference [1] proposes some specific selection procedures such as barycen- tric. The feasibility set T ad (t0 . In other words ⎧ ⎫ ⎨ x(t0 ) = x0 .17).4 Viability in the autonomous case The so-called autonomous case of fixed (or autonomous.2a)– (4.2d) have now disappeared. Other optimal selections are examined in Chap. (4. This situation ad- vocates for multiplicity and flexibility in the viable decision process.4 is a consequence of Proposition 4. there is no uniqueness of viable decisions. ⎩ ⎭ u(t) ∈ Bviab t. . ⎪ ⎪ ⎩ dynamics (4. u(t) . . and only if. T − 1 (4. ⎬ T ad (t0 . slow or inertial viable controls. . u(·) x(t + 1) = F t. x(t) . x0 ) = ∅ . The proof of the following Proposition 4. (4. x) has no reason to be reduced to a sin- gleton and. t = t0 . . 5 dealing with optimal control. the initial state belongs to the initial viability kernel: x0 ∈ Viab(t0 ) ⇐⇒ T ad (t0 . t = t 0 .3) is not empty if. having been incorporated into the new control constraints u(t) ∈ Bviab t. x0 ) in (4. x(t) .1) and constraints (4. . We may however require more oriented and specified decisions among the viable ones.3.15) any trajectory in T (t0 . Proposition 4.14).18) ⎪ ⎪ satisfying for any time t = t0 . ⎭ 4.4 Viability in the infinite horizon case Particularly when T = +∞.4.16) Notice that the state constraints (4. u(t)) ∈ D(t) ⊂ X × U . x0 ) = x(·). 4.17) The definition of the viability kernel is now [8] ⎧ ⎫ ⎪ there exist decisions u(·) ⎪ ⎪ ⎨ ⎪ and states x(·) starting from x at time t0 ⎬ Viab := x ∈ X . stationary) con- straints and dynamics is when .1 possible. one may consider the state/control constraintswhich are respected at any time t: (x(t). thus. Bviab t. 4.2 and of the definition (4. . rather than considering the constraints (4. T − 1 .2b). . .x(t).4 Viability in the autonomous case 83 We can see at once that Bviab (t. x(t) . x0 ) is generated by selecting u(t) ∈ ad Furthermore. . .
It turns out that the viability approach enlarges that of equilibrium.2 Viability domains Viability domains are convenient for the characterization of the viability kernel as shown below. the viability kernels are increasing with respect to time: Viab(t0 ) ⊂ Viab(t0 + 1) ⊂ · · · ⊂ Viab(T ) = A . x) = B(x) .19). F (x.22) .6. (4. ∃u ∈ B(x) .20). x. in addition. e ⊂ Viab(t0 ). the horizon is infinite (T = +∞). it is straightforward to prove that the admissible equilibria constitute a part of any viability kernel. the admissible equilibria of Definition 3. or a viable set if ∀x ∈ V . Definition 4. An equilibrium is only a partial response to viability issues. the viability kernels are stationary and we write the common set Viab: Viab(t0 ) = · · · = Viab(t) = · · · = Viab ⊂ A . Xad xe = F (xe . admissible equilibria are clearly “viable” but such an analysis does not take into account the full diversity of tolerable transitions of the system. through the maximum sustainable yield concept. It is defined as follows. (4. Notice that. u) = F (x.4.20) If. In the autonomous case (4. 3 pointed out the interest of equilibria in dealing with sustainability issues. Proposition 4. u) ∈ V . this is equivalent to Xad 4. especially for renewable resources. by (4. (4.5 is a consequence of Definition 4. in the autonomous case (4. ue )} ⊂ Viab(t) . Indeed. a subset V ⊂ X is said to be weakly invariant. In the autonomous case (4.19).19). In the autonomous case (4. a viability domain is a set that coincides with its viability kernel. or a viability domain.19) ⎪ ⎪ ⎪ ⎩ F (t.5. ⎪ ⎨ B(t. Proposition 4. u) . (4.19). Hence.21) 4.1 Equilibria and viability Chap. The following Proposition 4.1 belong to the viability kernel Viab(t) at any time t: e := {xe ∈ A | ∃ue ∈ B(xe ) . Basically.1 of viability kernels.7.4.84 4 Viable sequential decisions ⎧ ⎪ ⎪ A(t) = A .
Thus.4. we obtain a functional dynamic pro- gramming characterization in the infinite horizon case.8.4 Viable controls In the autonomous case (4. or dynamic programming equation. 4.19). the union of all vi- ability domains in A.4.4 Viability in the autonomous case 85 An equivalent functional characterization is ΨV (x) = min ΨV F (x. the viability kernel is the largest viability domain contained in A. The comfortable case Whenever the viability kernel is the whole set of constraints A = Viab(t0 ) = Viab(t) .9. it turns out that the a priori state constraints (namely the set A) are relevant. In the autonomous case (4. Indeed. three significant situations are worth being pointed out. u) . Proposition 4. Such a concept is central to characterizing the viability kernel as detailed below. u) . . 4.19) and in the infinite horizon case. 4. u) ∈ Viab} .5 Hopeless.24) Hence. (4. u∈B(x) The set of equilibria is a particular instance of a viability domain. Cycles or limit cycles constitute other illustrations of viability domains. u∈B(x) (4. A geometric assertion in the infinite horizon case is given by the following Theorem [1] involving viability domains (a proof may be found in [8]).3 Maximality and Bellman properties In the autonomous case (4. being included in the latter. In this case.19).19). the infinite horizon case provides the sim- plest characterization since time disappears from the statements.4. Theorem 4. V (x) = inf V F (x. from every state in A a feasible policy starts. Similarly. the extended function ΨViab is the largest solution V of the Bellman equation.23) V (x) ≥ ΨA (x) .19). the time com- ponent vanishes and we obtain the viable controls as follows: Bviab (x) := {u ∈ B(x) | F (x. comfortable and dangerous configurations In the autonomous case (4. ensuring viability means remaining in the viability kernel. which stands for the “true constraints” and thus sheds light on ex post viability. the set A is a viability domain. that is to say. 4. any viability domain is a lower approximation of the viability kernel. In autonomous case (4.
we restrict the study to a non-density-dependent and linear case B(t + 1) = RB(t) 1 − e(t) . this case is dangerous since parts of the initial constraint domain A are safe but others may lead to collapse or crisis by violating the constraints in finite time whatever the admissible decisions u(·) applied. In this sense. where the productivity of the resource is strictly larger than 1 (R > 1). We can show that viability occurs if the initial biomass is sufficiently high. one may speak of viability margins for the viability kernel. we have to face the crisis (to be outside A) in finite time whatever the future decisions taken. giving: 0 < B ≤ B(T ) ≤ B . As shown by Fig. For the sake of simplicity. 4. but not too high.86 4 Viable sequential decisions The dangerous case and security barriers Configuration of partial viability refers to the case where the viability kernel is neither empty nor viable. unavoidable crisis and irreversibility is everywhere within domain A. In- deed.5 Viable control of an invasive species We consider the discrete dynamics of an invasive species characterized by its biomass B(t) and harvesting effort decision e(t). 4.2. In this sense. the set of boundary points of the viability kernel. Viab(t0 ). We assume that the policy is to constrain the ultimate biomass level within an ecological window. The hopeless case Whenever the viability kernel is empty. we have a hopeless situation. that is Viab(t0 ) = ∅ . Other strategies. 4. such as enlarging the constraints or modifying the dynamics should be applied in order to solve the viability problem. that is to say: ∅ Viab(t0 ) A . which is located in A can be interpreted as the anticipative zone of dangers. namely between conservation and maximal safety values at time horizon T . The effort is constrained by 0 ≤ e ≤ e(t) ≤ e ≤ 1 . and set A is said to be a repeller. If we go over this safety barrier. The following sections present the viability kernels together with related viable feedbacks for some of the examples exposed in Sect.1. .
2. B) are those belonging to the set ) * B (t) B (t) viab E (t.3 2 0. but rather a requirement 0 < B ≤ B(t) ≤ B holding over all times t = t0 . }. Viable resource management for time horizon T = 5. We plot (a) viable trajectories of biomass states B(t) and the boundaries of the viability kernel Viab(t). When the state constraint is not only a final one.4 3 0.2 in the Appendix. B (t)] .8 7 0.6 biomass B(t) effort e(t) 5 0. Trajectories have been generated by Scilab code 7 Result 4. .0 1 2 3 4 5 1 2 3 4 5 time t time t (a) Biomass B(t) (b) Effort e(t) Fig.3. T . whose viability biomass bounds are given by t−1−T B (t) = B R(1 − e ) t−1−T B (t) = B R(1 − e ) .10 The viability kernels are intervals Viab(t) = [B (t).1. Viable feedback efforts e(t. 4.0 Viable state trajectories Viable control trajectories 9 Upper boundaries of viability kernels 0. A.9 Upper boundary of control constraints Lower boundaries of viability kernels Lower boundaries of control constraints 8 0. 2]. Growth parameter is R = 1.1 0 0.2.7 6 0. B) = e 1 − ≤e≤1− and e ≤ e ≤ e . . B ] = [1. RB RB Numerical illustrations are given in Fig. . . one can verify that the viability kernels are intervals whose bounds are given by backward inductions: B (t + 1) B (t + 1) B (t) = max{B . e ]. } and B (t) = min{B . Proof is expounded in Sect. 4.2 1 0. (b) Effort e(t) with the acceptability bounds [e . R(1 − e ) R(1 − e ) .1 and e = 0. The tolerable conservation window is C = [B . Effort bounds are e = 0.5 Viable control of an invasive species 87 Biomass Catch effort 10 1. 4.5 4 0.
2. W(t.2.:))>=0) then x_min=0. endfunction plot2d(Tempx..Horizon.3. -[1..i(t))). // projection of state on the grid xset("window".. i(1)=Indice(k).-[1.-[1.’effort e(t)’). z=min(z.. // Grid control u i(t+1)=dyna(traj_x(t). [1. // final time // Bellman backward equation B_min=1.1....NN).3]. // control constraints VV=[]. function [z]=dyna(x. endfunction xtitle("Catch effort"..e) ein=e_min*ones(Tempu). for (t=Horizon-1:-1:1) // state Constraints . end.B_max].B_max]./delta_x).1.2.3].x_min.. // // Dynamic Programming Viability // exec invasive_viability..3]).3]).. traj_x(t+1)=Etat_x(i(t+1)). e_max=0. 0 else [Vopt.."ul"). NN=S_x(2) . delta_u=0.. // else y=exp(100). nax=[0.2). S_x=size(grille_x) .3). endfunction W(Horizon. xtitle("Biomass".01 . SGN = bool2s((B_min <= B) & (B<=B_max)) . y=0*SGN + 1/%eps *(1-SGN) .xx. z=max(z./delta_x)+1. for (t=1:Horizon-1) e_viab(t)=Control_u(j_opt(t. end Horizon=5 .i)=jopt. MM=S_u(2) ..’time t’.. i=int((x-x_min). end.e_viab(t)).88 4 Viable sequential decisions Scilab code 7. u_max=e_max. Phi_u(t.i)=Vopt.2. end S_u=size(u). end // /////////////////////////////////////////////// .dyna(xx. // W value function R=1..11])..3].1 . P=Projbis(xsuiv).’biomass B(t)’).Horizon.uu)-Phi_x(t. end. Tempx=1:Horizon. "Upper boundary of control constraints". // end xset("window". // if (e_min <= e) & (e<=e_max) then y=0.5 4.*delta_x. x=grille_x.rect=[1. for ii=1:MM end Control_u(ii)=u_min+(ii-1)*delta_u."ul"). // if (B_min <= B) & (B<=B_max) then y=0. // is 1 when B belongs to [B_min. W=zeros(Horizon. xsuiv=dynpop(x*(1-e)). plot2d(Tempu. eax=e_max*ones(Tempu).2 3.Horizon. for k=[0. else "empty kernel" end.uu))]. // Initialization at final time T // resource productivity function y=dynpop(B) for i=1:NN y=R*B. endfunction nax=[0.B) VV=[VV. function [z]=Projbis(x) Bax=B_max*(R*(1-e_max))^(Tempx-Horizon) . z=Indice(P)..2. [1. delta_x=0.0. "Lower boundaries of viability kernels"]. z=round(x.11]). x_max=10. end "Lower boundaries of control constraints"].B.... xx=Etat_x(i).3).rect=[1. Etat_x(ii)=x_min+(ii-1)*delta_x. for ii=1:NN legends(["Viable control trajectories".3].1. function i=Indice(x) "Upper boundaries of viability kernels". u=u_min:delta_u:u_max .8 2.xx)+W(t+1.i)=-Phi_x(Horizon.2.1]. Bin=B_min*(R*(1-e_min))^(Tempx-Horizon) . function y=Phi_x(t.target for (i=1:NN) e_min=0.[e_viab ein’ eax’]....jopt]=max(VV) . for (j=1:MM) // Characteristic function State (approximation) uu=Control_u(j)... // // controled dynamics on the grid Tempu=1:Horizon-1.[traj_x Bax’ Bin’ ]. // Grid state space x if (max(W(1.e) //////////////////////////////////////////////////// SGN = bool2s((e_min <= e) & (e<=e_max)) .xx).x_max).’time t’.[traj_x Bax’ Bin’ ].x_max]. plot2d(Tempx. endfunction -[1.[e_viab ein’ eax’]. u_min=e_min. traj_x(1)=Etat_x(i(1)). xx=Etat_x(i). legends(["Viable state trajectories". +infty else j_opt(t.01. // is 0 when B belongs to [B_min.2). xbasc(2).. xset("window".5] grille_x=x_min: delta_x:x_max .. // else y=exp(100). // end endfunction //////////////////////////////////////////////////// // Characteristic function Control (approximation) // Simulations of some viable trajectories function [y]=Phi_u(t.x_min). plot2d(Tempu.Horizon. xset("window". xbasc(3).. B_max=2. y=0*SGN + 1/%eps *(1-SGN) ..sce /////////////////////////////////////////////// lines(0).
the initial concentration M (t0 ) is smaller than M (t0 ). Viable feedback abatement rates belong to the interval + .25) These induced M (t) thresholds play the role of a tolerable ceiling. . Let us now consider the problem introduced in Subsect. (4. we compute explicitly the feasible solutions of the problem and. The increasing curves are the baseline co2 emissions Ebau (t) = Ebau (Q(t)) and concentrations Mbau (t) over the period [2000.1 . Result 4. Q) = max 0. 2100].6 Viable greenhouse gas mitigation Emissions E(t) oncentrations M(t) Emissions Concentrations t t E(t) M(t) 35 1700 31 1500 27 1300 23 19 1100 15 900 11 700 7 500 3 t t −1 300 0 10 20 30 40 50 60 70 80 90 100 0 10 20 30 40 50 60 70 80 90 100 (a) Emissions Ebau (t) 1 − a(t) (b) Concentrations M (t) Fig. . We need to introduce the following maximal concentration values: M (t) := (M − M∞ )(1 − δ)t−T + M∞ . a(T − 1) is effective if and only if associated concentra- tions M (t) remain smaller than M (t). . and only if. a viable concentration ceiling. In other words.6 Viable greenhouse gas mitigation 89 4. the whole policy a(t0 ). . Viable emissions Ebau (t) 1− a(t) and concentrations M (t) are trajectories that coincide with the baseline until they decrease to reach the different concentration targets M = 450.2. 4. 4.11 An effective (viable) policy exists if. Ebau (Q) .2. we have: Viab(t) =] − ∞. 550 and 650 ppm. a(t0 + 1). 4.3. M. . In this case. in particular. - viab (1 − δ) M − M (t) + Ebau (Q) A (t. M (t)] × R+ . Using vi- able dynamic programming.
We need to recall equilibrium concepts and notations already intro- duced in Chap. The biomass of this resource at time t is denoted by B(t) while the harvesting level is h(t). (4. whenever the natural removal term disappears (δ = 0). the thresholds M (t) are strictly larger than terminal target M : this allows for exceeding the target during time.31) . as expected. which means that the terminal tolerable concentration is M . we assume that hlim > Blim > 0. (4.29) is useless.30) For the sake of simplicity.25) of the safety thresholds M (t) indicates that. the following controlled dynamics is obtained B(t + 1) = g B(t) − h(t) (4.6). A. (4.29) The combination of constraints (4. the expression (4. (4.28) yields the state constraint hlim ≤ B(t) . the induced safety thresholds coincide with final M along the whole time sequence and the effectiveness mitigation policies make it necessary to stay below the target at every period.26) with the admissibility constraint 0 ≤ h(t) ≤ B(t) . so that (4. 3. Conversely. 2. Let us observe that we always have M (T ) = M .90 4 Viable sequential decisions The proof of this result is provided in Sect.28) together with a non extinction level for the resource Blim ≤ B(t) .27) and (4. We assume that the natural dynamics is described by some growth function g as in Sect. Under exploitation.7 A bioeconomic precautionary threshold Let us consider some regulating agency aiming at the sustainable use and harvesting of a renewable resource. 4. As illustrated by Fig.3. • We take the sustainable yield function σ already defined by (3.2 in the Appendix.2. whenever natural removal occurs (δ > 0).27) The policy goal is to guarantee at each time t a minimal harvesting hlim ≤ h(t) . 4. giving h = σ(B) ⇐⇒ B = g(B − h) and 0≤h≤B. (4.
where (α(t))t∈N is an i. 4. B) = αhlim + (1 − α)B with α ∈ [0. As displayed by Fig. Then. the ceiling guaranteed catch given by (3. 7 One may also try h(t. the viability kernel Viab depends on a floor level Bpa which is the solution of Bpa = min B. for several initial conditions B(t0 ).33) B.7 A bioeconomic precautionary threshold 91 • The maximum sustainable biomass Bmse and maximum sustainable yield hmse are defined by hmse = σ(Bmse ) = max σ(B) .4. sequence of uniform random variables in [0. The Scilab code 8 makes it possible to examine and illustrate the conse- quences of this result with population dynamics governed by Beverton-Holt recruitment RB g(B) = . in this case. namely h(t) = hlim .30) is violated in such a case.35) The complete proof of this result is provided in Sect.d. +∞[ if hlim ≤ hmse Viab = (4. the viable catch feedbacks h(B) lie within the set H viab (B) = [hlim . We illustrate this with the admissible feedbacks7 h(t.32) B≥0 It turns out that when hlim ≤ hmse .2 in the Appendix. hpa (B)] where the ceiling catch hpa (B) is hpa (B) = hlim + B − Bpa . Rb The unsustainable case: Viab = ∅. In the following simulations. A. . 1]. The situation is even more catastrophic with se- quences of harvesting h(t) larger than the guaranteed one hlim . (4. 1 + bB Let us notice that. we compute differ- ent trajectories for the smallest admissible harvesting. hlim =σ(B) Result 4. B) = B or h(t. 4. For any stock B ∈ Viab.14) and (3. (4. B) = α(t)hlim + (1 − α(t))B.15) is √ (R − R)2 hmse = .34) ∅ otherwise. the viability kernel is given by [Bpa . we choose a guaranteed harvesting hlim strictly larger than hmse .12 Assuming that g is an increasing continuous function on R+ . (4. it can be observed that the viability constraint (4. 1].i.
The value Bpa is the smallest equilibrium solution of σ(B) = hlim . Unsustainable case where hlim > hmse . Now we choose a guaranteed harvesting hlim strictly smaller than hmse .30) is now satisfied. 4. we know that any viable feedback h(B) lies within the set [hlim .4. hpa (B)] where hpa (B) = hlim + B − Bpa . we compute different trajectories for a harvesting feedback of the form h(t. 4. the value of Bpa is √ (K + bhlim ) Δ Bpa = − . The viability constraint (4.5. namely: R(B − hlim ) B= . b 2b 2 with Δ = (R − 1 + bhlim ) − 4Rbhlim and K = R−1 b . Trajectories have been generated by Scilab code 8. In the simulations shown in Fig. B) = α(t)hlim + (1 − α(t))hpa (B).35). The sustainable case: Viab = ∅. 1 + b(B − hlim ) Hence. Biomass trajectories B(t) violating the viability constraint (horizontal line at hlim ) in finite time whatever the initial condition B0 .92 4 Viable sequential decisions biomass B(t) Biomass trajectories violating the constraint biomass B(t) Biomass trajectories violating the constraint 50 50 ♦ ♦ Viability threshold Viability threshold 40 40 30 30 20 20 10 0 time t 0 time t 0 10 20 30 40 50 60 70 1 2 3 4 5 6 7 8 9 10 11 (a) Biomass B(t) for stationary harvest. From (4. . (b) Biomass B(t) for random harvesting ing h(t) = h0 h(t) Fig.
depending on whether the original biomass is lower or greater than the viability barrier (horizontal line at Bpa ). (b) Viable catch h(t) ≥ hlim able biomass B(t) < Bpa Fig. Biomass trajectories violating or satis- fying the viability constraint. Harvest trajectories satisfying the viability constraint (horizontal line at hlim ). Trajectories have been generated by Scilab code 8. Sustainable case where hlim ≤ hmse .5. 4.7 A bioeconomic precautionary threshold 93 omass mass Btrajectories tories rvest h satisfying the constraint time t time t 28 10 ♦ ♦ Viability barrier Minimal harvest 9 24 8 20 7 16 6 12 4 4 0 2 1 2 3 34 5 6 7 8 9 10 11 1 2 3 4 5 6 7 8 9 10 (a) Viable biomass B(t) ≥ Bpa . 4. . Non vi.
B).alpha(t))..Horizon+1). satisfying the constraint". h_min*ones(1:0.alpha) B=zeros(1.’time t’./(1+b*B) xtitle(’Biomass trajectories violating the constraint’. xset("window". for i=1:nbsimul ’time t’.-4.2:Horizon.’ur’) Horizon=10.h).5 // for instance endfunction Horizon=60.11)..’biomass B’) function error=viabbarrier(B) error=SY(B)-h_min // number of random initial conditions endfunction nbsimul=30.xbasc().21).2:(Horizon+1). plot2d(B.alpha(t)).94 4 Viable sequential decisions Scilab code 8. h=max(h_min. for t=1:Horizon h(t)=viab(t.. // for i=1:nbsimul // exec bioeconomic_viability. legends("Minimal harvest"..B. xbasc(). for t=1:Horizon ///////////////////////////////////////////// h(t)=feedback(t. end. // // Random harvesting B(t+1)=max(0. endfunction B_V*ones(1:0. xtitle(’Biomass trajectories violating the constraint’.SY(B)) xtitle(’Sustainable yield curve associated to .B(t). B(1)=K*rand(1).plot2d(1:Horizon.B. // Population dynamics B(t+1)=max(0.22). endfunction ’time t’.2:(Horizon+1))..0).-4. // xset("window". // Population dynamics parameters end.B(t).style=-4) legends("Viability threshold".5 // for instance xset("window".’ur’) function [y]=g(B) y=R*B. function h=viab(t.5.style=-4) legends("Viability barrier".Horizon+1). plot2d(1:0.plot2d(1:(Horizon+1).h_min * ones(1:(Horizon+1))... ///////////////////////////////////////////// end.alpha*h_min+(1-alpha)*h_max(B)) endfunction // // Stationary harvesting Horizon=10. plot2d(1:(Horizon+1). B_V=fsolve(0. b=0. B=[0:1:K].. // .22).g(B(t)-h(t))).Horizon). xtitle("Harvesting trajectories . plot2d(1:(Horizon+1). end..sce B(1)=K*rand(1).-4. R=1.2:Horizon). plot2d(1:(Horizon+1).alpha) xset("window".Horizon). plot2d(1:0.( B_V / (R . xbasc().12). h=max(h_min.. for t=1:Horizon xset("window". alpha=rand(1..’biomass B(t)’) B(1)=K*rand(1)/2.viabbarrier) ///////////////////////////////////////////// // The unsustainable case ///////////////////////////////////////////// function h=h_max(B) h= B. end.01. B(t+1)=max(0.’ur’) end xset("window".2:(Horizon+1). Horizon=10.b*B_V) ) h_min= h_MSE +0.2:(Horizon+1)). plot2d(1:0. alpha=rand(1...-4.g(B(t)-h_min)). xset("window".’ur’) h=zeros(1.h_min*ones(1:0.style=-4) B=zeros(1.. for i=1:nbsimul xtitle("Biomass trajectories".Horizon+1)..g(B(t)-h(t))).’biomass B(t)’) function h=SY(B) h= B-(B.Horizon). function h=feedback(t..alpha*h_min+(1-alpha)*B).’biomass B’).’harvest h’).21). legends("Viability threshold". // numerical estimation of the viability barrier Beverton-Holt dynamics’.B).B)./(R-b*B)) endfunction ///////////////////////////////////////////// // The sustainable case B_MSE=(R-sqrt(R))/b ///////////////////////////////////////////// h_MSE=SY(B_MSE) K=(R-1)/b h_min= h_MSE *0. xbasc().style=-4) B=zeros(1.’time t’. xbasc().
2 0. 2. 1. Parameter definitions and values for anchovy and hake. In [9]. 0.366. 1. ICES indicators and reference points Two indicators are used in the precautionary approach with associated limit reference points. 0. 0. 36) × 10−3 (0. 0.8 The precautionary approach in fisheries management Fisheries management agencies aim at driving resources on sustainable paths that should conciliate both ecological and economic goals. (4.25. 0. 1. For manage- ment advice an additional precautionary reference point Bpa > Blim is used. 0. RP is for refer- ence point.2 0. the ices (International Council for the Exploration of the Sea) precautionary approach and advice rely on specific indicators and reference points such as spawning biomass or mean fishing mortality. 0.23. Definition Notation Anchovy Hake Maximum age A 3 8 Mean weight at age (kg) (υa )a (16. The second indicator.36) Ar − ar + 1 a=a r . 0. 1. Let us underline here that using limit reference points implies defining a boundary between unacceptable and admissible states. 1.1. 0.25 SSB precautionary RP (tons) Bpa 33 000 140 000 fishing mortality limit RP Flim / 0.1. is the spawning stock biomass A SSB(N ) = γa υa Na .5) Presence of plus group π 0 1 fishing mortality precautionary RP Fpa 1 − 1.5.126. 0. making it possible to reach the objective of keeping stock biomass above threshold Blim . To manage fisheries and stocks.319. It is shown how the age-structured dynamics can be taken into account for defining appropriate operational reference points. intended to incorporate uncertainty about the stock state. The first indicator. 0.8 The precautionary approach in fisheries management 95 4.4. 0. that is to say: λ r a=A F (λ) := Fa . 0.22. is the mean fishing mortality over a pre-determined age range from ar to Ar .2. 4.748. the viable control approach is used to make the relationships between sustainability ob- jectives and reference points for ices advice on stock management explicit. 0.27.42.35 SSB limit RP (tons) Blim 21 000 100 000 Table 4. 0.583.90. denoted by SSB in (2. 0. whereas it would be better to define desirable states using target reference points. 28.2 Fishing mortality at age (Fa )a (0. 1) (0.4) (0.60. denoted by F . 1) Natural mortality M 1. 0.4. 0. a=1 to which ices associates the limit reference point Blim > 0.986.42) Maturity ogive (γa )a (1.35).
the following usual advice (UA) is given: λUA (N ) = max{λ ∈ R+ | SSB(g(N. Let us define the precaution- ary approach state set .36). λ) ∈ RA + × R+ | SSB(N ) ≥ Blim and F (λ) ≤ Flim . in a stock with high abundance in the oldest age class and low abundances in the other age classes.33). For example. the set D may capture ecological. the acceptable set. λ)) ≥ Blim and F (λ) ≤ Flim } . Considering sustainable management within the precautionary approach. Acceptable controls λ. it can now be assumed that the decision maker can describe “acceptable configurations of the system. How- ever. the existence of such a fishing mortality multiplier for any stock vector N such that SSB(N ) ≥ Blim is tantamount to non-emptyness of a set of viable controls. the set of viable con- trols is not empty.96 4 Viable sequential decisions The associated limit reference point is Flim and a precautionary approach reference point Fpa > 0. (4. λ) of states and controls. / Vlim := N ∈ RA + | SSB(N ) ≥ Blim . involving spawning stock biomass and fishing mortality indicators. In practice.38) is a viability domain for the acceptable set Dlim under dynamics g.” that is acceptable cou- ples (N. Whenever the precautionary approach is sustainable. are those for which F (λ) ≤ Flim .34) and (2. we introduce the following ices precautionary approach configuration set: . This observation implies the existence of a viable fishing mortality multiplier that allows the spawning stock biomass of the popula- tion to remain above Blim along time. as higher fishing mortality rates might drive spawning stock biomass below its limit reference point. if recruitment is low. Acceptable configurations To define sustainability. whatever the fishing mortality. which form a set D ⊂ X × U = RA × R. maintaining the spawning stock biomass above Blim from year to year will not be sufficient to ensure the ex- istence of controls which make it possible to remain indefinitely at this point. When Vlim is not a viability domain of the acceptable set Dlim under dynamics g. according to this reference point. This justifies the following definitions. . spawning stock biomass would be above Blim but would be at high risk of falling below Blim the subsequent year. Here. (4. economic and/or sociological requirements.37) Interpreting the precautionary approach in light of viability The precautionary approach can be sketched as follows: an estimate of the stock vector N is made. if valid. / Dlim := (N. (2. the condition SSB(N ) ≥ Blim is checked.38) We shall say that the precautionary approach is sustainable if the precau- tionary approach state set Vlim given by (4. the dynamics g is the one introduced in (2.
it is not enough to keep it there from year to year. (4. and that the proportion γa of mature individuals and the weight υa at age are increasing with age a.39) is never satisfied and the precautionary approach is not sustainable.39) B∈[Blim . The previous condition is easy to understand when there is no plus-group π = 0. 1 − πe−M R≥R where R := Blim . Other conditions based upon more indicators have to be checked. Bay of Biscay anchovy: sustainability of advice based on the spawning stock biomass indicator for various stock recruitment relationships. A constant recruitment is generally used for fishing advice. . either. as well as the threshold Blim . the resulting recruits would be able to restore the spawning biomass at the required level. whatever the value of Blim . Assuming a constant recruitment R. we obtain 0 −M 1 inf πe B + γ1 υ1 ϕ(B) ≥ Blim .41) Hence. when γ1 = 0 (the recruits do not reproduce) condition (4. and only if.39) involves biological characteristics of the population and the stock recruitment relationship ϕ. in the worst case.2. (4. that is if. so the following simplified condition can be used. the precautionary approach is sustainable if. The answer is given in the last column of the table. to keep spawning stock biomass above Blim for an indefinite time. and only if. we have πe−M Blim + γ1 υ1 R ≥ Blim . the precautionary approach is sustainable if. γ1 υ1 R ≥ Blim . 4. Condition (4.39) does not depend on the stock recruitment relationship ϕ between 0 and Blim . Assuming a constant recruitment R and no plus group. However. It does not depend on Flim . where the whole population would spawn and die in a single time step. That is. (4.40) γ1 υ1 making thus of R a minimum recruitment required to preserve Blim .84 1 no Ricker inf [· · · ] ≥ Blim 0 21 000 no B≥Blim Table 4. the precau- tionary approach is sustainable if.+∞[ Notice that. it is worth pointing out that condition (4. stock recruitment relationship Condition Parameter values Threshold Sustainable Constant (mean) Rmean ≥ R 14 016 ×106 1 312 ×106 yes Constant (geometric mean) Rgm ≥ R 7 109 ×106 1 312 ×106 yes Constant (2002) R2002 ≥ R 3 964 ×106 1 312 ×10 6 yes Constant (2004) R2004 ≥ R 696 ×106 1 312 ×106 no Linear γ1 υ1 r ≥ 1 0. that is Ma = M .13 If we suppose that the natural mortality is independent of age.8 The precautionary approach in fisheries management 97 Result 4. and only if. and only if.
Case study: Bay of Biscay anchovy Because the first age class of Bay of Biscay anchovy accounts for ca. n−1 The following result related to the vacuity of the viability kernel can be obtained.98 4 Viable sequential decisions Case study: Northern hake For hake. Whenever it is not empty. . For the sake of simplicity. mainly determined by the stock recruitment relationship as there is no plus-group.8.4. 4. The answer is given in the last column of Table 4. hlim := 1 − (1 − m)n−1 (4. Assuming various stock recruitment relationships. the viability kernel Viab is characterized as follows. In this case.42) ⎪ ⎪ S ⎩ if m = 0 . it is determined whether the precautionary approach based on the current value of Blim is sustainable.9). The second column contains an expression whose value is given in the third. to the threshold in the fourth. we can verify that the total surface of the forest remains stationary: n Ni (t) = S . 80% of spawning stock biomass. i=1 As described and proved in [20]. we assume here that mortality and fertility parameters coincide in the sense that m = γ in (4. since no plus group is present. and has to be compared. 4. and taking π = 0. the following felling threshold hlim is deciding to characterize the viability kernel: ⎧ ⎪ ⎪ m(1 − m)n−1 ⎨S if m = 0 . the precautionary approach is never sustainable because γ1 = 0. the via- bility kernel is empty: h > hlim =⇒ Viab = ∅ .39). the sustainability of the precautionary approach will depend on the relationship between the biomass reference point and the stock dynamics. Result 4.14 For any minimal harvesting level h greater than hlim .9 Viable forestry management Now we consider the problem introduced in Subsect. according to condition (4.2.
Two cases for m are distinguished. provided by (4. . Then the viability kernel is given by ⎧ ⎫ ⎪ n ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎨ Nl = S ⎪ ⎬ n Viab = N ∈ R+ l=1 n .2. Indeed. Indeed.n−2 m(1 − m)i l=n−i−1 Two kinds of viable regulations have been used in the simulations hereafter. 4) .. The largest sustainable value. the inertial viable regulation hI consists in choosing a viable control h minimizing decision’s change |h − hc |: hI (N ) = arg min |h − hc | . n 1 − (1 − m)i hM (N ) = max h = min (1−m) Nl − h . . (4. min (1 − m) Nl − h .43) i=0. Given the resource state N ∈ Viabh and a current felling level hc . guaranteed catch h = 4.. At any surface vector N in viability kernel Viab..15 Consider h ∈ [0. h∈H viab (N ) The interest of such a policy is to take into account rigidity of decisions or behaviors. The feedback hM consists in choosing at any N ∈ Viab the largest value h allowed by the viability conditions: . 4. these additional inequal- ities impose other constraints on N (t) to maintain sustainability in the long term horizon. 6. i) m = 7%. computed from (4.. hlim ] and for N ∈ Viab. total surface S = 20 and the initial conditions N (t0 ) = (2. as long as the current decision is relevant.9 Viable forestry management 99 Result 4. n − 1 ⎪ ⎪ ⎩ l=n−i ⎭ The linear additional inequalities contained in the conditions advocate for the anticipation of potential crisis Nn (t) < h .n−2 m(1 − m)i l=n−i−1 • Inertial viable harvesting. is hlim 4. ..- n 1 − (1 − m)i H viab (N ) = h .43) is computed. Now the viability analysis is illustrated for five age classes n = 5.. we know that the viable regulation set is not empty. hlim ]. this policy is not modified. Result 4. 5. Maximal viable harvesting.. 3.42). • Maximal viable harvesting. The viability kernel exhibits the states of the forest compatible with the constraints. The present step is to compute the sustainable management op- tions (decisions or controls) associated with it. .16 When h ∈ [0. ⎪ ⎪ 1−(1−m)i ⎪ ⎪ ⎪ ⎪ Nl ≥ m(1−m)i h i = 1.. + . . h∈H viab (N ) i=0.
0 6.0 4.0 5.0 4.4 5.1 4.7 4.0 8.0 0.0 5.2 4.0 0.0 0.0 4.5 → 5.5 N3 5.6 4.3 4.6 5.0 4.0 8.0 5.56 0.0 3.0 4.56 0.2 We notice that viable trajectories converge asymptotically towards a sta- tionary state.4 5.0 8.0 8.0 3.0 4.0 N4 6.5 5.3 4.2 N1 4.4 5.4 5.0 4.7 4.0 → 0.1 Invariance kernel The invariance kernel refers to the set of states from which any state tra- jectory generated by any a priori admissible decision sequence satisfies the constraints.7 N2 3.7 4.6 2.0 5.5 4.0 5.0 4. The maximal viable harvesting hM is chosen.4 5.8 3.0 3.0 4.0 3.0 4.9 1.0 4.0 4. the inertial viable harvesting that fulfills (4.0 0.0 8.0 4.0 4.0 4. 4. The largest sustainable value is now hlim = 5.3 4.0 4. the constraints do not really influence the evolution.8 4.0 0.2 4.0 5.5 5.0 N2 3.0 4.7 5.0 4.7 4.0 8.0 4.8 4.0 6.4 6. iii) m = 0.0 0.0 5.0 3.0 2.5 5.0 4. This is the idea of invariance or strong viability.0 4.0 4.1 5.0 0.41 0.0 4.7 4.0 0.7 2.0 4.4 4.0 4.0 5.43) is applied.0 4.0 4.0 0.10.0 N1 4.56 N4 6.0 4.0 1.4 5.2 5.0 8.0 4.0 5.0 4.0 0. .4 hI 4.0 5. t 0 1 2 3 4 5 6 7 8 9 10 N5 2.0 4.0 4.0 4.2 5.0 4.0 4.0 5. This time.3 N3 5.4 5.0 N1 4.0 8.0 4.0 0.0 0.0 4.0 5.0 5.6 3.7 4.100 4 Viable sequential decisions t 0 1 2 3 4 5 6 7 8 9 10 · · · +∞ N5 2.7 5.3 4.0 4.5 4. 4.0 4.4 5.0 → 4.7 4.7 4.0 4.0 4.0 2.3 4.4 → 4.8 3.4 5.0 8.0 It has to be noticed that these viable trajectories become stationary in finite time.7 5.5 4.56 0.0 4.3 4. t 0 1 2 3 4 5 6 7 8 9 10 N5 2.7 → 4.0 4.0 5. ii) Again m = 7%.0 0.5 → 5.3 4.0 4.7 4.0 4.0 0.0 hM 8.0 4.0 5.6 hM 4.3 4.6 3.0 0.6 2.9 1.56 0.5 5.0 2.0 N4 6.7 4.0 It has to be stressed that these viable trajectories become (n − 1)-cyclic in finite time.10 Invariance or strong viability It may happen that.0 8.7 5.4 5.0 4.0 4.0 4.0 8.7 4.0 4.0 0.2 4.0 0.8 N2 3.0 4.0 4.0 0.4 5. for some initial states.4 5.0 2.0 8.0 4.0 N3 5.9 5.
. . Notice that Inv(s) ⊂ A(s) . x) in (4. x(t) . . and that the invariance kernel at horizon T is the target set A(T ): Inv(T ) = A(T ) . 4. Let us point out that the viability and invariance kernels coincide whenever the set of possible decisions or controls B(t. ⎪ ⎨ .1) and the constraints (4. once the “true constraints” Bviab (t. (4. x) is reduced to a singleton and only one decision is available: B(t. x(t). .1) and constraint (4. T − 1} ⎪ ⎬ Inv(s) := x ∈ X dynamics (4. The invariance kernel at time s ∈ {t0 . . the invariance requirement is more stringent than the viability one and the invariance kernel is contained in the viability kernel: Inv(t) ⊂ Viab(t) . . t = t0 .2a)–(4. Moreover. because the constraint (4. . .45) ⎪ ⎪ u(t) ∈ Bviab t. T − 1 . T } for the dy- namics (4. 4. x) = {u(t. T . . .14) and the viability kernels Viab(t) associated to the dynamics (4. t = t0 . It happens then that the domains Viab(t) are the invariant kernels for this new problem related to the property of viable controls which ensure that the above problem is equivalent to: . T − 1} ⎪ ⎪ ⎩ ⎭ and (4.10.1) and the constraints (4.2b) is satisfied at time s. . . ⎩ x(t) ∈ Viab(t) . t = t0 . . .44) ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ the constraints (4.17.2d) are known.2c) is the set denoted by Inv(s) defined by: ⎧ ⎫ ⎪ for every decision u(·) ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ and state x(·) starting from x at time s ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎨ satisfying for any time t ∈ {s.2a) .2b) are satisfied ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ for t ∈ {s.2 Invariance and viability Of course. . . . the same dynamics can be considered but under these new constraints. .2c) at final time T.10 Invariance or strong viability 101 Definition 4. . . u(t) (4. .2b)-(4. . x(t + 1) = F t. T − 1 . x)} =⇒ Inv(t) = Viab(t) .2a)– (4. namely: ⎧ ⎪ x(t0 ) = x0 ∈ Viab(t0 ). . .
. A. The proofs of the following Propositions follow the ones given for viability in Sect. x(t). This principle holds true through both geometrical and func- tional formulations. This situation may be useful in case of optimal intertemporal selection.3 Maximality and Bellman properties We also recover Bellman properties and the dynamics programming principle for invariance. The extended function V : (t. x(t) .18. x) are used instead of B(t. x) . 5.46) u(t) ∈ Bviab t. . T − 1 . . u) ∈ Inv(t + 1)} . We distinguish the infinite and finite horizons. x) in the dynamic programming method. . This case occurs in a cost-effectiveness perspective. ⎩ . T − 1 . x(t + 1) = F t. . A geometric characterization in the finite horizon case is given by the following Proposition. ex post admissible decisions Bviab (t.2 in the Appendix. . 4.47) Inv(t) = {x ∈ A(t) | ∀u ∈ B(t. The invariance kernel satisfies the backward induction. In this case. we obtain a functional dynamics programming characterization in the finite horizon case.19. Similarly. Proposition 4. . Proposition 4. where t runs from T − 1 down to t0 : Inv(T ) = A(T ) .10. t = t0 . u(t) (4. x. (4. as in Sect.102 4 Viable sequential decisions ⎧ ⎨ x(t0 ) = x0 ∈ Viab(t0 ). . t = t0 . x) . F (t.
u∈B(t.x) The autonomous case and infinite horizon framework provide the simplest characterization since time disappears from the statements. F (t. (4.20.19) and with T = +∞. Proposition 4. the invariance kernel does not depend on t and we write it Inv. x) = sup ΨA(t) (x) + V t + 1. or dynamic programming equation. In this case.→ ΨInv(t) (x) is the so- lution of the Bellman equation.48) ⎪ ⎩ V (t. In the autonomous case (4. u) . the extended function V : x . x. where t runs from T − 1 down to t0 : ⎧ ⎪ ⎨ V (T. x) = ΨA(T ) (x) .
49) V (x) ≥ ΨA (x) .→ ΨI nv(x) is the largest solution of the Bellman equation. . V (x) = sup V F (x. u) . u∈B(x) (4. or dynamic programming equation.
Definition 4.50) An equivalent functional characterization is ΨV (x) = sup ΨV F (x. 4. u) .22. u∈B(x) Proposition 4. In the autonomous case (4. u) ∈ V . (4. the invariance kernel Inv of A is the largest invariant domain contained in A.19). . ∀u ∈ B(x) . In the autonomous case (4.10 Invariance or strong viability 103 A geometric characterization is given using invariant domains as follows. a subset V ⊂ X is said to be an invariant (or strongly invariant) domain if ∀x ∈ V .21.19) and with T = +∞. F (x.
and P. P. J. Cury. [9] M. M. Journal of Environmental Management. S. [6] F. Environmental Resource Economics. S. 1:1–48. [11] L. De Lara. Doyen. Schellnhuber and F. [5] T. pages 217–234. Doyen. Guilbaud. The safe minimum standard of conservation and endan- gered species: a review. 36:385–396. [2] C. [7] P. J. Pelletier. Béné. 64(4):761–767. Viability Theory.. 2007. Y. Mar. De Lara. Ecological Economics. Sustainability of fisheries through marine reserves: a robust modeling analysis. ICES Journal of Marine Science. Quali- tative properties of trajectories of control systems: a survey. Rochet. and H. T. 62(3):577–584. 542 pp. Bruckner. L. Is a management framework based on spawning-stock biomass indicators sustainable? A viability approach. L. Gabay. 2003. Monotonicity properties for the viable control of discrete time systems. 2001. M. J. 2006. Doyen. Earth system analysis and management. 2001. Berrens. and M. Aubin. Shannon. R. [8] M. [4] R. G. J. Viability theory for an ecosystem approach to fisheries. L. 2005. A viability analysis for a bio-economic model. 56(4):296–302. 28:104–116. Doyen. H. J. Helm. Doyen and C. F. Garcia. [10] L. Clarke.-J. T. C. Sci. R. Storage and viability of a fishery with resource and market dephased seasonnalities. 2000. L. 1995. Systems and Control Letters. Le- imbach. In Environmental Modeling and Assess- ment. Petschell-Held. 69:1– 13. 1999. Ledayev. Birkhäuser. and D. Rochet. chapter 4. L. Doyen. Sustainability of ex- ploited marine ecosystems through protected areas: a viability model and . and D. 15:1–26. Climate change decision-support and the tolerable windows approach. Toth. Guilbaud.References [1] J. Ferraris. Boston. Journal of Dynamical Control Systems. De Lara. H.-P. Environmental Conservation. and M. Mullon. and L. Schellnhuber. Stern. H. 1991.-M. ICES J. Wolenski. Fussel.-J. Béné. [3] C. Toth. Béné and L. C.
2007. Report of the ices advisory committee on fishery management and advisory committee on ecosystems. Animal Research. in press. November 2007. Schellnhuber and V. Ecological Modelling. 2000. Sheffran. Economic Theory and Sustainability. 1988. Morris and D.ch/. Ambrosi.-P. August 2007. P. Valuing the Future. pages 437–450. [22] M. . New York. J. Integrating Science for Sustainability.Y. Martinet and L. [24] R. [16] IPCC. Quantitative Conservation Biology: Theory and Practice of Population Viability Analysis. 2007.17–39. Controlled invariance of discrete time systems. Terreaux. Schaffert. Ecological Mod- elling. 208(2-4):353–366. and L. 1.ipcc. and D. Wenzel. volume 1790 of Lecture Notes in Computer Science.106 References a coral reef case study. 2004. 1544 pp. 29(1):p. [18] V. Resource and Energy Economics. [23] M. Optimal timing of co2 mitiga- tion policies for a cost-effectiveness model. [12] L. L. F. Vidal. 64(2):411–422. Doyen. Doyen. Earth System Analysis. B. and O. Genin. and J. Doyen. Eisenack. Tichit. Mathematics and Computer Modeling. Lygeros. Tichit. L. Ecological Economics. Doyen.. February 2006. Sastry. Kropp. 2004. Hubert. A viability model to assess the sustainability of mixed herd under climatic uncertainty. Defining viable recovery paths toward sustainable fisheries. March 2006. Thébaud. Renault. Doyen. L. 206(3-4):277–293. Martinet. [17] V. Springer. Lemel. Mathematics and Computer Modeling. [21] H. Springer-Verlag. [19] W. J. The viability analysis of manage- ment frameworks for fisheries. Sinauer Associates. 2004. and P. Dumas. A co-viability model of grazing and bird community management in farmland. J. S. Rapaport. In Hybrid Systems: Computation and Con- trol. and S. 53(5):405–417. 1998. [15] ICES. Doyen. Sustainable management of renewable resource: a viability approach. J. Sustainable management of an exhaustible resource: a viable control approach. 2003. 43(5-6):466–484. 11(1):69–79. Heal. Doak. [13] K. Columbia University Press. Ices advice. and O. [20] A. [14] G. J. F. Environmental Modeling and Assessment.
However some advantages or outputs are not easy to assess in monetary units. An important debate for the optimal management of natural resources and the environment relates to the method of economic valuation of ecological or environmental outcomes. Such difficulties advocate for the use of Cost-Effectiveness (ce) analysis which also measures costs but with outputs expressed in quantity terms. Green Golden and Chichilnisky approaches. For relevant mathematical references in the discrete time optimal control context. maximizing the sum of discounted utility of consumption along time in an economic growth model. 4. are exposed for instance in [8] in the continuous case. minimizing the cost of recovery for an endangered species. we especially support the use of the dynamic programming method and Bellman equation since it turns .5 Optimal sequential decisions Many decision problems deal with the intertemporal optimization of some cri- teria. Contingent valuation methods aim at pricing such non-use values. 15]. Such is also the case for costs relying on damages of global changes [7] whose pricing turns out to be highly uncertain and controversial. In mathe- matical terms. the quantity constraints are directly taken into account in the criterion to optimize through adjoint variables including prices. maximizing the discounted rent of a fishery are all examples of dynamic optimal control problems. It includes in particular the maximin. Optimality approaches to address the sustainability issues and. shadow prices or existence values. ce deals with optimal control under constraints. Achieving a co2 concentration target in minimal time. The usual economic ap- proach of Cost-Benefit (cb) relies on the monetary assessment of all outcomes and costs involved in the management process. In the case of cb. 5] to- gether with [2] that contains optimality methods and models especially for the management of animal populations. Basic contributions for the optimal management or conservation of natural resources and bioeconomic modeling can be found in [3. intergenerational equity and conser- vation issues. In this textbook. This is the case for non-use values or indicators of ecological services of biodiversity [13] such as aesthetic or existence values. especially. Such concerns have fundamental connections with “price versus quantity” issues pointed out by [14]. we refer to [1.
T − 1 . u(t) .14 presents the maximin case. 5. (5. 5. (5. 5.11 focuses on the final payoff problem related to the Green Golden issues. T − 1 . the dynamic programming can be expanded to the uncertain case as will be exposed in the chapters to come. 2.1 provides the general prob- lem formulation for several intertemporal optimality criteria.108 5 Optimal sequential decisions out to be a relevant approach for many optimal control problems including additive and maximin criterion as well as viability and invariance problems. t = t0 .2. some admissibility or effectiveness constraints are to be sat- isfied as underlined in Chap. . . 4 focusing on invariance and viability. . . 2. These constraints include state and control constraints respected at any time x(t) ∈ A(t) ⊂ X . . Section 5. The chapter is organized as follows. t = t0 . x(t). By dynamic programming. with an illustration of the management of an ex- haustible resource in Sect. with an application to the Hotelling rule in Sect. t = t0 .9. . 5. Moreover. The so-called “maximum principle” is presented in Sect. The dynamic programming method for the additive criterion case is exposed in Sect. u(t) ∈ U = Rp is the control or decision. .1. . as in Sect. T corresponds to the time horizon which may be finite or infinite. Furthermore.15. .9.8. the dynamic optimality decision problem is solved sequentially: one starts at the final time horizon and then applies some backward induction mechanism at each time step. . We detail this process and ideas in what follows.9 for optimal and feasible sequential decisions in discrete time.1 Problem formulation Let us briefly recall the mathematical material already introduced in Sect.2) u(t) ∈ B t. Section 5. In addition.1) where x(t) ∈ X = Rn is the state. Then various examples illustrate the concepts and results for natural resource management. . with x(t0 ) = x0 . . while x0 and t0 stand for the initial state and time conditions. x(t) ⊂ U . x(t + 1) = F t.1 Dynamics and constraints We consider again the following nonlinear dynamical system. T . it is shown that the other well known approach termed Pontryagin maximum principle to cope with optimal control can be derived from the Bellman equation in a variational setting under an appropriate hypothesis. . 5. Section 5. 5.
. A criterion π is a function π : XT +1−t0 × UT −t0 → R (5. The Rawlsian or maximin form in the finite horizon is π x(·). u(·) = min min L t.) while M is the final performance. Different criteria have been detailed in Sect. Such a feasibility set.3 The general problem of optimal control under constraints The constraint (5.1.. with a final payoff. The additive criterion with final payoff in the finite horizon is −1 T π x(·).T −1 and.9.6) t=t0 .. (5.5 and studied in Chap. 2. u(·) = L t. one may aim at ranking the different feasible decision paths u(·) accord- ing to some specific indicator of performance or criterion π. utility.9.T −1 5.. payoff. u(·) = M T. x(t). In our discrete time framework when the hori- zon T is finite.. 5.4) t=t0 Function L is referred to as the system’s instantaneous performance (or profit. the expression is somewhat heavier to write: & ' π x(·). has already been introduced in Subsect. x0 ) ⊂ XT +1−t0 × UT −t0 . x(t). benefit.5) • The Maximin. M T. we shall label Green Golden a criterion of the form π x(·). (5. (5.7) t=t0 . u(t) . • General additive criterion...1) settle the set of all possible and feasible state and decision trajectories.1. Such pay- off includes usual discounted cases as well as Green Golden Rule or Chichilnisky performances.3) which assigns a real number to a state and control trajectory. 2. cost or cost-benefit over T + 1 stages. Of particular interest is the selection of a policy optimizing (minimizing or maximizing) this performance or criterion π. x(T ) .2) specified beforehand combined with the dynamic (5. etc. u(·) = min L t. x(t). u(t) + M T..1 Problem formulation 109 5.4 and we shall here concentrate on two main cases. payoff. x(T ) . We shall consider maximization problems where the criterion is a payoff. representing the total gain.2 The criterion and the evaluation of the decision Now. u(t) . 4: . x(T ) . (5. denoted by T ad (t0 .
110 5 Optimal sequential decisions ⎧ ⎫ ⎪ x(t0 ) = x0 . . t = t0 . benefit. u(·) . x(t) . we shall in practice abbreviate (5. . . x0 ) = max π x(·).u(·) ∈T ad (t0 . . x0 ) := sup π x(·). . ⎧ ⎨ x(t0 ) = x0 ∈ Viab(t0 ) ⇐⇒ x(t + 1) = F t. x(t)). . x0 ) such that π (t0 . .adx0 ) in (5. . (5.9) x(·). x(t)). 1 We shall only consider maximization problems. (5.). t = t0 .10) and to viable decisions examined in Chap. . u(·) .9) in π (t0 . etc. the feasible set T ad (t0 . . x0 ) ⇐⇒ ⎪ ⎪ u(t) ∈ Bviab (t. . In fact. . x0 ) = −∞. . x0 ) is related to the viability kernel Viab(t0 ) in (4. . . one should simply change the sign of x(·).8) This is the set of admissible trajectories which visit x0 at time t0 while re- specting both the constraints and the dynamics after time t0 . To cope with the minimization problem inf π x(·). . . As pointed out in that chapter (Proposition 4. x0 ) = x(·). . t = t0 . .x0 ) Abusively. T . T − 1 T ad (t0 . T − 1 ⎩ u(t) ∈ Bviab (t. T ad (t0 . u(·) = π x (·). . . . . ⎪ ⎪ u(t) ∈ B t. . . .11) x(·). x0 ) ⊂ XT +1−t0 × UT −t0 is given equivalently by ⎧ ⎪ x(t0 ) = ⎪ x0 ⎨ x(t + 1) = F t.u(·) ∈T ad (t0 . u(t) . x(t). Any path x (·).u(·) ∈T ad (t0 .10) u(·) Whenever feasibility is impossible. u(·) . . i. t = t0 . Definition 5. the “true” state constraints are captured by the viability kernels and T ad (t0 . T − 1 .x0 ) π since inf z∈Z f (z) = − supz∈Z (−f (z)). T − 1 ⎩ x(t) ∈ Viab(t). . . x0 ) = ∅. by convention we set the optimal criterion to minus infinity: π (t0 . u(t) . T (5. x0 ) := sup π x(·). 4 (see Definition 4. ⎪ ⎪ ⎨ ⎪ ⎬ x(t + 1) = F t. the problem reads1 π (t0 . u(·) .9) is called the optimal performance. utility. T − 1 x(·).1. T − 1 ⎪ ⎪ ⎩ ⎭ x(t) ∈ A(t) . t = t0 . u (·) (5. u(·) ∈ T ad (t0 . t = t0 . When the assessment π measures payoff (or profit. .14)). . t = t0 . x(t). t = t0 . x(t). .4).x0 ) is a feasible optimal trajectory or an optimal path. u (·) ∈ T (t0 .e. u(t) . The optimal value π (t0 . .1 and (4.
1] is a discount factor. Such a convenient configuration occurs in the special case without state constraint. Such difficulties justify the use of Cost-Effectiveness (ce) analysis which also measures costs but with outputs expressed in quantity terms. whenever the viability kernel Viab(t0 ) is empty. In mathematical terms. An invariant state constraint set means that. ∀x0 ∈ X .u(·) ∈T ad (t0 .x0 ) t=t0 (5. shadow prices or existence values. Cost-Benefit In this case. 4.4 Cost-Benefit versus Cost-Effectiveness Two specific classes of problems are worth distinguishing: Cost-Benefit versus Cost-Effectiveness. it is worthwhile to put a hold on the computation of any optimal solution as no feasible solution exists: Viab(t0 ) = ∅ ⇐⇒ T ad (t0 . Let us also point out that an interesting case corresponds to an invariant state constraint set as explained in detail in Sect.1. the objective is the intertemporal discounted profit. u(t) − C x(t). x(·). x0 ) = sup ρt B x(t). namely when A(t) = X.1 Problem formulation 111 Let us stress the fact that. Such is also the case for costs relying on damages of global changes whose pricing turns out to be highly unknown.12) where ρ ∈ [0. 5. thus revealing that every a priori admissible state x(·) and all decision u(·) trajectories will satisfy the constraints along time. u(t) . Such concerns have connections with “price versus quan- tity” debates. x0 ) = ∅ . for any time t. namely the difference between benefits B and costs C in monetary units T −1 π (t0 . The usual economic approach of Cost-Benefit (cb) relies on the monetary assessment of all outcomes and costs involved in the manage- ment process. the invariance kernel Inv(t) of Defi- nition 4. In the case of cb. the quantity constraints are directly taken into account in the criterion to optimize through adjoint variables including prices. no state constraints bind the optimal solution and. This is the case for non-use values of ecological services of bio- diversity such as aesthetic or existence values. 5. . However some advantages or outputs are not easy to assess in monetary units.17 coincides with the initial state constraint set A(t0 ). In other words. generally.10. the constraints do not really reduce the choice of the decisions and only the initial state constraint A(t0 ) prevails. ce deals with optimal control under constraints.
2 Dynamic programming for the additive payoff case The additive payoff case plays a prominent role in optimal control for the separable form which allows for the classical Bellman equation and for its economic interpretation as an intertemporal sum of payoffs. u(t) ≥ 0 5.2. x(T ) . x0 ) = ⎧ inf ρt C x(t). A. u(·) ∈ T ad (t . However.1 The optimization problem In this section. constraints at time t depend only on time t and state x(t). it is not essential for dynamic pro- gramming to apply it in the deterministic case. as pointed out in [15].2 Additive value function The additive value function V at time t and for state x represents the optimal value of the criterion over T − t periods. .14) x(·). finally. given that the state of the system x(t) at time t is x. x(t). x0 ) = sup L t. u(t) ≥ 0. capturing the effectiveness of the decisions.13) ⎨ x(·). 2 This is a traditional assumption. See the proofs in Sect. there is generally an additional state-control constraint.112 5 Optimal sequential decisions Cost-Effectiveness In this case. (5. u(t) . A general form is considered which combines an instantaneous payoff L together with a final requirement M : −1 T π (t0 . For this reason the objective is now intertemporal discounted costs minimization: −1 T π (t0 .3.2. 5. the dynamic is a first order difference equation and. the monetary evaluation of benefits. in a sense.u(·) ∈T ad (t0 . u(t) + M T. and replacing. (5. we focus on the maximization problem for additive and sepa- rable forms in the finite horizon. x ) 0 0 t=t0 ⎩ Y x(t). 5. in vecto- rial form Y x(t).x0 ) t=t0 We shall display that the following value function is the solution of a backward induction equation by observing that we can split the maximization operation into two parts for the following reasons: the criterion π is additive2 .
1) and under constraints (5. (5. (5. This approach generally renders dynamic programming numerically untractable for high dimensions of the state (curse of dimension- ality).4 and 5.2). for x ∈ Viab(t) −1 T V (t.x) s=t with the convention that V (t.16) ⎪ ⎩ V (t. x0 ) of Bellman func- tion: V (t0 . u) .3. . For the maximization problem (5. Proposition 5. 5. x0 ) . the value function is given by a backward induction. for all (t.u(·) ∈T ad (t.2. .5 can be found in Sect. x) := sup L s. x(s). the value function in (5. x) = M (T.15) is the solution of the following backward dynamic programming equation (or Bellman equation). The common proof of the three following Propositions 5. In the case without state constraint where A(t) = X in (5. u) + V t + 1. u(s) + M T.3. which is simpler to formulate. given the initial state x0 . x(T ) .3 in the Appendix.14) with dynamic (5. x) of time t and state x. starting from the final term M in (5. x. .17) over the decision space U.1)-(5. x) := −∞ for x ∈ Viab(t). 5.x) Thus. where t runs from T − 1 down to t0 : ⎧ ⎪ ⎨ V (T. we define a function V (t. Therefore. F (t. x) .14) and proceeding with a sequence of maximizations over u ∈ U. 5. x0 ) = π (t0 . .2)-(5.2 Dynamic programming for the additive payoff case 113 Definition 5. T − 1. x) = sup L(t. . A.15) x(·). Case without state constraint We first distinguish the case without state constraints. the optimal sequential decision prob- lem (5.14) refers to the particular value V (t0 . u∈B(t.2).3 Dynamic programming equation We shall now see the principle of dynamic programming which consists in replacing the optimization problem (5.14) over the trajectories space XT +1−t0 × UT −t0 by a sequence of T + 1 − t0 interconnected optimization problems (5.2. named additive value function or Bellman functionas follows: for t = t0 . x. x).
x) where Viab(t) is given by the backward induction (4. thus.17) en- ables us to compute the value function V (t.15) is the solution of the following backward dynamic programming equation (or Bellman equation). x) a value3 u ∈ B(t. the case taking into account state constraints is presented. x) and. the optimal payoff π . The value function defined in (5. x) given by (4.19) 5. and where the supremum in (5. if we denote by u (t. u) ∈ Viab(t + 1)} . Of course. The following Proposition 5. u) . ⎨ (5. ⎧ ⎪ V (T. assuming the additional hypothesis that the supremum is achieved in (5.5 claims that the dynamic programming equa- tion exhibits optimal viable feedbacks.17) for at least one decision. F (t.17) ⎪ ⎩ V (t. For any time t and state x ∈ Viab(t).14). . a stronger result is obtained since Bellman induction optimization reveals relevant feedback controls. 2.114 5 Optimal sequential decisions Case with state constraints Now. it is more complicated than the previous one since viability and optimality conditions are combined. x) | F (t. u) ∈ Viab(t + 1)} . x.17) is over viable controls in Bviab (t. In fact. Proposition 5.10. (5.18) ⎩ Viab(t) = {x ∈ A(t) | ∃u ∈ B(t. Indeed. x) defines an optimal feedback for the optimal control problem in the following sense.11) ⎧ ⎨ Viab(T ) = A(T ) . x. x.2. (5. where t runs from T − 1 down to t0 .17). ∀x ∈ Viab(t) .5.4 Optimal feedback As we have seen. Proposition 5. the backward equation of dynamic programming (5. x. assume the existence of the following feedback decision 3 See the footnote 13 in Sect. u) + V t + 1. u∈Bviab (t. x) which achieves the maximum in (5. then u (t.4. namely Bviab (t. x) = {u ∈ B(t. x) . F (t. x) = M (T. ∀x ∈ Viab(T ) . x) = sup L(t. x) .
3 Intergenerational equity for a renewable resource Let us return to the renewable resource management problem presented in Sect. T − 1.x) Then u is an optimal viable feedback for the maximization problem (5. x (t + 1) = F (t. when x0 ∈ Viab(t0 ).3 Intergenerational equity for a renewable resource 115 u (t. For the sake of simplicity. B) = ρ2 L(B) ⎪ ⎪ ⎪ ⎪ ⎪ V (1. The Bellman equation (5. (5. we consider the particular case of T = 2 periods and we suppose as well that the discount factor ρ equals the growth rate of the resource 1 ρ= with R > 1 . that is. . 5. (5.21) for t = t0 . u (t) = u (t. x(t)) . h(·) t=t0 under the dynamic and constraints B(t + 1) = R B(t) − h(t) . belongs to T ad (t0 .20) u∈Bviab (t. (5. 5. . F (t. x) ∈ arg max L(t. .2 T −1 sup ρt L h(t) + ρT L B(T ) .14) under constraints (5. B) = sup {ρL(h) + V (2. u (t)) . x. u (·) . RB − h))} ⎨ 0≤h≤B . u (·) generated by x (t0 ) = x0 . for instance).8) in the sense that.x0 ) Notice that the feedback found is appropriate for any initial time t0 and initial state x0 ∈ Viab(t0 ). u(·) = π x (·). that is to say L < 0. and strictly concave. 0 ≤ h(t) ≤ B(t) . x0 ) given by (5. / ⎪ ⎪ = sup ρL(h) + ρ2 L(R(B − h)) ⎪ ⎪ ⎪ ⎪ 0≤h≤B ⎪ ⎩ = sup υ(h) 0≤h≤B .23) R The utility function L is supposed sufficiently smooth (twice continuously differentiable. x (t). x. . u) + V t + 1.8) and is an optimal feasible trajectory.u(·) ∈T ad (t0 . u) . max π x(·). the trajectory x (·).16) implies ⎧ ⎪ ⎪ V (2.22) x(·). 2. (5.
B) = B 1 + R + R2 and the value function is of the same form as L. it must necessarily satisfy the so-called first order optimality condition dυ (h ) = 0 . B (1)) are stationary: R2 h (0) = h (1) = B0 . B) = ρL( B) + ρ2 L( B) = ρ(1 + ρ)L( B) . B0 ) and h (1) = h (1. so that the optimal feedback is still linear 1+R R2 h (0. 0≤h≤B 1+R The first order optimality condition now implies R L (h ) = L ( R(B − h )) . B) = sup L(h) + V 1. one has h = R(B − h ) so that the optimal feedback is linear in B R h (1. The value function is of the same form as L: R R R V (1.116 5 Optimal sequential decisions where υ(h) = ρL(h) + ρ2 L R(B − h) . 5. h = R(B − h ). by (5. dh We then have L (h ) = ρRL R(B − h ) = L R(B − h ) . as L is a strictly decreasing function. This is closely related to the assumption ρR = 1 as shown by the following example of an exhaustible resource management. we easily find that the optimal catches h (0) = h (0. R(B − h) 0≤h≤B ) * R = sup L(h) + ρ(1 + ρ)L R(B − h) . 1+R 1+R 1+R Likewise. B0 ) and B (1) = R(B0 − h (0)). 1+R R Thus. .3. B) = B 1+R R and we check that 0 < h = 1+R B < B. we check that . Assuming that the last supremum is achieved for an interior solution h ∈]0. / V (0. the optimal harvests promote intergenerational equity as may be seen in Fig. Going forward with h (0) = h (0. B[. 1 + R + R2 In this sense. Thus.23). hence injective.
y=R*B . years=1:Horizon. // Graphic display Horizon= 10. xbasc(20+1). // vector will contain the catches h(1). R=R_whale .. linear(trajectory_whale(t)-catch_whale(t)). for t=years // per capita productivity catch_whale(t)=R^{Horizon-t+1}/ .4]).’year (t)’. K=K_whale . xset("window". [catch_whale 0]]’.1.... ’biomass B(t) in blue whale unit’) // initial condition plot2d2(yearss.. Scilab code 9.4].4 Optimal depletion of an exhaustible resource 117 Trajectories under linear growth with R=1.. Time is measured in years while population and catches is in blue whale unit.. endfunction.... style=-[3.’Catch trajectory’]. 5. Binit= K/2 ..[trajectory_whale . sum(R..sce trajectory_whale(1)=Binit . 2.05... trajectory_whale(t)... end // LINEAR DYNAMICS function [y]=linear(B). // carrying capacity (BWH.05 . R=’+string(R_whale)..20+1). 5.[trajectory_whale . K_whale = 400000.05 200000 Biomass trajectory 180000 Catch trajectory 160000 biomass B(t) in blue whale unit 140000 120000 100000 80000 60000 40000 20000 0 1 2 3 4 5 6 7 8 9 10 11 year (t) Fig. // // exec intergen_equity.. 0 ≤ h(t) ≤ S(t) for the optimal management of an exhaustible resource ..B(Horizon+1) legends([’Biomass trajectory’. plot2d2(yearss. xtitle(’Trajectories under linear growth with.. blue whale unit) trajectory_whale(t+1)=.1 S(t + 1) = S(t) − h(t) . yearss=1:(Horizon+1). trajectory_whale=zeros(yearss) .B(Horizon+1) R_whale=1. [catch_whale 0]]’ )...4 Optimal depletion of an exhaustible resource Consider the model presented in Sect. // vector will contain the trajectory B(1).^{Horizon-years(t:$)+1})*..-[3.. Trajectories are computed with the Scilab code 9.. // initialization of vector B(1). Biomass B(t) and “equity” catch h(t) trajectories for a linear dynamic model of whale growth with yearly growth rate R = 1..’ur’) catch_whale=zeros(years) .h(Horizon) // 5.
h (t. S − h) . Let us also deduce that the profile of optimal consumptions basically depends 1 on the discount factor ρ through a = ρ η−1 since h (t + 1) = a−1 h (t) .118 5 Optimal sequential decisions T −1 sup ρt h(t)η + ρT S(T )η h(·) t=t0 in the particular case of an isoelastic utility function L(h) = hη with 0<η<1. / ⎩ V (t. . contributing to the final inheritance or existence value of the re- source ρT L(S (T )) = ρT (S (T ))η > 0. where a−1 1 b(t) = with a := ρ η−1 . S(T )) = ρT S(T )η enhanc- ing the resource. ⎩ a−1 aT +1−t −1 h (t) = a−at−T aT +1 −1 S0 . In particular. the optimal extractions strictly decrease with time for usual values of the discount factor strictly smaller than 1. let us stress the fact that. thus pointing out how sustainability is threatened in such an optimality context. one can prove by induction that V (t. Result 5. a − at−T Thus. S) = ρt b(t)η−1 S η . 1[.6 Using dynamic programming. some sustainability remains since the optimal final stock is strictly positive. S) = b(t)S . 0≤h≤S Notice the “existence” or “inheritance” term M (T. by stock dynamic S (s + 1) = S (s) − h (s. By dynamic programming equation (5. the final optimal stock S (T ) and consumption h (T ) vanish for usual values of the discount factor ρ ∈ [0. for an infinite horizon T = +∞. However.21). the value function is the solution of the backward induction: ⎧ T η ⎨ V (T. S) = sup ρt hη + V (t + 1. How does this al- ter sustainability of both the exploitation and the resource? At a first glance. This fact illustrates the preference for the present of such a discounted framework. S (s)) as in (5.16). we get the optimal paths in open-loop terms from initial time t0 = 0 as follows: ⎧ T +1−t −1 ⎨ S (t) = aaT +1 −1 S0 . S (T ) > 0. S) = ρ S . .
that is to say C(h. By dynamic programming equation (5. then B0 = h (t0 ) and 0 = h (t0 + 1) = · · · = h (T − 1).7 Assume that the discount factor ρ is strictly smaller than 1 (0 < ρ < 1). S) = ρT −1 S η and that all results above may be used with T replaced by T + 1. ⎪ ⎪ T →+∞ ⎪ ⎩ lim h (T ) = 0 . not surprisingly. It is assumed that the utility function is also linear L(h) = h. B(t0 ) = B0 and 0 ≤ h(t) ≤ B(t) . the optimal control problem T −1 sup ρt h(t)η h(·) t=t 0 under the same dynamics and constraints is the same as the previous one. it is optimal to totally deplete the resource at the final period. then 0 = h (t0 ) = h (t0 + 1) = · · · = h (T − 2) and h (T − 1) = B0 RT −1−t0 . We find that S (T ) = 0: without “inheri- tance” value of the stock. the optimality problem over T periods corresponds to T −1 sup ρt h(t) . extinction and inequity Here we follow the material introduced in Sect. If ρR < 1.h(T −1) t=t 0 under the dynamics and constraints B(t + 1) = R(B(t) − h(t)) . 5. h(t0 )...2. it can be proved that the optimal catches h (t) are computed for any initial state B0 as follows..5 Over-exploitation. If ρR > 1.16).8 Optimal catches depend on ρR as follows. sustainability of the resource is altered more in such a case. ⎪ ⎪ ⎨ lim S (T ) = 0 . A similar com- putation shows that V (T − 1. Result 5. T →+∞ Furthermore.h(t0 +1). 2. Let us consider the ex- ploitation of a renewable resource whose growth is linear g(B) = RB.. Then sustainability disappears in the sense ⎧ ⎪ h (t + 1) < h (t) . 2. Hence. 5. . except for the absence of an inheritance value of the stock. extinction and inequity 119 Result 5.5 Over-exploitation. B) = 0. 1. which means that price is normalized at p = 1 while harvesting costs are not taken into account. Hence.
2. • It can be optimal to destroy the resource. or catches are maintained at zero until the last period when the whole biomass is harvested (ρR > 1). no guar- anteed harvesting occurs.24) !"#$ !"#$ economic discount factor biological growth factor which mixes economic and biological characteristics of the problem. • Intergenerational equity is a central problem: whenever ρR = 1. An extinction problem occurs as pointed out by [3]. many solutions exist. An illustrative example is provided by blue whales whose growth rate is estimated to be lower than 5% a year [10]. The solutions are displayed in Fig. it is efficient to destroy the whole biomass at the initial date.120 5 Optimal sequential decisions 3. 5. The sustainability issues captured by such an assertion are the following and depend critically upon the product ρ × R (5. Especially if biomass growth R is weak. One optimal solution is given by h (t0 ) = h (t0 + 1) = · · · = h (T − 1) = B0 /(T − t0 ). . • The discount factor ρ plays a basic role in favoring the future or the present or providing equity through ρR = 1. Such a low rate might explain the overexploitation of whales during the twentieth century that led regulating agencies to a moratorium in the sixtees [3]. If ρR = 1. the intergenerational equity problems again occur in a similar qualitative way depending on the critical value ρR. Another example with the utility function L(h) = 1 − e−h is examined in Scilab code 10. Preference for the future or present basically depends on ρR. Either the resource is completely depleted at the first period and thus catches vanish along the remaining time (case when ρR < 1). Although the optimal paths are smoother.
05: constant catches Fig.04 12 Catch trajectory Biomass trajectory 10 8 biomass B(t) 6 4 2 0 0 20 40 60 80 100 year (t) (b) Unsustainable case R = 1. . Optimal biomass B (t) (in ) and optimal catches h (t) (in ⊕) for different productivity R of the resource B(t) with T = 100.05 for the utility function L(h) = 1 − e−h . 5. Figures are generated by Scilab code 10.2.5 Over-exploitation.04 Trajectories under linear growth with R=1. extinction and inequity 121 Trajectories under linear growth with R=1.05 12 Catch trajectory Biomass trajectory 10 8 biomass B(t) 6 4 2 0 0 20 40 60 80 100 year (t) (c) “Limit” sustainable case R = 1. initial biomass B0 = 10 and discount factor ρ = 1/1.1 Trajectories under linear growth with R=1.1 50 Catch trajectory Biomass trajectory 40 biomass B(t) 30 20 10 0 0 20 40 60 80 100 year (t) (a) Sustainable case R = 1. 5.
122 5 Optimal sequential decisions
Scilab code 10.
// end;
// exec opti_certain_resource.sce
// Optimal catches and stocks
Horizon=100; // time Horizon opt=[];
hopt=[];
r0=0.05;rho=1/(1+r0); P0=10; // initial biomass
// discount rate r0=5% Popt(1)=P0;
for t=1:Horizon
R=1/rho; // limit between sustainable and unsustainable hopt(t)=min(Popt(t),max(0,b(t)*Popt(t)+f(t)));
R=1.04; // unsustainable Popt(t+1)=max(0,R*(Popt(t)-hopt(t)));
R=1.1; // sustainable end
growth=[1.04 1/rho 1.1];
// Graphics
for i=1:3 xset("window",10+i);xbasc();
R=growth(i); plot2d2(0:(Horizon)’,[[hopt; Popt($)] Popt],...
rect=[0,0,Horizon*1.1,max(Popt)*1.2]);
// Construction of b and f through dynamic programming // drawing diamonds, crosses, etc. to identify the curves
b=[]; abcisse=linspace(1,Horizon,20);
b(Horizon+1)=1; plot2d(abcisse,[ hopt(abcisse) Popt(abcisse) ],style=-[3,4]);
for t=Horizon:-1:1 legends([’Catch trajectory’;’Biomass trajectory’],-[3,4],’ur’)
b(t)=R*b(t+1)/(1+ R*b(t+1)); xtitle(’Trajectories under linear growth with...
end; R=’+string(R),’year (t)’,’biomass B(t)’)
f=[]; end
f(Horizon+1)=0;
for t=Horizon:-1:1 //
f(t)=(f(t+1)-log(rho*R))/(1+R*b(t+1));
5.6 A cost-effective approach to CO2 mitigation
Consider a cost effectiveness approach for the mitigation of a global pollutant
already introduced in Sect. 2.3. Here, however, we do not consider the pro-
duction level Q(t) as a state variable, and we have cost function C(t, a) and
baseline emissions Ebau (t) directly dependent upon time t. The problem faced
by a social planner is an optimization problem under constraints.
T −1 It consists
in
minimizing4 the discounted intertemporal abatement cost t=t0 ρt C t, a(t) ,
where ρ stands for the discount factor, while achieving the concentration tol-
erable window M (T ) ≤ M . The problem can be written
−1
T
inf ρt C t, a(t) , (5.25)
a(t0 ),a(t0 +1),..,a(T −1)
t=t0
under the dynamic
M (t + 1) = M (t) + αEbau (t) 1 − a(t) − δ(M (t) − M−∞ ) , (5.26)
and constraint
M (T ) ≤ M . (5.27)
4
This differs from the general utility maximization approach followed thus far in
the book.
5.6 A cost-effective approach to CO2 mitigation 123
We denote by a (t0 ), a (t0 + 1), .., a (T − 1) an effective optimal solution
of this problem whenever it exists. We assume that bau emissions increase
with time, namely, when Ebau is regular enough
dEbau (t)
>0. (5.28)
dt
For the sake of simplicity, we assume that the abatement costs C(t, a) are
linear with respect to abatement rate a in the sense that
C(t, a) = c(t)a . (5.29)
We do not specify the marginal cost function, allowing again for non linear
processes. We just assume that the abatement cost C(t, a) increases with a
which implies
∂C(t, a)
= c(t) > 0 . (5.30)
∂a
Furthermore, following for instance [7], we assume that growth lowers marginal
abatement costs. This means that the availability and costs of technologies
for fuel switching improve with growth. Thus if the marginal abatement cost
c(·) is regular enough, it decreases with time in the sense
∂ 2 C(t, a) dc(t)
= <0. (5.31)
∂t∂a dt
As a result, the costs of reducing a ton of carbon decline.
Using backward dynamic programming equation (5.16), the optimal and
feasible solutions of the cost-effectiveness problem can be computed explicitly
as in [6]. However, let us mention that the proofs are not obvious and require
the use of a generalized gradient. Indeed, the value function and feedback
controls display some non smooth shapes because of kink solutions and active
constraints. Numerical solutions are displayed in Fig. 5.3 and can also be
obtained using any scientific software with optimizing routines.
As explained in detail in Sect. 4.6 of Chap. 4, a viability result brings the
following maximal concentration values to light:
M (t) := (M − M∞ )(1 − δ)t−T + M∞ . (5.32)
It turns out that an optimal cost-effective policy exists if and only if the
initial concentration M0 is smaller than M (t0 ). In this case, the whole abate-
ment rates sequence a(t0 ), a(t0 + 1), . . . , a(T − 1) is effective if and only if
associated concentrations M (t) remain lower than M (t).
Now, under the previous existence and effectiveness assumption, we obtain
the optimal policy in terms of feedback depending on the current state M of
the system. A proof based on Bellman dynamic programming under constraint
can be found in [6].
124 5 Optimal sequential decisions
Concentrations (ppm) with sigmoid emission function
1200
baseline
1100 tolerable concentration (target 550)
target 450
1000 target 550
target 650
900
800
700
600
500
400
300
2000 2020 2040 2060 2080 2100 2120
(a) Baseline M bau (t), optimal M (t) and tolerable M (t) concentrations for
different target M of 450, 550 and 650 ppm.
Concentrations (ppm) with linear emission function, δ varies
1200
δ 0.002
1100 δ 0.01
δ 0.017
1000
900
800
700
600
500
400
300
1980 2000 2020 2040 2060 2080 2100 2120
(b) Cost-effective concentrations with a 550 ppm target. The rate of removal
δ varies.
Costs in percent of GDP
0.08
0.06
0.04
0.02
0
2000 2010 2020 2030 2040 2050 2060 2070 2080
(c) Optimal cost
Fig. 5.3. Cost-effective concentration trajectories M (t) over the time window
[2000, 2120]. The bau emission function is sigmoid and the optimal concentrations
are plotted for different concentration targets. The baseline concentrations M bau (t),
and the tolerable concentrations M (t) for a 550 ppm target are also shown.
5.7 Discount factor and extraction path of an open pit mine 125
Result 5.9 Consider a tolerable initial situation M (t0 ) ≤ M (t0 ). If assump-
tions for emissions and cost functions (5.28) and (5.31) hold true, then the
optimal effective mitigation policy is defined by the feedback abatement
(1 − δ)(M − M (t)) + Ebau (t)
a (t, M ) = max 0, .
Ebau (t)
Let us point out that abatement a (t, M ) reduces to zero when condi-
the
tion (1 − δ) M − M (t) + Ebau (t) is negative which corresponds to the case
where the violation of the tolerable threshold M (t) is not at risk even with
bau emissions. We also emphasize that the case of total abatement where
a (t, M ) = 1 occurs when the current concentration M coincides with maxi-
mal tolerable concentration M (t).
Using the optimal feedback abatement above, we obtain the following
monotonicity result which favors a non precautionary policy in the sense that
the reduction of emissions is more intensive at the end of period than at the
beginning.
Result 5.10 Consider a tolerable situation M (t0 ) ≤ M (t0 ). If assumptions
for emissions and cost functions (5.28) and (5.31) hold true, then the optimal
abatement rates sequence a (t) = a (t, M (t)) is increasing with time in the
sense that
a (t0 ) ≤ a (t0 + 1) ≤ · · · ≤ a (T − 1) .
At this stage, let us point out that the previous qualitative results depend
on neither the discount factor ρ ≤ 1 nor the specific form of the emission
and marginal abatement cost functions. This fact emphasizes the generality
of the assertions. In other words, only a change in the described behavior of
the emission function or the use of a non linear cost function could justify
another abatement decision profile on the grounds of this simple optimality
model.
5.7 Discount factor and extraction path of an open pit
mine
Consider an open pit mine supposed to be made of blocks of ore with dif-
ferent values [11]. Each block is a two-dimensional rectangle identified by its
horizontal position i ∈ {1, . . . , N } and by its vertical position j ∈ {1, . . . , H}
(see Fig. 5.4). In the sequel, it will also be convenient to see the mine as a
collection of columns indexed by i ∈ {1, . . . , N }, each column containing H
blocks.
We assume that blocks are extracted sequentially under the following hy-
pothesis:
• it takes one time unit to extract one block;
. . . T . . • a retirement option is available where no block is extracted. the state of the mine is a profile x(t) = x1 (t). . . The initial profile is x(0) = (1. due to physical requirements. . N } (see Fig. due to physical requirements. . xN (t) ∈ X = RN where xi (t) ∈ {1. States and admissible states Denote discrete time by t = 0. An admissible profile is one that respects local angular constraints at each point. • a block cannot be extracted if the slope made with one of its two neighbors is too high.4). A state x = (x1 . . .4.j) H Depth Fig. H + 1} is the vertical position of the top block with horizontal position i ∈ {1. At time t. where an upper bound for the number of extraction steps is obviously the number N ×H of blocks (it is in fact strictly lower due to slope constraints). . . . . 1. 1. . .126 5 Optimal sequential decisions 1 2 3 j N Columns 1 2 Block i (i. . . H + 1. . . . An extraction profile in an open pit mine • only blocks at the surface may be extracted. H + 1). . 1) while the mine is totally exhausted in state x = (H + 1. xN ) is said to be admissible if the slope constraints are respected in the sense that . . 5. 5. . . . . .
. . H + 1}N the set of admissible states satisfying the above slope constraints (5. At time t. It is assumed that the value of blocks differs in altitude and column because richness of the mine is not uniform among the zones as well as costs of extraction. Indeed. 5. N + 1 = 0. 5. . Thus a decision u is an element of the set B = {1. and extracting xu(t) (t) yields the value R xu(t) (t). u) = (5. xN (t) ) becomes ) xj (t) − 1 if j = u(t) xj (t + 1) = xj (t) else. N + 1} ⊂ U = R. while all other top blocks remain. Of course. N Denote by A ⊂ {1. then x(t + 1) = x(t) and the profile does not change. . In other words. . there is no corresponding block and the following notation (t) = xN +1 (t) is meaningless. . For instance Figs. or the retirement option that we shall identify with a column N + 1. . the dynamics is given by x(t + 1) = F (x.33) ⎪ ⎪ ⎪ ⎩ x = 1 or 2 (border slope). . In case of retirement option u(t) = N + 1. . not all decisions u(t) = j are possible either because there are no blocks left in column j (xj = H + 1) or because of slope constraints. .5 (a) and (b) display high value levels in darker (black and red) blocks. . . the 5 When u(t) = N + 1.7 Discount factor and extraction path of an open pit mine 127 ⎧ ⎪ ⎪ x1 = 1 or 2 (border slope) ⎪ ⎨ |xi+1 − xi | ≤ 1 . N +1) = 0 when the retirement option is selected. . . . . . . j). . for i = 1.33). the corresponding block is extracted and the profile x(t) = x1 (t). With discounting 0 < ρ < 1. N } whose top block will be extracted. N. . N } is chosen at the surface of the open pit mine. but this is without incidence since the value xu(t) R xN +1 (t). the top block of column j is no longer at altitude xj (t) but at xj (t)−1. . . N } Fj (x. Controlled dynamics A decision is the selection of a column in {1. Intertemporal profit maximization The optimal mining problem consists in finding a sequence of admissible blocks which maximizes an intertemporal discounted extraction profit. . if a column u(t) ∈ {1. . The net value a each block is denoted by R(i. . N − 1 (5. . Selecting a square u(t) ∈ B at the 5 the corresponding block at depth surface of the open pit mine. By convention R(i.34) xj if j = u or j = N + 1 . . u(t) . u) where ) xj − 1 if j = u ∈ {1. . .
128 5 Optimal sequential decisions .
35) is solved by a numerical dynamic pro- gramming corresponding8 to Scilab codes 11-12.35) u(0). . u) − ΨA F (x.u(T −1) t=0 Dynamic programming equation The value function V (t. The high preference for present neglects potential use of the mine at stronger depths while a com- plete admissible exploitation occurs with a more important account of future incomes through a larger discount factor. u)) = 0 if F (x..5 exhibit optimal extraction mine profiles for t = 1. 2} and supi=2. let us introduce the map- ping x = (x1 .N |yi | ≤ 1.95. card(A) ≤ 2 × 3N −1 and the dynamic programming algorithm will be released with the new state y = (y1 . This is how we capture the fact that a decision u is admissible. . However. Let x ∈ A and y = ϕ(x). u)) = −∞ if F (x. . .33). Figs. u) ∈ A. . yN ) ∈ {1. 8 However. u(t) .. u) ∈ A. . 0. . 2} × {−1. y necessar- ily satisfies y1 ∈ {1. . t = 18 and final time for two discount values. x) = 0 and7 V (t. Notice that the sum is in fact finite. bounded above by the number of blocks. measuring the distance between two subsequent extraction columns. 1}N −1 corresponding to the increments of the state x. x) = max ρt R(xu .. x) solves V (T. Since x satisfies the admissibility condition (5. due to numerical considerations and curse of dimensionality..99.95. 6 If we account for transportation costs... xN ) → ϕ(x) = (x1 .99 leads to a larger exploitation of the mine than a lower ρ = 0. we may subtract to R a term proportional to δ(u(t). while the right one is for ρ = 0. u(t − 1)). to give a flavor of the complexity of the problem. x2 − x1 . while this raises to 1010 000 if we assume that the surface consists of 100 × 100 columns (N = 10 000). . F (x.. 5. Indeed. The left column is for discount factor ρ = 0. (5. It is shown how a large discount factor ρ = 0. Thus. u) . (5. u) + V t. while −ΨA (F (x.. a more parsimonious state is introduced in the Scilab code 11 before applying the dynamic programming algorithm.+∞ optimization problem is supu(·) t=0 ρt R xu(t) (t). . the set A of acceptable states has a cardinal card(A) which is gen- erally much smaller than (H + 1)N . u(t) . .36) u∈B The maximization problem (5. . Hence. xN − xN −1 ). . To see this. we shall rather consider6 −1 T sup ρt R xu(t) (t). notice that 4 columns (N = 4) each consisting of nine blocks (H = 9) give 10 000 states ((H + 1)N = 104 ). 7 We have −ΨA (F (x.
ρ = 0. The darker the zone. The left column is for discount factor ρ = 0.99 0 0 −1 −1 −2 −2 −3 −3 −4 −4 −5 −5 0 2 4 6 8 10 12 0 2 4 6 8 10 12 (a) t = 1.95 (d) t = 18.95 Optimal extraction profile at ultimate time t=12 for discount rate 0. Trajectories are computed with the Scilab codes 11-12. the more valuable. Optimal extraction mine profiles for t = 1.99 Optimal extraction profile at time t=12 for discount rate 0.95 Optimal extraction profile at ultimate time t=30 for discount rate 0.99 Fig. ρ = 0.99 0 0 −1 −1 −2 −2 −3 −3 −4 −4 −5 −5 0 2 4 6 8 10 12 0 2 4 6 8 10 12 (e) t = T .99 0 0 −1 −1 −2 −2 −3 −3 −4 −4 −5 −5 0 2 4 6 8 10 12 0 2 4 6 8 10 12 (c) t = 18.95 (b) t = 1. 5. while the right one is for ρ = 0. t = 18 and final time. ρ = 0.99.5. ρ = 0. ρ = 0.99 Optimal extraction profile at ultimate time t=20 for discount rate 0. .95 Optimal extraction profile at ultimate time t=1 for discount rate 0.95. 5.7 Discount factor and extraction path of an open pit mine 129 Optimal extraction profile at initial time t=1 for discount rate 0.95 (f) t = T . ρ = 0.
. Admissible=Admissible .k)=State(:.. // (s_j-1)=1 or (s_{j+1}-1)=-1.1)=State(:. // extracting block in column j is not admissible.... // Correction for the dynamics Forced_Profiles= mini(HH.NN).. // and s_k \in \{0. // when the last column NN is selected.1)= maxi(1.NN). // Will contain..k-1)+3^{k-1}*State(:. Admissible(:.. approximation of -infinity. // Given a mine profile.1)=s_1 Admissible(:. // to fill in the instantaneous gain matrix.3:$)>0 ) .. starting from the profile p(0)=(0.k-1) ) / 3^{k-1} . // ----------------------------------------. // Dynamics (with a "maxi" because some integers in // An element in column 1<j<NN of AA is one if and only // Integers+1-3^{1} do not correspond to "mine profiles"). the // following extraction rule will always give "mine profiles".1\} // an element in adm_bottom is one if and only if // and y_j = s_j . // Will contain. 3^{1}... // // Extracting block in column 1 is admissible // The initial profile is supposed to be p(0)=(0.1 \in \{-1. Increments(:.1.k)=s_1+s_2*3^{1}+.uu)) *bottom. for each integer z in Integers.. + s_NN*3^{NN-1} adm_bottom=bool2s(Profiles<HH) .uu) . "c" ) . // has value "bottom".1)=State(:.y_NN). // number of states // Since. // Extracting block in column NN is admissible // if and only if p_{NN}=0. State=zeros(MM.* .0. for k=2:NN // An element in column j of admissible is zero remainder= ( Integers-Partial_Integer(:. for each integer z in Integers. // Will contain. for which only the // original top block may be extracted: State(:...1) .. // Each line contains a profile. // ADMISSIBLE INTEGERS // ----------------------------------------- // ----------------------------------------- // LABELLING STATES AND DYNAMICS // Mine profiles are those for which // ----------------------------------------.NN)==0).0. // extracting block in the corresponding column.. Future_Integer=zeros(MM...k)=pmodulo(remainder.uu)= Admissible(:.1\} for j>1... 3) .....0) and // // s(0)=(1..2\} for k \geq 2. // HH \geq p_1 \geq 0. // an element in columns 1 and NN of Admissible is one // State(z.1)-1. Future_Integer(:. // labelled states // we shall not exclude other unrealistic profiles..+s_k*3^{k-1} // Labels of states for which no decision is admissible. // Corresponds to side columns 1 and NN. // State(:.NN). // the image by the dynamics under the control consisting in Admissible(:.2:($-1))=.^{[1:(NN-1)]}] ) . // When the control uu is not admissible. yy= p-[ 0 p(1:($-1)) ] . // ----------------------------------------...1) and z(0)=1+ 3^{1} + .2:($-1))<2 & State(:.. 3^{NN-1} // // Partial_Integer(z.0. endfunction // .* [1 3. such that // 1) z = s_1 + s_2*3^{1} + .1)=bool2s(Profiles(:... // the top block of the column is not at the bottom.NN).. // Extracting block in column j is admissible // a lower aproximation of z in the basis // if and only if s_j < 2 and s_{j+1} > 0. Integers=(1:MM)’ .. Increments=zeros(MM. Partial_Integer(:.. // Dynamics (with a "mini" because some integers in // This trick is harmless and useful // Integers+3^{NN-1} do not correspond to "mine profiles").. // 2) a mine profile p_1. // the sequence y=(y_1. bool2s( State(:.. HH \geq y_1 + . Admissible=zeros(MM.. + y_k \geq 0 for all k MM=3^{NN} .Integers+3^{k-1}-3^{k}) . HH \geq p_NN \geq 0 // that is...p_NN is given by // A block at the bottom cannot be extracted: // p_k = y_1 + .control) is admissible. for each integer z in Integers.. // hence the decision is the retirement option // Dynamics (with a "maxi" because some integers // in Integers+3^{k-1}-3^{k} // do not correspond to "mine profiles") // ----------------------------------------- end // INSTANTANEOUS GAIN // ----------------------------------------- Future_Integer(:. realistic or not. // instant_gain is the richness of the top block of column uu.1)==0).2\} // Each line contains a profile.k)=s_1 + s_2*3^{1} +. // 1. // Extracting block in column j 1<j<NN) is not admissible // if and only if y_j=1 or y_{j+1}=-1 that is. + 3^{NN-1}. // to which corresponds y(0)=(0. // s_j < 2 and s_{j+1} > 0. // Partial_Integer(z.k).1)=s_1 // if and only if the pair (state. Profiles) ) .0)). // is admissible if the slope is not too high. + y_k where y_1= s_1-1 \in \{0.+ s_k*3^{k-1}. extracting one block at the surface // Will contain. for uu=1:NN // FROM PROFILES TO INTEGERS instant_gain(:.. // if and only if // s_{k} + s_{k+1}*3 + .uu). // a sequence s=(s_1.Integers+3^{NN-1}) . forced to be realistic..... function z=profile2integer(p) end // p : profile as a row vector // When the control uu is admissible. Future_Integer(:.Integers+1-3^{1}) .. maxi(1.1)=pmodulo(Integers.0..k)=Partial_Integer(:. // Partial_Integer(z.k)=s_{k} Increments(:. // else it is one.* adm_bottom . Partial_Integer(:.130 5 Optimal sequential decisions Scilab code 11... // // ----------------------------------------- stacksize(2*10^8). 3^{1}) . for each integer z in Integers.NN)= mini(MM.k)= maxi(1. richness(Forced_Profiles(Future_Integer(:.. Stop_Integers=Integers( prod(1-Admissible. + (1-Admissible(:. State(:. ss=yy+1 ..NN)=bool2s(Profiles(:..uu) . uu ).1...."c") ==1 ) .0) // if and only if p_1=0..s_NN) with Profiles= cumsum (Increments .k)-1. // s_1 \in \{1. Partial_Integer=zeros(MM. instant_gain z=sum( ss . instant_gain=zeros(MM.NN).NN).
0.:) 0 0]. time=1. VV(:.. UUopt=(NN+1)*ones(MM.5.uu(t)). Admissible(:.-[0 xx(time. // retire option plot2d2(-0.-[0 xx(time. xpause(400000). xtitle("Optimal extraction profile for discount rate ". endfunction // OPTIMAL TRAJECTORIES // ----------------------------------------.hotcolormap(64)). xset("colormap". xtitle("Optimal extraction profile at ultimate time t=". display_profile(time) xx=zeros(T.-[0 xx(1..:)) .8 Pontryaguin’s maximum principle for the additive case A dual approach to solve intertemporal optimization problems emphasizes the role played by the adjoint state. VV(:.t+1) + discount^t *0] . display_profile(time) vv=0..t)=rhs.[0.. We present this so-called Pontryaguin’s maxi- .plot2d2(-0. xbasc().5]). // When the control uu is not admissible. [lhs. // function []=display_profile(time) loc=[loc. end t=t+1 .t)=lhs. // instantaneous gain and does not modify the state: xset("colormap".-HH-0. if uu(t)<NN+1 then // The value attributed to the value function VV(:. uu(t)=UUopt(zz(t). // Will be in background.5+0:(NN+2).NN+1.T).. zz=zeros(T. end // loc is the usual DP expression.0.. // ----------------------------------------. loc_bottom=mini(VV(:... // xset("window".NN).. // Displays graphics of mine profiles // Adding an extra control/column which provides zero xset("window".5+0:(NN+2).5.5]). time=t. loc=[]..* (discount^t * bottom + loc_bottom) ] . Matplot1(rich_color.hotcolormap(64)).uu(t))=xx(t. VV=zeros(MM.. discount^t * instant_gain(:.NN+1.uu(t)) . uu=(NN+1)*ones(T. t=1 . + (1-Admissible(:. 5. // retire option..8 Pontryaguin’s maximum principle for the additive case 131 Scilab code 12.-HH-0.1).5.-HH-0.uu) + . vv=vv+discount^t*richness(xx(t+1.:) 0 0].5.time) .NN+1.5]) Matplot1(rich_color.uu) .0. +string(discount)) // loc is the DP expression // with both terms at the lowest values.. // Just to to set the frame UUopt(:. VV( Future_Integer(:.0. // when a control is not admissible..-HH-0. last_control=0 ..5..1).0.uu) .5]).:) 0 0].uu)) .rhs]= maxi(loc.[0.:)=zeros(1. // value functions in a matrix // The final value function is zero.NN+1.t)=(NN+1)*ones(Stop_Integers) .:).5. // ----------------------------------------..T).t) xx(t+1.5+0:(NN+2).5+0:(NN+2). // // The value of the mine blocks in color.. // table of colors // DYNAMIC PROGRAMMING ALGORITHM xbasc(). UUopt(Stop_Integers.5]).NN+1."c") .:) 0 0].-HH-0. // end for uu=1:NN // columns 1 to NN selected // halt() loc=[loc.* ( .-[0 xx(t+1.t+1))...t) . // optimal controls in a matrix // while last_control<NN+1 do for t=(T-1):(-1):1 // backward induction zz(t)=profile2integer(xx(t.0. display_profile(time) // initial profile // 5. // DP equation rect=[0. +string(time) +" for discount rate "+string(discount)) // ----------------------------------------. // will contain the vector to be maximized xx(t+1. rect=[0. t+1 ) ) +.uu(t))+1.:)=xx(t. // plot2d2(-0. Lagrangian or Kuhn and Tucker multipliers in optimal control problems. rect=[0.5]). end rect=[0. xx(1.NN+1.NN).1) .plot2d2(-0.-HH-0. last_control=uu(t). // When the control uu is admissible. xbasc()... time=ceil(T/3).
p. Here. The maximum principle is a necessary condition for optimality. We could as well de- duce the principle from the existence of Lagrange multipliers in optimization problems with constraints on RN .11. u) := qi Fi (t.8.14) is the following function10 n H(t.132 5 Optimal sequential decisions mum principle 9 using a Hamiltonian formulation.13. 10 Recall the notations for transpose vectors: if p and q are two column vectors of Rn . the optimality condition is not necessarily a maximum but may be a minimum or neither of both. we basically deduce the maximum principle from the Bellman backward induction equation. u) (5. A. and subtract the in- stantaneous payoff. x. q.38) i=1 = F (t. x. final utility M and dynamic F are continuously differentiable 9 This is an abuse of language. .3 in the Appendix.14) under con- straints (5. x. in the discrete time case.12.37). u) + L(t. simply multiply the dynamics by the adjoint variable (scalar product in dimension more than one). x. The Hamiltonian associated to the maximization problem (5. to form the Hamiltonian. The Hamiltonian conditions involving the so-called optimal adjoint state q (·) together with the optimal state x (·) and decision u (·) are described in the following Proposition. Consider the maximization problem (5. The new variable q is usually called adjoint state. The other way that we have chosen is to apply the Bellman principle in a marginal version as exposed in Proposition 5. called the maximum principle. Definition 5. (5. Proposition 5.1 Hamiltonian formulation without control and state constraints We assume here the absence of control and state constraints: B(t. One proof can be derived from a Lagrangian formulation. q = p q = q p = q. u) q + L(t. Assume that instanta- neous utility L. which is not the case in continuous time.8) without state constraints as in (5. or multi- plier. as is often introduced in the literature. It basically stems from first order optimality conditions under constraints involving first order derivatives. Thus. x. adjoint variable. 5. the scalar product of p and q is denoted indifferently p. The proof can be found in Sect. where denotes the transpose operator.37) The maximum principle may be expressed in a compact manner introducing the so-called Hamiltonian of the problem. Indeed. x) = U = Rp and A(t) = X = Rn . u) .
t = t0 + 1. .13. ∂xi Writing the previous Hamiltonian conditions. ⎪ ⎪ ∂qi ⎪ ⎪ ⎪ ⎨ ∂H qi (t − 1) = t. q (t). called adjoint state. p. we have ⎧ ⎪ ∂H ⎪ ⎪ xi (t + 1) = t. . Assume that there exists an optimal trajectory x (·) such that u t. u (t) . u (t) . we may hope to simulta- neously reveal the optimal state. q (t). . . u (t) . . x (t). . the sequence q (·) defined by . (5. x (t). Let the trajectory x (·). . t = t0 . T − 1 . ⎨ (5. the adjoint state is also related to the Lagrangian multipliers associated with the dynamics seen here as an equality constraint between state trajectory. . u (t) . q (t). . . . for any i = 1. Proposition 5.39) can be equivalently depicted in a more compact form using vectors and transposed as follows ⎧ ⎪ ⎪ ∂H ⎪ ⎪ x (t + 1) = ( ) t. Suppose that the value function V (t. q (t). .2 The adjoint state as a marginal value The adjoint state can be interpreted in terms of prices and marginal value: it appears indeed as the derivative of the value function with respect to the state variable along an optimal trajectory. u (·) ∈ XT +1−t0 × UT −t0 be a solution of the maximization problem (5. (5. . . T − 1 . . . T − 1 . . . . t = t0 . . . . such that. there exists a sequence q (·) = (q (t0 ).8. decisions and adjoints.39) ⎪ ⎪ ∂xi ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ∂H ⎩ 0= t. Then. u (t) .14) is smooth with respect to x. .40) ⎪ ⎪ ∂M ⎩ qi (T − 1) = t. . Conditions (5. .14). x) associated to the maximization problem (5. q (t). n and j = 1. x (t). For this reason the principle proves useful and is applied for the analysis of many optimal control problems. . T − 1. x (t). 5. . ∂uj together with boundary conditions ⎧ ⎪ ⎪ xi (t0 ) = xi0 .20) is unique for all t = t0 . ⎪ ⎪ ∂q ⎪ ⎪ ⎨ ∂H q (t − 1) = ( ) t. q (t). u (t) . q (T − 1)) ∈ XT −t0 . x (t). x (t). x (t) .41) ⎪ ⎪ ∂x ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎩ ∂H 0=( ) t. control trajectory and time. Then. x (t) in (5.8 Pontryaguin’s maximum principle for the additive case 133 in the state variable x. . ∂u 5. Similarly.
x (t + 1) . q (t) = S (t + 1) ∂q ⎪ ⎪ ∂H ⎪ ⎪ t. S (t). T − 1 . (5.. S (t). h (t).. (5. where we ignore the constraints. . x (t + 1) . h (t).42) ∂xi is a solution of (5. Let us handle the “cake-eating” model coping with an exhaustible resource presented at Sect. we write (5.42) equivalently as ∂V q (t) := t + 1. q (t) = q (t − 1) ⎪ ⎪ ∂S ⎪ ⎪ ⎪ ⎪ ∂M ⎩ T. .45) ⎪ ⎪ q (t) = q (t − 1) ⎪ ⎪ ⎪ ⎪ ⎩ ρT L S (T ) = q (T − 1) . S (T ) = q (T − 1) ∂S giving ⎧ t ⎪ ρ L h (t) − q (t) = 0 ⎪ ⎪ ⎪ ⎪ ⎪ ⎨ S (t) − h (t) = S (t + 1) (5. ..134 5 Optimal sequential decisions ∂V qi (t) := t + 1. Thus.1. q) := ρt L(h) + q(S − h) .12. In a more vectorial form. S (t).. t = t0 . From Proposition 5. We define the Hamil- tonian as in (5.44) if there exists an adjoint state trajectory q (·) such that the following conditions are satisfied ⎧ ⎪ ∂H ⎪ ⎪ t.44) h(t0 ).9 Hotelling rule Let us now apply the maximum principle to a simple example. h (·) is the solution of the opti- mization problem (5.38) H(t. h (t). a trajectory S (·). q (t) = 0 ⎪ ⎪ ∂h ⎪ ⎪ ⎪ ⎪ ∂H ⎪ ⎨ t.h(T −1) t=t 0 with dynamics S(t + 1) = S(t) − h(t) and S(t0 ) given.40). h. giving −1 T sup ρt L h(t) + ρT L S(T ) (5. . 2. S.43) ∂x 5.39) and (5. the multiplier q (t) is stationary and we obtain the following interesting result that .
the Hotelling rule is stated as ḣ h =− η . h (t) h Thus. and a decrease in the elasticity of the marginal utility of consumption increases the rate of extraction. writing L h (t + 1) 2 h (t+1) L log = (h)dh L h (t) h (t) L and introducing the elasticity of the marginal utility of consumption hL (h) η(h) := − . the greater the rate of discount ρ. and the optimal extraction h (t) is stricly decreasing with time t if marginal utility L is taken to be stricly decreasing (L stricly concave) and since ρ ≤ 1. we obtain that h (t) = (L )−1 (q (t0 )ρt0 −t ) . Thus the price growth rate coincides with the interest rate: this is the so-called Hotelling rule [9]. (5.47) L h (t) ρ The marginal utility L h (t) is interpreted as the price of the resource at time t. L (h) equation (5. From (5. we observe that the extraction h (t) goes toward zero. that we denote by p(t) := L h (t) .46) We may write the above relation as L h (t + 1) 1 = . we derive that the price of the resource grows as 1 p(t + 1) = (1 + rf )p(t) with rf := −1.47) becomes11 2 h (t+1) η(h) dh = log ρ . Moreover. . When T → +∞ and the marginal utility at zero is infinite L (0) = +∞. ρ where the discount factor ρ is usually related to the interest rate rf through the relation ρ(1 + rf ) = 1. From (5.9 Hotelling rule 135 L h (t) = q (t0 )ρt0 −t . 5.46). Since the stock S (t) rf 11 In continuous time. (5. where rf = − log ρ is the discount rate. the greater the rate of extraction.47).
10 Optimal management of a renewable resource We first present a sustainable exploitation when ρR = 1. 5.. • optimal consumption decreases along time h (t + 1) < h (t). h(t0 ). Consider indeed the same problem but without “in- heritance” value: −1 T sup ρt L h(t) .. However. Hence.h(T −1) t=t0 with dynamic B(t + 1) = R B(t) − h(t) ..10. it also goes down to a limit.136 5 Optimal sequential decisions decreases and is nonnegative.. Then • the rate of return (financial) of the resource is the interest rate. Result 5.2 T −1 sup ρt L h(t) + ρT L B(T ) h(t0 ). we shall verify afterwards that the optimal solution is an interior solution in the sense that . one should be cautious in doing so. T →+∞ T →+∞ Optimal depletion without existence value We have ignored the constraints 0 ≤ h(t) ≤ S(t) above. temporarily ignoring the constraints 0 ≤ h(t) ≤ B(t).h(T −1) t=t 0 The optimality T equations are the same as in (5.1 Sustainable exploitation Let us return to the management problem presented at Sect. giving q (t) = 0 and a contradiction with L h (t) ρ = q (t) = 0 and L > 0 in general.45) except for q (T − 1) = L S (T ) ρ which now would t become q (T − 1) = 0.14 Assume that the concave utility L satisfies L < 0 and the in- terest rate rf is strictly positive. Let us summarize these results as follows. • optimal stock and extraction are exhausted in the long term: lim S (T ) = lim h (T ) = 0 . 5. we see that S (T ) (L )−1 (+∞) = 0. By the equality ρT L (S (T )) = q (t0 ). 2.. We illustrate the maximum ap- proach. then expose the so called fundamental equation of renewable resource... both the extraction h (t) and the stock S (t) go toward zero under reasonable assumptions..
1 of Chap. B) = ρ2 L(B). and strictly concave (L < 0).10. 5. q (0) = ρL B (2) . 3. namely Rh (σ(B). implying that optimal catches are R2 h (0) = h (1) = B0 .1. 3. For the sake of simplicity. 5.10 Optimal management of a renewable resource 137 it satisfies 0 < h (t) < B(t). B. Such equilibrium accounts for the interest rate rf or risk free asset.2 A new bioeconomic equilibrium Following [4]. the growth of the resource g(B). The utility function L is taken to be sufficiently regular (twice continuously differentiable. Since L is a strictly concave function. we consider the par- ticular case of T = 2 periods and we suppose that the discount factor satisfies relation (5. The maximum principle (5.48) Rh (σ(B).23) namely. 2 . L h (0)) = L h (1) = L B (2) . 3 and the rent R in marginal terms. 2 and 0 = q (t)R + ρt L h (t) . for instance). B) + RB (σ(B). This yields q (1) = ρ2 L B (2) . Using the general notations of Sect. B) gB B − σ(B) = (1 + rf ) . q. t = 0. (5. 1 + R + R2 We check that 0 < h (t) < B (t). its derivative is strictly decreasing and one can deduce that we are dealing with stationary optimal consumptions h (0) and h (1). we may derive from the maximum principle at equilibrium a well known relationship displaying a new bioeconomic equilibrium based on a long term steady state. h) = qR(B − h) + ρt L(h) . According to the dynamic equation.6) of Chap. we deduce that B (2) = R B (1)−h (1) = R R B0 −h (0) −h (1) = R R B0 −B (2) −B (2) . t = 1. B) Such equilibrium has to be compared with characterizations of mse or ppe equilibria in Subsect.38) is given by H(t.3. both equal to B (2). The Hamiltonian as in (5. . the sustainable yield σ(B) defined in (3. ρR = 1. 1.39) implies q (1) = ρ2 L B (2) and q (t − 1) = q (t)R. we have M (2. 5.
48).48). A steady state (B . ⎪ ⎨ h = σ(B ) . B ) + l g (B − h ) . B. ⎪ B B Combining the equations yields the desired result (5.. Despite the numerous assumptions underlying such reasoning. In particular. Let us consider the illustrative case where . B(t) + l(t)gB B(t) − h(t) . B(t) + ρT M B(T ) .. h) := qg(B − h) + ρt R(h. h . B(t) − l(t)gB B(t) − h(t) . q. ⎪ ⎨ B(t + 1) = g B(t) − h(t) . B(t) . under the dynamic B(t + 1) = g B(t) − h(t) . ⎪ ⎪ ⎪ ⎪ ⎩ l(t − 1) = ρ RB h(t). Under regularity assumptions on the functions R and g. ⎪ ⎪ ⎪ ⎩ q(t − 1) = q(t)gB B(t) − h(t) + ρt RB h(t). B(t) . B) . Such equilibrium questions the long term sustainability of an optimal man- agement.h(T −1) t=t0 where the discount ρ refers to the interest rate through ρ(1 + rf ) = 1. h(t0 ). Setting l(t) := q(t)ρ−t . It has an interesting economic interpretation. On the left hand side. the maximum prin- ciple reads ⎧ ⎪ ⎪ 0 = −q(t)gB B(t) − h(t) + ρt Rh h(t). B ) − l gB (B − h ) . the conditions become ⎧ ⎪ ⎪ 0 = Rh h(t). ⎪ ⎪ ⎩ l = ρR (h . we consider the dynamic optimization problem T −1 max ρt R h(t). The Hamiltonian is H(t. we may wonder whether this equilibrium can take negative values. ⎪ ⎪ ⎨ B(t + 1) = g B(t) − h(t) .. this equa- tion has been called the fundamental equation of renewable resource..138 5 Optimal sequential decisions To achieve assertion (5. l ) associated with these two dynamics satisfies ⎧ ⎪ ⎪ 0 = Rh (h . the first term gB B − σ(B ) is the marginal productivity of the resource (at equilib- rium) while the second term involving the marginal stock effect measures the marginal value of the stock relative to the marginal value of harvest.
the Green Golden rule value function or Bellman function V (t. such assertions stress the fact that major economic rationales exist for non conservation and non sustainability of renewable resources. the long term equilibrium satisfies R (R − bB )2 1 + rf = 2 = . x(T ) . both the dynamic programming and maximum principle apply with major simplifications. B) = p . x) := sup M T. Thus. B) = 0 and Rh (h. x) is given by (5. this framework turns out to be a particular instance of the additive case of Sect. 5.8). Result 5. x) at time t and for state x represents the optimal value of the criterion over T − t remaining periods. • rent is of the form R(h. namely V (t.49) x(·).u(·) ∈T ad (t. given that the state of the system at time t is x.11 The Green Golden rule approach As already been pointed out in the introduction. it constitutes a dictatorship of the future. Indeed. Again. by focusing on the decisions that favor the final payoff. the unique solution B is a negative biomass. It has been already shown that R 1 gB (B) = and σ(B) = B 1 − . If Rρ ≤ 1 then extinction is optimal in the sense that the long term equilibrium is negative B ≤ 0. Thus. 5. B R 1+b R − bB Thus. . this approach promotes the distant future. For the management of nat- ural resources. 5. (1 + bB)2 R − bB Moreover we obtain RB (h. Again. In this sense. it turns out that such an approach may reduce consumption to zero along time and promote the stock resource. the Green Golden criterion sheds interesting light on the sustainability issue from the point of view of the future preferences. B) = ph − c.2 without instantaneous payoff. whenever Rρ ≤ 1.11 The Green Golden rule approach 139 • the resource dynamic is of the Beverton-Holt type g(B) = RB 1+bB .15 Consider the Beverton-Holt dynamics and fixed harvesting costs.x) where T ad (t. (5. From the methodological viewpoint. More general conditions for “optimal extinction” are exposed in [3].
(5. 0 ≤ h(t) ≤ B(t) . let us examine an application of the Green Golden rule for the following renewable resource management problem B(t + 1) = g B(t) − h(t) . The value function defined by (5.x) where Viab(t) is again given by the backward induction (5. We describe it in the case with the state constraint involving viability conditions. the value function and optimal feedbacks are given by V (t. Indeed. etc.50) is over viable controls in Bviab (t. x) = M (T.2. The case where g(B) = B stands for the ex- haustible issue. x) as in (5.. B) = 0 . x) which achieves the maxi- mum in equation (5. Result 5. x. 5. F (t.. g (T −t) (B) . Bellman induction optimization in the Green Golden rule case also reveals relevant feedback controls. B(T ) . with criterion sup M T.18) and where the supremum in (5. u∈B viab (t.50). . where t runs from T − 1 down to t0 . 5.19).50) for at least one decision.140 5 Optimal sequential decisions An induction equation appears for the Green Golden rule value function V (t. (5. h(t0 ). ∀x ∈ Viab(t) . ∀x ∈ Viab(T ) .h(T −1) where M is some payoff function with respect to resource state B and g represents the resource dynamic. x).). then u (t.. the optimal catches are reduced to zero. B) = M T. u (t. x) . As in the additive case.51) i times # $! " where g (B) = g(g(· · · g(B) · · · )) denotes the i-th composition of function g (i) (g (1) = g. assuming the additional hypothesis that the supremum is achieved in (5. u) . The proof of the following assertion is a particular instance of the additive case of Sect.49) is the solution of the following dy- namic programming equation (or Bellman equation).16 Assume that the final payoff M and resource productivity g are increasing functions. x) a value u ∈ B(t.50) ⎪ ⎩ V (t.12 Where conservation is optimal Now. x) = sup V t + 1. Then. if we denote by u (t. g (2) = g ◦ g.. under general and simple assumptions. x) is an optimal feedback for the optimal control problem. ⎧ ⎪ ⎨ V (T. It can be proved that.
5.13 Chichilnisky approach for exhaustible resources 141
Notice that such an optimal viable rule provides zero extraction or catches
along time and thus favors the resource which takes its whole value from the
final payoff. In this sense, such an approach promotes ecological and envi-
ronmental dimensions. Although such a Green Golden rule solution displays
intergenerational equity since depletion is stationary along time and favors
the resource, it is not a satisfying solution for sustainability as soon as con-
sumption is reduced to zero along the generations.
Why is it so mathematically? From (5.50), the inductive relation (5.51)
holds true at final time T . Assume now that the relation (5.51) is satisfied at
time t + 1. From dynamic programming equation (5.50), we infer that
V (t, B) = sup V t + 1, g(B − h)
0≤h≤B
= sup ρT M T, g T −t−1 g(B − h) .
0≤h≤B
Since payoff M and dynamic g increase with resource B, we deduce that
the optimal feedback control is given by its lower admissibility boundary
u (t, B) = 0 and consequently
V (t, B) = M T, g T −t−1 g(B) = M T, g T −t (B) ,
which is the desired statement.
5.13 Chichilnisky approach for exhaustible resources
The optimality problem proposed by Chichilnisky to achieve sustainability
relies on a mix of the Green Golden rule and discounted approaches. The
basic idea is to exhibit a trade-off between preferences for the future and
the resource underlying the Green Golden approach and preferences for the
present and consumption generated by the discounted utility criterion. The
general problem of Chichilnisky performance can be formulated as a specific
case of additive performance with a scrap payoff where the discount is time
dependent. We focus here on the case of exhaustible resource S(t + 1) =
S(t) − h(t) as in Sect. 2.1 with criterion
T
−1
max θ ρt L h(t) + (1 − θ)L S(T ) . (5.52)
h(·)
t=t0
Here, θ ∈ [0, 1] stands for the coefficient of present preference. Note that the
extreme case where θ = 1 corresponds to the usual sum of discounted utility of
consumptions, while θ = 0 is the Green Golden rule payoff. Hence comparison
of the three contexts can be achieved only by changing θ, the coefficient of
present preference. Applying dynamic programming, the following assertions
can be proved.
142 5 Optimal sequential decisions
Result 5.17 Using dynamic programming, one can prove by induction that
V (t, S) = ρ(t)b(t)η−1 S η ,
(5.53)
h (t, S) = b(t)S ,
where b(·) is the solution of backward induction
ρ(t + 1)μ b(t + 1)
b(t) = , b(T ) = 1 ,
ρ(t)μ + ρ(t + 1)μ b(t + 1)
)
1 θρt if t = t0 , . . . , T − 1 ,
with μ = and ρ(t) =
η−1 (1 − θ) if t = T .
At final time t = T , the relation holds true as
V (T, S) = (1 − θ)S η = ρ(T )b(T )η−1 S η .
Now, assume that (5.53) is satisfied at time t + 1. By dynamic programming
equation (5.16), the value function is the solution of the backward induction
. /
V (t, S) = sup θρt hη + V (t + 1, S − h) ,
0≤h≤S . /
= sup θρt hη + ρ(t + 1)b(t + 1)η−1 (S − h)η .
0≤h≤S
Applying first order optimality conditions, we deduce that
ρt θ(h )η−1 = ρ(t + 1)b(t + 1)η−1 (S − h )η−1 .
Consequently, the optimal feedback is linear in S,
ρ(t + 1)μ b(t + 1)
h (t, S) = S,
ρ(t)μ
+ ρ(t + 1)μ b(t + 1)
which is similar to the desired result. Inserting the optimal control h (t, S)
into the Bellman relation, it can be claimed that V (t, S) = ρ(t)b(t)η−1 S η .
Indeed, we derive that for any time t = t0 , . . . , T
V (t, S) = θρt h (t, S)η + V (t + 1, S − h (t, S))
= θρt(b(t)S)η + ρ(t + 1)b(t + 1)η−1 (S − b(t)S)η
= S η ρ(t)b(t)η + ρ(t + 1)b(t + 1)η−1 (1 − b(t))η
ρ(t)ρ(t + 1)μη b(t + 1)η + ρ(t + 1)b(t + 1)η−1 ρ(t)μη
= Sη η
(ρ(t)μ + ρ(t + 1)μ b(t + 1))
1+μ
ρ(t)ρ(t + 1) b(t + 1) + ρ(t + 1)b(t + 1)η−1 ρ(t)1+μ
η
= Sη η
(ρ(t)μ + ρ(t + 1)μ b(t + 1))
ρ(t + 1) b(t + 1) + ρ(t)μ
μ
= S η ρ(t)ρ(t + 1)b(t + 1)η−1 η
(ρ(t)μ + ρ(t + 1)μ b(t + 1))
μ η−1
(ρ(t + 1) b(t + 1))
= S η ρ(t) η−1
(ρ(t)μ + ρ(t + 1)μ b(t + 1))
η η−1
= S ρ(t)b(t) .
5.13 Chichilnisky approach for exhaustible resources 143
It is worth pointing out that the feedback control h(t, S) is smaller than the
stock S since coefficient b(t) remains smaller than 1.
By stock dynamics S (s + 1) = S (s) − h (s, S (s)) as in (5.21), we get
the optimal paths in open-loop terms from initial time t0 . The behavior of
optimal consumption h (t) = h (t, S (t)) can be described as follows:
h (t + 1) b(t + 1)S (t + 1)
=
h (t) b(t)S (t)
b(t + 1)S (t)(1 − b(t))
=
b(t)S (t)
ρ(t)μ
= b(t + 1)
ρ(t+ 1)μ b(t + 1)
μ
ρ(t)
= .
ρ(t + 1)
Hence, we recover the discounted case for periods before final time since op-
timal consumptions for t = t0 , . . . , T − 1 change at a constant rate
h (t + 1) = τ h (t) with τ = ρ−μ for t = t0 , . . . , T − 1 .
Now, let us compute the final resource level S (T ) generated by optimal
extractions h (t). From Result 5.17, it can be claimed by induction that
−1
T
S (T ) = S0 (1 − b(t)) .
t=t0
μ
ρ(t)
Since 1 − b(t) = b(t) 1
b(t) − 1 and 1
b(t) = ρ(t+1)
1
b(t+1) + 1, we deduce
that μ
ρ(t) b(t)
1 − b(t) = .
ρ(t + 1) b(t + 1)
Consequently,
−1
T μ
ρ(t0 ) b(t0 )
(1 − b(t)) = .
t=t0
ρ(T ) b(T )
μ
1 ρ(t) 1
Moreover, by virtue of the relation b(t) = ρ(t+1) b(t+1) +1 and by b(T ) = 1,
we also obtain that
T μ
1 ρ(t0 )
= .
b(t0 ) t=t ρ(t)
0
Combining these results, we write
−1
T μ &
T μ '−1 & T
μ '−1
ρ(t0 ) ρ(t0 ) ρ(T )
(1 − b(t) = = .
t=t0
ρ(T ) t=t0
ρ(t) t=t0
ρ(t)
144 5 Optimal sequential decisions
Therefore, the optimal final resource state is characterized by
& T μ '−1
ρ(T )
S (T ) = S0 .
t=t0
ρ(t)
Replacing the discount factors ρ(t) by their specific value for the Chichilnisky
performance gives
& μ T
−1
'−1 μ −μ(T −t0 ) −1
1−θ −μt 1−θ ρ −1
S (T ) = S0 1+ ρ = S0 1 + .
θ t=t0
θ ρ−μ − 1
Therefore, whenever the discount factor is strictly smaller than one ρ < 1,
the Chichilnisky criterion exhibits a guaranteed resource S (+∞) > 0 to-
gether with a decreasing consumption that vanishes with the time horizon.
Result 5.18 Assume the utility function is isoelastic in the sense that L(h) =
hη with 0 < η < 1. If the discount factor is strictly smaller than unity (ρ <
1) and the present preference coefficient is strictly positive, θ > 0, then the
Chichilnisky criterion yields
μ −1
1−θ 1
• guaranteed stock: lim S (T ) = S0 1 +
> 0;
T →+∞ θ 1 − ρ−μ
• consumption decreasing toward zero: h (t+1) < h (t) and lim h (T ) = 0.
T →+∞
At this stage, a comparison can be achieved between the DU (discounted),
GGR (Green Golden rule) and CHI (Chichilnisky) approaches as shown by
Fig. 5.6. Each criterion can be characterized through the parameter θ. It
is worth noting that for DU (θ = 1) and CHI frameworks, consumptions
h (t) are decreasing toward 0 while it remains zero along time for GGR (θ =
0). This observation emphasizes the unsustainable feature of such optimal
solutions. However, as far as resource S(t) is concerned, it turns out that both
CHI and GGR provide conservation of the resource. In this sense, the CHI
framework represents an interesting trade-off for sustainability as it allows
both for consumption and conservation.
5.14 The “maximin” approach
As already pointed out in Subsect. 5.1.2, the maximin or Rawls criterion sheds
an interesting light on the sustainability issue. Indeed, by focusing on the
worst output of decisions along generations and time, this approach promotes
more intergenerational equity than the additive criterion which often yields
strong preferences for the present. From the methodological point of view,
this framework turns out to be more complicated to handle because a “max”
5.14 The “maximin” approach 145
green golden rule
Chichilnisky
2.0
discounted
1.5
Extraction h(t)
1.0
0.5
0.0
2 4 6 8 10 12 14 16 18
time t
12
10
8
Resource S(t)
6
4
2 discounted
green golden rule
Chichilnisky
0
2 4 6 8 10 12 14 16 18 20
time t
Fig. 5.6. A comparison between discounted (3, θ = 1), Green Golden rule (⊕, θ =
0) and Chichilnisky (, θ = 0.2) approaches for optimal stock S(t) and consumption
h(t). Here the utility parameter is η = 0.5, the discount factor is ρ = 0.9 and the
final horizon is T = 20.
operator is less regular than an addition (in an algebraic sense that we do
not treat here). For instance, the maximum principle no longer holds for the
maximin framework, at least in simple formulations. However, the dynamic
programming principle and Bellman equation still hold true, although some
adaptations are needed. Strong links between maximin and viability or weak
invariance approaches are worth being outlined.
5.14.1 The optimization problem
In this section, we focus on the maximization of the worst result along time
of an instantaneous payoff in the finite horizon (T < +∞)
π (t0 , x0 ) = sup
min L t, x(t), u(t) (5.54)
t=t0 ,...,T −1
x(·),u(·) ∈T ad (t0 ,x0 )
A. T } × X → R. for x ∈ Viab(T ) = A(T ).146 5 Optimal sequential decisions and under feasibility constraints (5.3 Maximin dynamic programming equation As in the additive case of Sect. this separation has to be adapted to the maximin case.20. . u) = M T.56) is the solu- tion of the following backward dynamic programming equation (or Bellman equation). a backward induction equation appears for the maximin value function V (t.1)-(5. 5.. (5. by changing T in T + 1 and defining L(T. x.T −1 x(·).2)-(5. x0 ) .20 can be found in Sect.14. V (T.2 Maximin value function Again. x) := +∞ . We can also address the final payoff case with π x(·). The proof of the following Proposition 5. u(s) . where t runs from T − 1 down to t0 .8). . For the maximization problem (5. we define a function V : {t0 .. x0 ) = π (t0 . . x(t).. Definition 5. M T. x) when we note that the maximization operation can again be split up into two parts.T −1 Actually.2. . ..54) refers to the particular value V (t0 . x . the minimax with final payoff may be interpreted as one without.x) with the convention that.u(·) ∈T ad (t. u(t) . x(T ) . The value function defined by (5. named maximin value function or Bellman function as follows: for t = t0 .. but on a longer time horizon. T − 1. t=t0 .56) Therefore. . the maximin value function V at time t and for state x represents the optimal value of the criterion over T − t periods. u(·) = min min L t. given the initial state x0 . . . However.. the optimal sequential decision prob- lem (5..1) and under feasibility constraints (5. x0 ) of the Bellman function: V (t0 . Proposition 5. (5. for x ∈ Viab(t) V (t. x(s).3 in the Appendix.19. x) := sup min L s.. .54) with dynamics (5.2). given that the state at time t is x.55) s=t.55)–(5.14. 5. 5.
2. ⎨ ⎪ ⎩ V (t.4 Optimal feedback As in the additive case. . In particular. x) a value u ∈ B(t.14 The “maximin” approach 147 ⎧ ⎪ V (T. it turns out that the max- imin value function corresponds to a static optimality problem involving the viability kernel. . x. Bellman induction optimization (5. 5. The proof of the following Proposition 5.59) 5. u).19). u (·) for the maximization problem (5.x) where the maximin value function V is given in (5.58) u∈Bviab (t.5 Are maximin and viability approaches equivalent? Here we examine the links between the maximin framework and viability ap- proaches. . Such a connection has already been emphasized in [12] in the context of exhaustible resource management. V t + 1.14. x) = +∞ and then apply a backward induction. x) is an optimal feedback for the optimal control problem in the following sense.54) is given for any t = t0 . u∈Bviab (t. Indeed. F (t. We need to consider a specific viability kernel associated with the additional constraint requiring a guaranteed payoff L. to compute the maximin value V (t. x (t) . x) = sup min L(t. x (t). Then an optimal trajectory x (·). u) . V t + 1.x) (5. A. Thus.21 follows from the proof of Proposition 5.18) and where the supremum in (5. (5.57) in the maximin case also reveals relevant feedback controls. x.57) for at least one decision.14.20 in Sect. x) as in (5. x. x) = +∞ . For any time t and state x. . Proposition 5. as in the additive case of Sect. x. u) . T − 1 by x (t + 1) = F t.55). u). u (t) . we begin with final payoff V (T.57) is over viable controls in Bviab (t.57) where Viab(t) is again given by the backward induction (5. then u (t. namely: . x) which achieves the maximum in equation (5. assume the existence of the following maximin feedback decision u (t. if we denote by u (t. ∀x ∈ Viab(t) . u (t) = u t. 5. F (t.57). x). assuming the additional hypothesis that the supremum is achieved in (5. x) ∈ arg max min L(t. 5. ∀x ∈ Viab(T ) .21. (5.3 in the Appendix.
148 5 Optimal sequential decisions L t.. The main result is a character- ization of the maximin value function V (t.. 0 ≤ h(t) ≤ S(t) . u(t) ≥ L ...22 can be found in in Sect. Assume that it is satisfied at time t + 1.. the above formula holds true at final time T . h(t0 ). Proposition 5. . x(s).15 Maximin for an exhaustible resource Consider the exhaustible resource management S(t + 1) = S(t) − h(t) . We shall show that the value function and optimal feedbacks are given by S S V (t. the interest of the viable control framework to deal with equity issues and. T −t T −t From (5. S(t0 ) = S0 . The maximin value function V in (5.22. L )} . u(s) ∈ B(s. T ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎨ x(s + 1) = F s. x(T ) final term and. x(s)) ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎩ L(s.3 in the Appendix.T −1 where L is an increasing utility function.57). S) = +∞ since there is no M T. . h (t.. the viability property related to the maximin approach. . on the other hand. Such a result points out. The proof of the following Proposition 5. . 5. From dynamic programming equation (5. we introduce the viability kernel ⎧ ⎫ ⎪ ∃ x(·).56). . thus. on the one hand. x) = sup{L ∈ R | x ∈ Viab(t. A. u(·) such that ∀s = t. Hence. x(s).. we have V (T. T − 1 . t = t0 . u(s) ⎪ ⎬ Viab(t. in the maximin perspective sup min L h(t) . x(t).55) satisfies: V (t. x) through a static optimization problem involving the viability kernel. L ) := x ∈ X x(t) = x ⎪ ⎪ x(s) ∈ A(s). . . u(s)) ≥ L ⎭ which depends on the guaranteed payoff L . we infer that . S) = L . S) = .h(T −1) t=t0 . .
S) = sup min L(h). h (t) = h t. sup L(h) T − t − 1 0≤h≤ S T −t ≤h≤S S 4 S− S 3 T −t T −t S = max L( T −t−1 ). 5. S and that the optimal feedback control is unique and given by h (t. S−h = max sup L . T T − t0 Such a maximin solution promotes intergenerational equity in the sense that depletion h (t) is stationary.15 Maximin for an exhaustible resource 149 S−h V (t. Result 5. Therefore the solution at time t0 is given by S0 V (t0 . L( T −t ) = L( TS−t ) . T −t−1 T −t ≤h≤S S 3 sup0≤h≤ S min L(h). S) = T −t . Then the maximin optimal extraction path h (·) is stationary and S0 (T − t + t0 ) S0 S (t) = . S (t) = . The “cake” S0 is shared in equal parts eaten along time. . S0 ) = L T − t0 and we deduce the optimal path as follows.23 Assume that the instantaneous payoff L is increasing. L( ) . L( TS−h −t−1 ) T −t . L( ) 0≤h≤S T −t−1 S−h = max sup min L(h).
Review of Economic Studies. Wiley. [10] M. Conroy. Available on. Goulder and K. Athena Scientific. 2007. Byron. Millennium Ecosystem Assessment. 1998. D. Martinet and L. 68:17–24. Hotelling. Conrad and C. Clark.aspx. Economic Theory and Sustainability. Optimal timing of co2 mitiga- tion policies for a cost-effectiveness model. H. Weitzman. Cambridge University Press. 1999. Nichols. J. Grossman. Optimization over Time: Dynamic Programming and Stochastic Control. Doyen. volume 1. Resource and Energy Economics. Columbia University Press. New York. [7] L. Valuing the Future. F. and M. W. Doyen. [8] G. Kot. [15] P. and P. Heal. Belmont. Conrad. quantities. . Dumas. Sustainable management of an exhaustible resource: a viable control approach. Clark. 39:1–38. [6] L. Journal of Environmental Economics and Management. Prices vs. 2002. Dynamic Programming and Optimal Control. Mathematics and Computer Modeling. Natural Resource Economics. 1990. Trans- actions.17–39. John Wiley & Sons. Bertsekas. second edition. Mathematical Bioeconomics. Cambridge. 1987. Optimum design of open-pit mines. 1965.org/en/index. second edition. Lerchs and I. Journal of Political Economy. [12] V. Academic Press. New York. 2000. CIM. 2000. [14] M. [9] H. October 1974. Ambrosi. in press. P. 39:137–175. Optimal co2 abatement in the presence of induced technical change. [5] J. Whittle. 41(4):477–491. [11] H. 29(1):p. M. april 1931.maweb.References [1] D. Cambridge University Press. [13] MEA. The economics of exhaustible resources. New York. Elements of Mathematical Ecology. [4] J. 2005. Mathai. 1982. [2] K. [3] C. Volumes 1 and 2. W. 2001. Resource Economics. Cambridge University Press. L. M. P. Analysis and Management of Animal Populations. Massachusets. J.
On the other hand. In the framework of dynamic decision-making under uncertainty. multiprior models [7] may appear relevant alternatives for the . We can distinguish several kinds of uncertainty. stock evaluations will remain poor. Such uncertainties are involved. which can be useful when the probability of an outcome is known from experience and statistics. the methods of decision-making under uncertainty are useful [11]. For instance. by dealing with ambiguity. Decision makers have to take sequential decisions without precise knowl- edge about phenomena that can affect the system state and evolution [3. First. We simply underline here that such irreducible uncertainties open the way for controversies. occur much later than the date at which decisions must be taken. 15]. as for example with scenarios such as the global economic growth rate or demographic evolution along with the uncon- trollability of catches for harvesting of renewable resources. to name a few. policy makers may refer to risk assessment. The general method is stochastic control [1. although it can be reduced by it. the usual approach applied is the expected or mean value of utility or cost-benefits. 2. Errors in measurement and data also constitute sources of uncertainty. To deal with risk. although recognizing this problem in no way negates the necessity of taking decisions. 4]. there is risk. In this context. beliefs. 14]. Uncertainties also occur at more anthropic stages.6 Sequential decisions under uncertainty The issue of uncertainty is fundamental in environmental management prob- lems. which covers events with known probabilities. irreducible scientific uncertainties. for instance. Most precaution and environmental problems involve ambiguity in the sense of con- troversies. By fundamental. there are cases presenting ambiguity or “Knightian” uncertainty [9] with unknown probability or with no probability at all. we mean that the issue of uncertainty is inherent to envi- ronmental problems in the sense that it cannot be easily removed by scientific investigation. For fish harvest- ing. the scientific resolution of uncertainty for global warming will. or the natural removal rate in the carbon cycle. In this sense. 12. if it is ever achieved. in natural mechanisms in- cluding demographic or environmental stochasticity for population dynamics [10.
we shall focus on state feedback policies. This context makes it possible to treat robust and stochastic approaches simultaneously. The notion of dynamics introduced in Chap. trajectories are no longer unique in contrast to the deterministic case. Since states and controls are now uncertain. but they are now dependent on external variables (disturbance. while minimax operations lead to ro- bust control. The chapter is organized as follows. Assuming perfect infor- mation. For instance. 2 is extended to the uncertain case in Sect. we consider control dynamical systems with perturbations. due to uncertain- ties.1 Uncertain dynamic control system Now. the interest of dynamic programming is emphasized. Another difficulty lies in optimal criterion. noise. This is a natural extension of deterministic control systems which cover a large class of situations.154 6 Sequential decisions under uncertainty precaution issue. 7.1. some parameters are not under direct control in the dynamics and may vary along time. Spe- cific treatment is devoted to the probabilistic or stochastic case in Sect. The assessments rely on mean performance in the stochastic case while worst case criteria are adapted to the robust perspective. This fact opens the door to different options: taking the mathematical expectation leads to stochastic control. As a first conse- quence. the criterion also becomes uncer- tain. Dynamics. etc. . the decision at each point in time must rely at least on the uncertain available information (current state for instance) to display required adaptive properties. 6. The remaining Sections are devoted to examples. As an initial step in these directions. 6. 6. Then. worst case. and we are led to define solution maps and feedback strategies in Sect. A similar type of difficulty arises for constraints in stochastic or robust viability that will be handled in Chap.4.3. 6. In this context. The principal difficulties stem from the fact that we are still manipulating states and controls. Perturbations disturb the system and yield uncertainties on the state paths whatever the decision applied. Similarly. For the sake of simplicity. decisions and controls are now to be selected to display reasonable performance for the system despite these uncertainties. constraints and optimality have to be carefully expanded. pessimistic. This chapter is devoted to the extension of the concepts and results of deterministic control to the uncertain framework. Different options for the criteria are presented in Sect. 6. In both cases. total risk-averse or guar- anteed and robust control frameworks may also shed interesting light. the open loop approach – consisting in designing control laws depen- dent only upon time – is no longer relevant: now.2. in the sense that the state is observed by the decision maker. the dynamic control system which has been the basic model in the previ- ous chapters is no longer deterministic.). the present textbook proposes to introduce ambiguity through the use of “total” uncertainty and robust control [6].
.
w(T ) (6. T − 1 with x(t0 ) = x0 (6. namely when Ω is a singleton Ω = {w(·)}.3. in Chap. it is worth distinguishing robust and stochastic approaches for handling such invariance or viability issues. In particular. . • The control constraints are respected at any time t: u(t) ∈ B t. Probabilistic assumptions on the uncertainty w(·) may also be added as we shall see in Sect. (6. This issue is addressed in Chap. u(t) ∈ U = Rp represents the decision or control vector. The new element w(t) in the dynamic stands for the uncertain variable 1 . the horizon T ∈ N∗ or T = +∞ stands for the term. The deterministic or certain case is recovered as soon as the alternatives are reduced to one choice. 9. . or disturbance. The assertions below are thus to be taken in a loose sense at this stage. 6.1 Uncertain dynamic control system 155 Uncertain dynamics Extending the state equation (2. . w(t0 + 1). . taking its values from a given set W = Rq . x0 ∈ X is the initial condition at initial time t0 ∈ {0. x(t). .4) capture the idea of possible scenarios for the problem. However. the uncertain dynamic model is described in discrete time by the state equation: x(t + 1) = F t.2) so that the sequences w(·) := w(t0 ). Scenarios We assume that w(t) ∈ S(t) ⊂ W . 7. noise. u(t). . Constraints and viability As in the certain case. . we may require state and decision constraints to be satisfied. . w(T − 1). 6. (6.5a) 1 Notice that we do not include here the initial condition in the uncertain variables.48). . x(t) ⊂ U . w(t) . the following requirements depend upon the scenarios w(·) ∈ Ω in a way that we shall specify later. . t = t0 .3) belonging to Ω := S(t0 ) × · · · × S(T ) ⊂ WT +1−t0 (6. x(t) ∈ X = Rn represents the system’s state vector at time t. T − 1}. A scenario is an un- certainty trajectory.1) where again F is the so-called dynamics function representing the system’s evolution. . since state trajectories are no longer unique. . .
utility. control and uncertainty trajectory. w(t) + M T..6) t=t0 in which the function L again specifies the instantaneous payoff (or gain. • The additive and separable form in finite horizon is −1 T π x(·). x(t). u(·). w(t) +(1−θ)M T. w(·) = L t. x(t). x(t). u(·). w(t) . M T.7) An intermediary form (Chichilnisky type) may be obtained by adding instantaneous and scrap performances (with 0 ≤ θ ≤ 1): T −1 π x(·). x(T ). A criterion π is a function π : XT +1−t0 ×UT −t0 × WT +1−t0 → R which assigns a real number to a state. u(·). x(t). benefit.1. (6. u(t). w(T ) . we distinguish the following cases. The final performance is measured through function M which can depend on time and terminal uncertainty w(T ). u(t)..4.) when the criterion π is maximized. w(·) = M T. (6.9.9) t=t0 .. 2. w(·) = min L t. u(t).156 6 Sequential decisions under uncertainty • The state constraints are respected at any time t: x(t) ∈ A(t) ⊂ X . the expression is somewhat heavier to write: π x(·). The so-called Green Golden form focuses on the final performance: π x(·).. w(t) . profit. 5.T −1 . with a final payoff. Extending the different forms exposed for the deterministic case in Sect. w(·) = min min L t.2 now depends upon the scenarios w(·): this point raises issues as to how to turn this family of values (one per scenario) into a single one to be optimized.5b) • The final state achieves a fixed target A(T ) ⊂ X: x(T ) ∈ A(T ) .5c) Criteria to optimize The criterion π of Subsect.8) t=t0 • The Rawls or maximin form in the finite horizon is (without final term) π x(·). w(T ) . x(T ). (6. x(T ). x(T ).. w(T ) .. w(·) = θ L t.. u(t). etc. t=t0 . (6. u(·). u(·)..T −1 and. (6. Such a general additive framework encom- passes more specific performance as the Green Golden or the Chichilnisky form. w(T ) (6.
x(t) which display more adaptive properties by taking the uncertain state evolution x(t) into account. the whole state x(t) is observed and available for control design. 6. conser- vation.2 Decisions. This perfect information case corresponds to state feedback controls u : N × X → U which may be any mapping apart from general measurability assumptions in the stochastic case. Extensions to the context of imperfect information are partly handled in Chap. . we must drop the idea that the knowledge of decisions u(·) induces one single path of sequential states x(·). 6. at time t.2 Decisions. We define a feedback as an element of the set of all functions from the couples time-state towards the controls: U := {u : (t. . We shall assume in the present chapter that. in contrast to closed loop or feedback controls u t. x) ∈ N × X . solution map and feedback strategies 157 These distinct ways2 of taking time into account for assessing the inter- temporal performance have major impacts on sustainability (equity. Open loop controls u(t) depending only upon time t are no longer relevant. 9. In the uncertain context. ) as previously discussed in the deterministic case. solution map and feedback strategies Decision issues are much more complicated than in the certain case.
while we denote by u ∈ U a feedback 2 For the mathematical proofs.. Such a policy is said to be pure by opposition to a mixed strategy that assigns to (x(t0 ).11) At this level of generality. x(t). a feedback decision is also termed a pure Markovian strategy 3 . . u(t0 ). for the sake of clarity. Hereafter. u(t) ∈ U. .. in the probabilistic setting. Markovian means that the current state contains all the sufficient information of past system evolution to determine the statistical distribution of future states. . . x(t). .. no measurability assumptions are made. the decision maker draws randomly a decision u(t) on U according to this latter law. x) ∈ U} . . w(t) × M T. x(t). However. . . u(t−1)) a control u(t) ∈ U. . w(·) = L t.→ u(t. σ-algebras will be introduced with respect to which feedbacks will be supposed measurable. only current state x(t) is needed in the feedback loop among the whole sequence of past states x(t0 ). u(t−1)) a probability law on U: in a mixed strategy. Thus. Let us mention that. x(T ). . . u(t). in the stochastic context. . w(T ) .. (6. .10) t=t0 3 A pure strategy (or policy) at time t is a rule which assigns to (x(t0 ).. we restrict the notation u(t) for a control variable belonging to U. u(t0 ). . x(t). the multiplicative form is also used: T −1 π x(·). . (6. . u(·).
. . x(T )) solution of dynamic x(t + 1) = F t. u. w(t − 1)) and not upon all w(·) = (w(t0 ). x) ∈ B(t. 6. Mathematically speaking. u. ⎧ ⎪ ⎨ xF [t0 . Given a feedback u ∈ U.12) corresponding to control constraints (6. x0 . x0 . w(·)] is the state path x(·) = (x(t0 ). with straightforward notations. . . t = t0 . u(T − 1)) where u(t) = u t. . thus expressing a causality property: the future state xF [t0 . . . The solution control uF [t0 . . x0 . . x(t0 + 1). x0 . . 2. . w(·)]. .5b)- (6. x) . (6. . and w(·) is identified with identity mapping. state and control variables are func- tions of the disturbances w(·) and in this sense they become uncertain vari- ables 4 . its definition depends upon the context. x(t). x)} . (w(t0 ). . . w(·)](t) de- pends upon the disturbances (w(t0 ). u t. Thus. . .4 in the Appendix. w(·)](t) = xF [t0 . T − 1 with x(t0 ) = x0 starting from the initial condition x(t0 ) = x0 at time t0 and associated with feedback control u and scenario w(·). what characterizes uncertain systems is the non uniqueness of trajectories.10). x0 . x(t) . u(t0 + 1). The viability case covers control and state constraints as in (6.3 Probabilistic assumptions and expected value Probabilistic assumptions on the uncertainty w(·) ∈ Ω may be added. A. Specific definitions are given hereafter accordingly. w(T − 1). w(t − 1))](t) (6. . x(t) .5c). x [t . At this stage. . Once a state feedback law is selected. w(T )). we equip 4 We reserve the term random variable to the case where the set WT +1−t0 is equipped with a σ-field and a probability measure. . the solution state xF [t0 . . w(·)](t0 ) = x0 . u. .5a). x . w(t) . However. ∀(t.158 6 Sequential decisions under uncertainty mapping. . a scenario w(·) ∈ Ω and an initial state x0 at time t0 ∈ {0. either robust or stochastic. . u. The terminology unconstrained case covers the situation where all feedbacks in U are allowed. u. u. This property will be used in Sect. x0 . . It should be noticed that. x) ∈ U (see the footnote 13 in Sect. .13) ⎪ ⎩ F 0 0 for t ≥ t0 + 1 .5a)-(6. we need to introduce some notations which will appear quite useful in the sequel: the state map xF [t0 . . . u. T − 1}. u. The control constraints case restricts feedbacks to admissible feedbacks as follows Uad = {u ∈ U | u(t. . with u(t. w(·)] is the associated decision path u(·) = (u(t0 ). x0 . pro- viding a stochastic nature to the problem. w(·)] and the control map uF [t0 .
when integrable. w(T − 1). controls and disturbances is now a ran- dom variable and. 7 Thus. F ). . In the stochastic setting. In such a probabilistic con- text. we are led to consider measurability assumptions. Once a feedback u is picked up in Uad defined in (6.i. . dw(T −1)dw(T ) . x(t) . Thus. the sets X = Rn and U = Rp are assumed to be equipped with the Borel σ- fields B(Rn ) and B(Rp ) respectively. w(T )) ∈ Ω now become the primitive random variables. by feedback. F. ) on W = Rq . Let A : Ω → R be a measurable function. Here. P) constitutes a probability space. . Ω with q the density of P on Ω. w(·) is identified with the identity mapping on (Ω. . (Ω.3 Probabilistic assumptions and expected value 159 the domain of scenarios Ω ⊂ WT +1−t0 = Rq × · · · × Rq with a σ-field5 F and a probability P: thus. . 6. In this configuration. we use thenotation Ew(·) [A w(·) ] for the expected value of the random variable A w(·) . x0 . w(T − 1). w(t0 + 1). . all ran- dom variables w(t) take values from the same domain S. and the probability P on the domain of scenarios is Ω = ST +1−t0 is chosen as the product of T − t0 + 1 copies of a probability μ over S. . 6. • For discrete probability laws (products of Bernoulli. . we mean a measurable feedback. ). uniform.6 The notation E refers to the mathematical expectation over Ω under prob- ability P. binomial. . 5 5 For instance the usual Borelian σ-field F = Tt=t0 B(Rq ). . To be able to perform mathematical expectations. this gives 2 Ew(·) [A w(·) ] = A w(·) q w(·) dw(t0 )dw(t0 +1) . hence. . w(·)](t) and u(t) = u t. beta. .) random variables w(t0 ). w(t0 + 1). We shall generally assume that the primitive random process w(·) is made of independent and identically distributed (i. 8 See the previous footnote 6. u. . . this means that: Ew(·) [A w(·) ] = A w(·) P w(·) . F. all the objects considered will be implicitly equipped with appropriate measurability prop- erties7 . exponential. . P) by means of the relations x(t) = xF [t0 .d. .11). the dynamic F is assumed to be measurable and. F ).2. when bounded or nonnegative. any quantity depending upon states. The sequences w(·) = (w(t0 ). w(T ) under P. which refer to state and control solution maps introduced in Sect. admits an integral with respect to probability P. 6 Recall that a random variable is a measurable function on (Ω. the state and control variables x and u become random variables 8 defined over (Ω. w(·)∈Ω • For continuous probability laws (Gaussian.
• Optimistic. • Stochastic or expected. we focus on robust and expected criteria. this requires a probabilistic structure for the uncertainties. x0 . 6.) as only the set of possible scenarios Ω is involved. w(·)](t) and u(t) = u t. u(·).2. x(t) . One weakness of such an approach is to promote means. (6. the optimistic perspective focuses on the most favorable payoff. Instead of maximizing the worst cost as in a robust approach. w(·) . u∈Uad w(·)∈Ω w(·)∈Ω . even if convenient and tradi- tional.160 6 Sequential decisions under uncertainty 6.15) u∈Uad where again in the last expression x(·) and u(·) refer to solution state and control introduced in Sect. u(·). we here expose optimistic. Robust control sheds interesting light on decision- making under uncertainty by adopting a pessimistic. w(·) + (1 − α) sup π x(·). A proportion α ∈ [0. u∈Uad w(·)∈Ω • Hurwicz criterion. 6. The most usual approach to handle decision under uncertainty corresponds to optimizing the expected payoff 6 7 sup E π x(·). Let us pick up a criterion π among the discounted. To quote a few. • Robust or pessimistic.2.14) u∈Uad w(·)∈Ω where the last expression is abusively used. We also mention the quadratic case which is connected to mean-variance analysis. This approach adopts an intermediate attitude be- tween optimistic and pessimistic approaches. Of course. Such a pessimistic approach does not require any probabilistic hypothesis on uncertainty w(. w(·) . w(·) . (6.1. u(·). worst case or totally risk-averse point of view. u. maximin or Chichilnisky forms as in Sect. It aims at maximizing the worst payoff sup inf π x(·). in which x(·) and u(·) need to be replaced by x(t) = xF [t0 . u(·). 6. referring to solution state and control in- troduced in Sect. hence to neglect rare events which may generate catastrophic paths. other approaches for decision-making under uncertainty exist. However.4 Decision criteria under uncertainty In this textbook. w(·) . This situation may be espe- cially critical for environmental concerns where irreversibility is important. Hurwicz criteria and multi-prior approaches. 1] grad- uates the level of prudence as follows: ) * sup α inf π x(·). namely: sup sup π x(·). u(·).
the prob- lem reads: inf var[π x(·). Nn (t) is the vector of abundances and h(t) = h1 (t). w(·) . u(·). • Multi-prior approach. Hence. . hn (t) the vector of catches. ki (t) . 9 The following notation EP stresses the dependency of the mathematical expecta- tion upon the probability P. u∈Uad The criterion is connected to mean-variance analysis since. w(·) . are relevant for the uncertain scenarios w(·) ∈ Ω. . It is assumed that different probabilities P. . 10 Other instances of uncertainty are of an anthropic feature. . u(·). w(·) ] = π. the population dynamic gi in Sect. 2. . we have: E[L(π)] = var[π] + E[π]2 − aE[π] . u∈Uad P∈P 6. w(·) . We consider a quadratic function L(z) = az−z 2 to assess the performance of the payoff π within a stochastic context: 6 7 sup Ew(·) L π x(·). n. . All possible ecological scenarios10 are described by w(·) ∈ Ω. For aggregated and compact models. u(·). u(·). . w(·) ] . Uncontrollability of catches suggests uncertain efforts which impact the harvests. . u(·). The multi-prior approach combines robust and expected criterion by taking the worst beliefs in terms of expected9 payoff.5 Management of multi-species harvests 161 • Quadratic and variance approach. denoting tem- porarily π = π x(·). if the expected payoff is a fixed E[π x(·). . its minimization captures the idea of reduction of risks. . 6. . . namely [7]: 6 7 P sup inf E π x(·). . termed as beliefs or priors and belonging to a set P of admissible prob- abilities on Ω. where N (t) = N1 (t). instances of such population uncertainties can be depicted by a combination of the uncertain intrinsic growth rate ri (t) and the carrying capacity ki (t): Ni (t + 1) = gi N (t) − h(t). u∈Uad Since the variance is a well-known measure of dispersion and volatility.5 Management of multi-species harvests For different species i = 1. ri (t). w(t) .2 is submitted to random factors w(·) including fluctuations in recruitment and mortality parameters imposed by demographic or environmental changes Ni (t + 1) = gi N (t) − h(t).
robust optimal criteria and worst case approach for dis- counted profit maximization are given by n T −1 sup inf ρt pi hi (t) − Ci hi (t). Chap- ter 7 gives insights into this issue. n. diversification is clearly an important topic. Diversification means retaining assets currently thought to be of little value when it is known that circumstances may change and alter that valuation. optimal expected discounted profit is: 6T n 7 −1 sup Ew(·) ρt pi hi (t) − Ci hi (t). Economic processes ap- pear through decisions of land-use allocation in order to guarantee a final wealth. Ni (t) . . In this context. . Similarly. . 6. i = 1. . Ni (t)) for costs. This issue is well known in finance and portfolio theory and a basic concern for biodiversity and environmental conservation problems. Ni (t) . h(·) w(·)∈Ω t=t i=1 0 where p = (p1 . pn ) stands for unitary prices and Ci (hi (t). This last requirement corresponds to a stochastic viability problem. ki (t)) which takes its values from some given set Si (t). whenever a probability P equips Ω. . h(·) t=t0 i=1 Whether diversification of catches among the targeted species is more efficient than specialization in harvesting in one species constitutes a basic issue in such a context.162 6 Sequential decisions under uncertainty In that case. . From a conservation and ecological viewpoint. In agriculture. . the uncertain variables for species i is wi (t) = (ri (t). . The modeled system is made up of a finite number of agricultural uses where each use accounts for total household wealth. where uncertainty and risk are pervasive. the regulating agency may also aim at ensuring non extinction of the populations at final time T with a confidence level β in the sense that: P N1 (T ) ≥ N1 . . Here is displayed a dynamic model dealing with wealth allocation strate- gies through land-use. .6 Robust agricultural land-use and diversification When an environment has unknown features or when it is constantly changing. It takes into account biological processes: each use is characterized by its own return rate which fluctuates with climatic situations. . . diversification of production assets can be a way of dealing with uncertainty. Nn (T ) ≥ Nn ≥ β . .
7 Mitigation policies for uncertain carbon dioxyde emissions 163 The natural productivity of the land-uses described through their biomass Bi (t). 6. . i=1 where pi Bi (t) ui (t) := υ(t) . . If we introduce fixed prices (sales and purchases) pi for each resource i. i=1 The wealth evolution is then described by & n ' υ(t + 1) = υ(t) ui (t)Ri w(t) . . i = 1. the wealth of the farm is given by: n υ(t) = pi Bi (t) .. where we assume that the climatic parameter w(t) can fluctuate along time within a given set S(t) (for instance between two extremal values).n. are represented by an intrinsic growth rate Ri (w) depending on a climatic parameter w as follows Bi (t + 1) = Ri w(t) Bi (t) .
3.7 Mitigation policies for uncertain carbon dioxyde emissions Following the stylized model described in Sect. the maximization of utility of the final wealth occurs with respect to feedback strategies. un ) ∈ S n . belonging to the simplex S n of Rn . among the different land-uses appears as a decision variable representing the land-use structure (the “portfolio”).n stands for the proportion of wealth generated by use i ( i=1 ui (t) = 1. such models raise the following question: How do mixed and diversified strategies. the farmer may aim at ensuring a minimal wealth at final time T in the following sense: υ(T ) ≥ υ . 2. u(·) where L is some utility function linked to risk-aversion [8]. . . In a viability approach. Consequently. improve overall performance? 6. as explained in the general case. the allocation u = (u1 . Here again. ui (t) ≥ 0). . we consider a climate- economy system depicted by two variables: the aggregated economic produc- . compared with strategies of specialization in one use. . In fact. Another way of formulating the problem is to consider the stochastic optimal problem max E[L(υ(t))] .
gwp: Q(t + 1) = 1 + g w(t) Q(t) . and is measured in GtC.164 6 Sequential decisions under uncertainty tion level. The description of the carbon cycle is similar to [13]. • the abatement rate a(t) corresponds to the applied reduction of co2 emis- sions level (0 ≤ a(t) ≤ 1).17) We consider a physical or environmental requirement through the limita- tion of concentrations of co2 below a tolerable threshold M at a specified date T > 0: M (T ) ≤ M . • Ebau (t) is the baseline for the co2 emissions. gwp. α ≈ 0. measured in ppm.GtC−1 sums up highly complex physical mechanisms.16) where • M (t) is the co2 atmospheric concentration.2 GtC per year between 2000 and 2005). namely a highly simple dynamical model M (t + 1) = M (t) + αEbau (t) 1 − a(t) − δ M (t) − M−∞ .18) The cost effectiveness problem faced by the social planner is an optimiza- tion problem under constraints. (6. Gigatonnes of carbon (about 7. (6. denoted by M (t). such as gross world product. • the parameter α is a conversion factor from emissions to concentration. denoted by Q(t) and the at- mospheric co2 concentration level. parts per million (379 ppm in 2005). The decision variable related to mitigation policy is the emission abatement rate denoted by a(t).471 ppm. • M−∞ is the pre-industrial atmospheric concentration (about 280 ppm).01 year−1 ). where the function Ebau stands for the emissions of co2 resulting from the eco- nomic production Q in a “business as usual” (bau) scenario and accumulating in the atmosphere. • the parameter δ stands for the natural rate of removal of atmospheric co2 to unspecified sinks (δ ≈ 0. The baseline Ebau (t) can be taken under the form Ebau (t) = Ebau (Q(t)). It consists . (6. The global economics dynamic is represented by an uncertain rate of growth g w(t) ≥ 0 for the aggregated production level Q(t) related to gross world product.
Tin minimizing the expected dis- −1 counted intertemporal abatement cost E[ t=t0 ρt C a(t). Q(t) .. . 1] stands for a discount factor..17) and target constraint (6. The parameter ρ ∈ [0.16) and (6. the problem can be written as +T −1 - inf E t ρ C a(t).18). Therefore..a(T −1) t=t0 under the dynamic constraints (6. Q(t) ] while reach- ing the concentration tolerable window M (T ) ≤ M . (6..19) a(t0 ).
In the robust sense. the non viable ’business as usual’ path abau (t) = 0% and. CO2 concentration viable 3.1.0e+11 0.5e+12 BAU green 3.0e+11 3.1 together with the ceiling target M = 550 ppm. this is not a viable reduction strategy. 6. Projections of co2 concentration M (t) and economic production Q(t) at horizon 2100 for different mitigation policies a(t) together with ceiling target M = 550 ppm in 3. The path in ⊕ relies on a total abatment a(t) = 100%. Another abatement path corresponding here to stationary a(t) = 90% pro- vides some viable or non viable paths.5e+11 1. The “business as usual” no abatement path abau (t) = 0% does not display sat- isfying concentrations since the ceiling target is exceeded at time t = 2035.0e+12 5. in blue. In black.7 Mitigation policies for uncertain carbon dioxyde emissions 165 Some projections are displayed in Fig.0e+00 1980 2000 2020 2040 2060 2080 2100 years t Fig. .0e+11 2.5e+11 2.5e+12 M(t) (GtC) 2. They are built from Scilab code 13 with scenarios of eco- nomic growth g w(t) following a uniform probability law on [0%.0e+11 5.0e+10 0.5e+12 1. 6.5e+11 4.0e+00 2000 2020 2040 2060 2080 2100 years t Production Q(t) 4.0e+12 threshold 2.0e+11 1. a reduction a(t) = 90%. 6%].5e+11 3.0e+12 1. 6.
style=-[4..’ul’).7) dealing with an economy exploiting an exhaustible natural resource ⎧ ⎨ S(t + 1) = S(t) − r(t) . function Mnext=dynamics(t. // initial time L_E=[]. M_g=M. // Strong mitigation xtitle(’Emissions E(t)’.t_F-t_0+1).20) . L_E=[L_E E].2000]) .’M(t) (ppm)’). // System Dynamics xset("window".style=-[8]).1).3.Q.a) // Results printing E = sigma * Q * (1-a).t_F-t_0+1). mean_taux_Q=0. E_bau= emissions(Q. M_g=M0. L_Eg=[L_Eg E_g]. for ii=1:N_simu xtitle(’Economie: Production Q(t)’. -[4.xbasc(2). r(t). endfunction long=prod(size(L_t)). rect=[t_0. E = emissions(Q. t=t_0. a = 1*ones(1.Q. L_Ebau=[L_Ebau E_bau]. endfunction plot2d(L_t(abcisse).M_g. // (uncertain +.3]. a = 0*ones(1.1).0. // Initial conditions L_bau=[L_bau M_bau].166 6 Sequential decisions under uncertainty Scilab code 13. Q=(1+g_Q)*Q.9*ones(1. L_g=[M0].’t’. M=dynamics(t. style=-[4.5. L_Q=[L_Q Q].a(t-t_0+1)).M_bau.a) step=floor(long/20).2). M_bau=M."BAU".’Q(t) (T US$)’). // medium mitigation L_g(abcisse)’ ones(L_t(abcisse))’*M_sup]. // Mitigation concentration sig_taux_Q=0. M0=354.-[4.8 Economic growth with an exhaustible natural resource Let us expand to the uncertain context the stylized model introduced in Sect. // PARAMETERS // L_M=[M0]. // random mitigation legends(["Mitigation". a = 0.L_Eg=[].Q.Q. (6. function E=emissions(Q.a(t-t_0+1)).0.-1]. xset("window". plot2d(L_t(abcisse). // in (T US$) end. end Q = Q0.4).15) M_g=dynamics(t.. abcisse=1:step:long..a) .0). Q0 = 20.’t’.’ul’).3. // Business as usual (BAU) // dynamics parameter: atmospheric retention E_g = emissions(Q. sigma=0. // Distinct abatment policies L_Eg(abcisse)’].5)+mean_taux_Q."green"]. t=t_0. M_bau=M0.’t’. M_sup=550.3]) .. w(t) − c(t) . //in (ppm) L_g=[L_g M_g]. M_inf=274. N_simu=3.t_F. L_M=[L_M M]. M=M0. g_Q=sig_taux_Q*2*(rand(1..xbasc(4) xtitle(’Concentration CO2’. E = emissions(Q. // //Initialisation 6. //a = 1*rand(1.64. legends(["Mitigation"."threshold"].5. // mean and standard deviation of growth rate M_bau=dynamics(t....5. // Time step // random growth rate delta_t=1.[L_M(abcisse)’ L_bau(abcisse)’ .t_F-t_0+1).L_Q(abcisse)."BAU". // concentration target (ppm) L_t=[L_t t+1].M."green".1).03.9. // total abatement deltaa=1/120. // No mitigation (BAU) xset("window". t_0=1990.M.519. Mnext =M + alphaa* E -deltaa*(M-M_inf).’E(t) (GtC)’).. // L_t=[t_0]. // final Time for (t=t_0:delta_t:t_F) t_F=2100. ⎩ K(t + 1) = 1 − δ w(t) K(t) + Y K(t).1)-0.-1]. xbasc(1). (2.t_F-t_0+1).[L_E(abcisse)’ L_Ebau(abcisse)’ . alphaa=0. L_Q=[].0). L_Ebau=[]. L_bau=[M0]. plot2d(L_t(abcisse)..03.5.
Again state-control constraints can be taken into account. The extraction r(t) is irreversible in the sense that: 0 ≤ r(t) . r(t).8 Economic growth with an exhaustible natural resource 167 where S(t) is the exhaustible resource stock. w) captures possible changes in environmental preferences. 1[ is a discount factor. (6. More generally. (6. A question that arises is whether the uncertainties w(t) affect the con- sumption paths compared to the certain case. we can consider a stronger conservation constraint for the resource as follows: S ≤ S(t) .24) A sustainability requirement can be imposed through some guaranteed con- sumption level c along the generations: 0 < c ≤ c(t) . w(t) . The controls of this economy are levels of consumption c(t) and extraction r(t) respectively. c.r(·) t=t0 where ρ ∈ [0. (6. w(t) − c(t) . We assume the investment in the reproducible capital K to be irreversible in the sense that: 0 ≤ Y K(t).22) The threshold S > 0 stands for some guaranteed resource target. The uncertainty of the utility function L(S. c(·).23) We also consider that the capital is non negative: 0 ≤ K(t) . referring to a strong sustainability concern whenever it has a strictly positive value.25) One stochastic optimality problem adapted from [5] is + +∞ - sup E ρt L S(t).21) We take into account the scarcity of the resource by requiring: 0 ≤ S(t) . K(t) represents the accumulated capital. . c(t). (6. The last two parameters are now assumed to be uncertain in the sense that they both depend on some uncertain variable w(t). r(t) stands for the extraction flow per discrete unit of time. c(t) stands for the consumption and the function Y represents the technology of the economy. Parameter δ is the rate of capital depreciation. 6. (6.
P. [4] G. Olson and R. Journal of Mathematical Economics. Chichilnisky. Kokotowic. [2] D. 18(2):141–153. Heal. 95:186– 214. [5] P. [10] M. Academic Press. and B. [3] K. [6] R. 2001. Dynamic Programming and Optimal Control. April 1989. Bertsekas and S. Analysis and Management of Animal Populations. Birkhäuser. Conroy. 1996. Maxmin expected utility with non-unique prior. Houghton Mifflin Company. Stochastic Optimal Control: The Discrete-Time Case. Sustainability: Dynamics and Uncertainty (Economics. 41:1–28. 1982. 2000. Elements of Mathematical Ecology. S. Heal. Risk. J. 1998. Freeman and P. and A. 1921. Lande. Athena Scientific. Dynamic efficiency of conservation of renew- able resources under uncertainty. MIT Press. MIT Press. [14] L. G. John Wiley & Sons. New York. Saether. Gollier. Basel. Gilboa and D. volume 1. Nichols. Kot. Massachusets. 1989. MIT Press. Symposium on the Eco- nomics of Exhaustible Resources. Review of Economic Studies. Cambridge University Press. 2003. D. Oxford series in ecology and evolution.-E. M. E. 2001. [12] R. second edition. D. Cambridge. [9] F. Managing the Global Commons. J. [8] C. The optimal depletion of exhaustible resources. Santanu. Belmont. Shreve. 1996. . J. Boston. Stochastic population dynamics in ecology and conservation. The Economics of Uncertainty and Information. [11] J. A. Vercelli. Massachusets. Knight. Springer. Dasgupta and G. Cambridge. Volumes 1 and 2.-J.References [1] D. Byron. Cambridge. P. V. [13] W. Whittle. Belmont. Engen. [7] I. Uncertainty and Profit. The Economics of Risk and Time. Journal of Economic Theory. and M. [15] P. 1974. Energy and Environment). Nordhaus. 2000. 1994. Schmeidler. W. Laffont. Optimization over Time: Dynamic Programming and Stochastic Control. Bertsekas.H. Athena Scientific. 2002. Robust Nonlinear Control Design (State Space and Lyapunov Techniques).
7. co2 ceiling. After briefly introducing the uncer- tain viability problem in Sect. Regarding these motivations. We present the dynamic programming method. totally risk averse context [5. . constraints “in the probabilistic or stochastic sense” are basically related to risk assess- ment and management. The robust approach is closely related to the stochastic one with a confidence level of 100%. it is detailed in the robust framework in Sect. . risks.5. safety and precaution constitute major issues in the man- agement of natural resources and sustainability concerns. The idea of stochastic viability is basically to require the respect of the constraints at a given confidence level (say 90%. 10]. ) is central but has to be articulated with uncertainty. 9. the role played by the acceptability constraints or targets (popu- lation extinction threshold. 99%). 3. we adapt the notions of viability kernel and viable controls within the probability and robust frameworks. robust and stochastic approaches deserve to be distinguished although they are not disconnected.1. 8. Some mathematical materials of stochastic viability can be found in [1. On the other hand. 4] but they tend to focus on the continuous time case. The chapter is organised as follows.7 Robust and stochastic viability Vulnerability. in the field of con- servation biology. The present chapter addresses the issue of constraints in the uncertain context and expands most of the concepts and mathematical and numerical tools examined in Chap. 11. 7. Here. On the one hand. and different examples illustrate the main statements. 7]. the problems and methods of population viability analysis (pva) [2. and the stochastic case is treated in Sect. con- straints “in the robust sense” rely on a worst case approach.2. 4 about viable control. Such stochastic viability includes. 7. It implic- itly assumes that some extreme events render the robust approach irrelevant. In the uncertain framework. . The fundamen- tal idea underlying such robust viability is to guarantee the satisfaction of the constraints whatever the uncertainties which may be related to a pes- simistic.
Such a feasibility issue can be addressed in a robust or stochastic framework.1) Here again. .2c) hold true under the dynamics (7. ∀(t. t = t0 . The control constraints case (7.1) whatever the scenario w(·) ∈ Ω. u(t). we first deal with such a problem in a robust perspective. In the robust case. x(t) ∈ X = Rn represents the system state vector at time t. Possible scenarios. T −1 with x(t0 ) = x0 .2c) These control. As detailed in Sect.3) Robust viable controls and states The viability kernel plays a basic role in viability analysis. (7.3). (7. . or disturbance.1 The uncertain viability problem The state equation introduced in (6.11) such that the control and state constraints (7. Namely we consider the admissible feedbacks u in U defined in (6. x) u(t) ∈ B t. w(·) are described by: w(·) ∈ Ω := S(t0 ) × · · · × S(T ) ⊂ WT +1−t0 .2b) and a target x(T ) ∈ A(T ) ⊂ X . w(t) .1) as the uncertain dynamic model is considered: x(t+1) = F t.1. x0 ∈ X is the initial condition at initial time t0 .172 7 Robust and stochastic viability 7.2a) restricts feedbacks to admissible feedbacks as follows: Uad = {u ∈ U | u(t. or paths of uncertainties. 6. T > t0 is the horizon. In the sequel. u(t) ∈ U = Rp represents the decision or control vector while w(t) ∈ S(t) ⊂ W = Rq stands for the uncertain variable. state or target constraints may reduce the relevant paths of the system.2a) together with a non empty subset A(t) of the state space X for all t x(t) ∈ A(t) ⊂ X . Uad is the set of admissible feedbacks as defined in (7. (7. x(t). x) ∈ B(t. 7.2 The robust viability problem Here. (7. x)} . noise. . . the admissibility of decisions and states is re- stricted by the non empty subset B(t.2b)-(7.2a)-(7. it is the set of initial states x0 such that the robust viability property holds true. x(t) ⊂ U . x) . . x) of admissible controls in U for all (t. (7.
x) := 1A(t) (x) sup w∈S(t) inf V t + 1. the viability problem consists in identifying the viability kernel Viab1 (t0 ) and the set of robust viable feedbacks Uviab 1 (t0 . and 1A (x) = 0 if x ∈ A. . namely Viab1 (T ) = A(T ) . (7. T where again x(t) equals xF [t0 . Notice that the final viability kernel is the whole target set. .2c) is defined by the following back- ward induction.2. it is convenient to use the indicator function 1 1A(t) of the set A(t) ⊂ X. 6. . (7. (7. By definition.x) This is the robust viability dynamic programming equation (or Bellman equa- tion). x0 ) = ∅ . u∈B(t. To achieve this.2. Viable robust feedbacks are defined by ) * for all scenario w(·) ∈ Ω ad U1 (t0 .1).e.3. x0 . .6) Thus.2 The robust viability problem 173 Definition 7. Viable robust feedbacks are feedbacks u ∈ Uad such that the robust viability property occurs. (7. .5) x(t) ∈ A(t) for t = t0 . u. x0 . x. x) := 1A(T ) (x) . . Definition 7.2a) state con- straints (7.1.7) ⎪ ⎩ V (t. T ⎭ where x(t) corresponds to the state map namely x(t) = xF [t0 . Definition 7. where t runs from T − 1 down to t0 : ⎧ ⎪ ⎨ V (T. w(·)](t) as defined in Sect. F (t. The robust viability value function or Bellman function V (t. w) . w(·)](t) as defined in Sect. x).4) ⎩ x(t) ∈ A(t) for t = t0 . the robust iability kernel represents the initial states x0 avoiding the emptiness of the set of robust viable feedbacks Uviab 1 (t0 .: x0 ∈ Viab1 (t0 ) ⇐⇒ Uviab 1 (t0 . 7. The robust viability kernel at time t0 is the set ⎧ ⎫ ⎨ there exists u ∈ Uad such that ⎬ Viab1 (t0 ) := x0 ∈ X for all scenario w(·) ∈ Ω . i. Robust dynamic programming equation A characterization of robust viability in terms of dynamic programming can be exhibited.2. . x0 ). control constraints (7. u. 1 Recall that the indicator function of a set A is defined by 1A (x) = 1 if x ∈ A. x0 ) := u ∈ U viab . .2b) and target constraints (7. u. x0 ). . associated with dynamics (7. 6.
.
x) ∈ {0. Proposition 7. 1}.4. A. x) ∈ B1 viab (t.5 is given in the Appendix. where t runs from T − 1 down to t0 : ⎧ ⎪ ⎪ Viab1 (T ) = A(T ) .5. x) = ∅ ⇐⇒ x ∈ Viab1 (t) . It turns out that the robust viability value func- tion V (t. x) | ∀w ∈ S(t) . F (t. let us define robust viable con- trols: Bviab 1 (t.7) makes it possible to define the value function V (t. (7. x) . w) ∈ Viab1 (t + 1)} . x) := {u ∈ B(t. . x) = 1 ⇐⇒ x ∈ Viab1 (t) .10) A solution to the viability problem is: ⎫ x0 ∈ Viab1 (t0 ) ⎬ ⇒ u ∈ Uviab 1 (t0 . . ∀x ∈ Viab1 (t) ⎭ Notice that the state constraints have now disappeared. T − 1 .5. (7.174 7 Robust and stochastic viability Notice that V (t. Sect. . u. ∀t = t0 . .9) Robust viable controls exist at time t if and only if the state x belongs to the robust viability kernel at time t: Bviab 1 (t. . u(t.5).8) The proof of the following Proposition 7. being incorporated in the new control constraints u(t) ∈ Bviab 1 t. x) . u. (7.11) ⎪ ⎪ ⎪ ⎩ F (t. x) and reveals relevant viable robust feedbacks. x) = 1Viab1 (t) (x). Definition 7. x0 ) . w) ∈ Viab1 (t + 1)} . ∀w ∈ S(t) . We have V (t. x. Viable robust feedbacks The backward equation of dynamic programming (7. x(t) . x. ·) at time t is the indicator function of the robust viability kernel Viab1 (t) (Proposition 7. The previous result also provides a geometrical formulation of robust vi- ability dynamic programming since the robust viability kernels satisfy the backward induction. ⎪ ⎨ Viab1 (t) = {x ∈ A(t) | ∃u ∈ B(t. (7. For any time t and state x. that is: V (t.
3 Robust agricultural land-use and diversification Here we cope with the problem already introduced in Sect. i=1 where pi Bi (t) ui (t) := υ(t) . The annual wealth evolution of the farm is described by & n ' υ(t + 1) = υ(t) ui (t)Ri w(t) = υ(t)u(t). R(w(t) .3 Robust agricultural land-use and diversification 175 7. 6.6 and inspired by [11]. 7.
and w(t) corresponds to environmental uncertainties evolving in a given domain S. υ) = 1[υ (t+1).+∞[ (υ).7). . ui (t) ≥ 0). Assume now that. . Viability kernel Result 7. The farmer aims at ensuring a minimal wealth at final time T : υ(T ) ≥ υ . u∈S n w∈S Equivalently. R = sup inf u. The allocation u = (u1 . R(w) .+∞[ (υ) . sup inf u. the robust viability kernel is Viab(t + 1) = [υ (t + 1). Using the Bellman equation (7. The value function at final time T is given by: V (T. among the different land-uses appears as a decision variable represent- ing the land-use structure. +∞[ . +∞[ with: υ (t + 1) = υ (R )t+1−T . we reason backward using the dynamic program- ming method for indicator functions as in (7. the value function is V (t + 1.6 The robust viability kernel turns out to be the set Viab(t) = [υ (t). with the viability threshold υ υ (t) = T −t .n stands for the proportion of wealth generated by use i ( i=1 ui (t) = 1. we deduce that: . υ) = 1[υ .7) for robust viability. R(w) u∈S n w∈S To prove such is the case. at time t + 1. . un ) ∈ S n . belonging to the simplex S n of Rn . .
See Figs. . the equality does not hold in general. The equality holds true whenever no uncertainty occurs.+∞[ υ( sup inf u. .. R(w) = R . namely with a fixed w. +∞[ with υi (t) = T −t . In the uncertain case. 7. +∞[. We conclude that Viab(t) = [υ (t).+∞[ υ = 1[υ (t).1 built with Scilab code 14. inf w∈S Ri (w) 8n Of course. . 0. R(w)) u∈S n w∈S = 1[υ (t+1). w∈S ⎩ sup inf u. If the growth functions are such that max inf Ri (w) < sup inf R(w). n} corresponds to: ui (t) = 1 . uj (t) = 0 . υ) = sup inf V t + 1. This means that the viability of specialized and diversified strategies coincide in this case..176 7 Robust and stochastic viability V (t.. the worst growths are: ⎧ ⎨ inf Ri (w) = R − σ .. R(w)) u∈S n w∈S = 1[υ (t+1). υ(u. ∀j = i . .+∞[ υR = 1[υ (t+1)(R )−1 .+∞[ (υ) . it is enough to think of the following example: R1 (w) = R − wσ. u .5). R(w)) u∈S n w∈S = sup inf 1[υ (t+1). Specialization versus diversification Now we aim at comparing specialized and diversified land-use. In this case. .5. R2 (w) = R + wσ. To capture the difference. Hence we obtain the specialized robust viability kernel: υ Viabi (t) = [υi (t). u∈S n w∈S Note that the diversified viable land-use is given by u = (0.+∞[ υ(u. w ∈ [−1. however. 1] . The specialized land-use in i ∈ {1. i=1. we have the inclusion i=1 Viabi (t) ⊂ Viab(t).n w∈S u∈S n w∈S 8n then i=1 Viabi Viab.
3 Robust agricultural land-use and diversification 177 Wealth 200 Diversified strategy 180 Minimal wealth threshold 160 140 120 wealth x(t) 100 80 60 40 20 0 0 1 2 3 4 5 6 7 8 9 time t (a) Diversified strategy Wealth 400 Strategy specialized in use 1 Minimal wealth threshold 350 300 250 wealth x(t) 200 150 100 50 0 0 1 2 3 4 5 6 7 8 9 time t (b) Specialized strategy in use 1 Wealth Strategy specialized in use 2 200 Minimal wealth threshold 150 wealth x(t) 100 50 0 0 1 2 3 4 5 6 7 8 9 time t (c) Specialized strategy in use 2 Fig. 7. . Many catastrophic scenarios υ(T ) < υ exist for specialized land-use. 7. Wealth υ(t) for diversified u = (0.1. 0. while diversified land-use ensures guaranteed wealth υ(T ) ≥ υ .5. 0) for different environmental scenarios with time horizon T = 9 and υ = 50.5). 1) and u = (1. specialized u = (0.
.11).Horizon)’ ].t).’time t’.’w(t)’).xtitle("Uncertainty".2). // 7. // diversified x_2(:. rect2=[0.Horizon)’ ].’t’..Horizon)’ ]. // xset("window".-4]) // time horizon legends([’Strategy specialized in use 1’.w_viab’.Horizon-2.11).200].w_max].rect=rect1) Horizon=10.0]*ones(1.Horizon-1).Horizon-1).w) // Simulations // dynamics x_viab=x_prec+rand(1. // exec robust_diversification.t+1)=f(x_viab(:. xset("window".4 Sustainable management of marine ecosystems through protected areas: a coral reef case study Over-exploitation of marine resources remains a problem worldwide. y=x*(1+u’*retu(w)).rect=rect1) // Viable diversified return plot2d(xx.Horizon)’ ]. the influence of protected areas upon the sustainability of fisheries within an ecosystemic framework is addressed through a dynamic bioeconomic model in- tegrating a trophic web.Horizon-1).Horizon-1.style=[1. // Diversified wealth xtitle("Wealth". // u_2=[0. Many works advocate the use of marine reserves as a central element of future stock management in a sustainable perspective.’t’. catches and environmental uncertainties.sce // Specialized strategies //////////////////////////////////////////// N_simu=10.style=[1.w_viab(:.0. // specialized in use 2 rect3=[0.’time t’.rect=rect2).178 7 Robust and stochastic viability Scilab code 14.-4]. w_max=1.plot2d(xu. // precautionnary initial conditions function r=retu(w) // x(0)>= x_min/(1+r_star)^(Horizon-1) // return of land-use w_viab=w_min+(w_max-w_min)*rand(1.[x_1’ x_min+zeros(1.[1.Horizon-1). x_1=x_viab.rect=rect1).[x_viab’ x_min+zeros(1.Horizon)’ ].3).5.plot2d(xu. w_min=-1.’ul’) // Viable initial state // xset("window".t)). It is inspired from data on the Aboré coral reef reserve in .21).t).t)).1. The model is spatially implicit.u_viab’. plot2d(xx. r=[r_0+sig*w.’ul’) r_0=0.’time t’. In the present model detailed in [6].0).u_1(:.-4]) legends([’Strategy specialized in use 2’.5 // // mean and variance return xset("window". // // wealth bounds // x_min safety constraint xset("window".1]*ones(1.xbasc().xbasc(). plot2d(xx.0..1].t+1)=f(x_1(:.. r_star=r_0.-4]) // uncertainty margins legends([’Diversified strategy’.xbasc(). xset("window". x_prec=x_min/((1+r_star)^(Horizon-1)).r_0-sig*w].[x_viab’ x_min+zeros(1.[x_2’ x_min+zeros(1.Horizon-2. end // specialized in use 1 // xset("window".xbasc().2).t). plot2d(xx.-4]..) x_viab(:.0. ’Minimal wealth threshold’].u_2(:. xset("window".0).[1. plot2d(xx. // Random climate along time endfunction for (t=1:1:Horizon-1) // Viable Trajectory x(.’wealth x(t)’).u_viab(:. xset("window". xx=[0:1:Horizon-1].style=[1.’wealth x(t)’). plot2d(xx.u.5]*ones(1.t). // Diversified viable strategy end u_1=[1.) u(..t)).xu=[0:1:Horizon-2].w_min.[x_1’ x_min+zeros(1.’wealth x(t)’).’Minimal wealth threshold’]. xset("window".t).Horizon)*(x_max-x_min). xtitle("Wealth".21)..[x_2’ x_min+zeros(1. ’Minimal wealth threshold’]. u_viab=[0. rect1=[0.w_viab(:. x_1(:.rect=rect3). // Specialized wealth xtitle("Wealth".’ul’) x_min=50.sig=0. [1.w_viab(:. endfunction x_2=x_viab.t+1)=f(x_2(:.xtitle("Allocation"..-4]. x_max=100.. // Land-use and diversification // Number of simulations //////////////////////////////////////////// for i=1:N_simu function [y]=f(x.’u(t)’).Horizon)’ ].3).t).xbasc().
Hereafter. . Coral cover is denoted as y1 (t).069 0 0 The predation intensity depends on coral cover y1 (t) through a refuge effect exp y1 − y1 Sij . .3 6 67 11 3 5 6 .3 .3 . Other fish (small) N4 (t) include sedentary and territorial organ- isms. i where R = (R1 . the time unit is assumed to be the day. Herbivores N3 (t) are represented by Scarus sp parrot fish.Macroinvertebrates 21 82 20 2 0 2 1 .7. Species richness.4 3 2 0 3 79 .093 0. . .3 1 0 66 3 0.013 0.002 0.076 −0.106 −0.Zooplankton 1 0.Microalgae 0 1 5 7 28 80 11 .Macroalgae 0 0. .01 0 ⎟. microcarnivores (17 cm).3 1 1 4 6 0. . Macrocarnivores N2 (t) feed on macroinver- tebrates and a few fish species.Microinvertebrates 0.Detritus 0 0. N4 (t) and coral y(t) evolutions. 0 ⎠ −0. Based on diet composition in Table 7. . The evaluation of the ecosystem is designed through the re- spect along time of constraints of both conservation and guaranteed captures. .3 . .1 and a Lotka-Volterra structure.012 0. coral feeders (16 cm) and zooplanktonophages (13 cm). .Nekton 77 10 2 0 0 0.m−2 ) and coral covers (percent) are considered in order to char- acterize the state of the ecosystem. .002 ⎟ S=⎜ ⎝ −0.Coral 0 0.4 Sustainable management of marine ecosystems through protected areas 179 New Caledonia. Piscivores N1 (t) are predators of fish and are often targeted by fishermen.Other plankton 0 0 0 0 0 0 0. Four trophic group densities (g.3 2 77 0 1 0. mean diet composition and adult size The dynamics of the ecosystem rely on trophic interactions between groups N1 (t).2 Maximum adult size (cm) 77 38 17 16 39 24 13 Table 7.53 −0. the dynamic of the trophic groups i = 1.013 0. . R4 ) and where the interaction matrix S reads: ⎛ ⎞ −0.013 ⎜ −0. Trophodynamics of the ecosystem Piscivores Macro Micro Coral Herbivores Microalgae Zooplankton carnivores carnivores feeders Detritivores feeders (Pi) (MC) (mC) (Co) (He) (mAD) (Zoo) Group for the model N1 N2 N4 N4 N3 N3 N4 Species richness 46 112 50 26 10 73 54 Diet composition (%) . 4 is summarized in matrix form by Ni (t + 1) = Ni (t) R + exp y1 − y1 (t) Sx(t) .1 1 . .1.
Computed at the equilibrium.8 . On average.008 ⎠ . the coral grows by 10% a year but not linearly: it takes 8 to 10 years to reach the initial cover.12) Rcor Exploited dynamics with a protected area For the area under study. The intrinsic growth rate Rk includes mortality and recruit- ment of each trophic group k. 1. Kcor We identify the maximal value of 80% with the carrying capacity: Rcor − 1 y1 = Kcor = 0.12). independently of interactions with other trophic groups. We assume that the climatic change scenario corresponds to a rise of 50% in p namely p = 1/(4 × 365). Assuming a simple Gor- don Schaefer production function where e(t) is the fishing effort. • Kcor is related to the so-called carrying capacity ȳ1 solution of: ȳ1 1 = Rcor 1 − . In the model.007 ⎟ R=⎜ ⎟ ⎝ 1. Unfortunately. we .180 7 Robust and stochastic viability where the refuge parameter y1 corresponds to the maximal coral cover defined later in (7. • p is the probability of a cyclonic event.054 Habitat dynamics Coral evolution over time is described through the equation: ⎧ ⎨ y1 (t) Rcor 1 − with probability (1 − p) . cyclonic events occur randomly with probability p at each time step and bring coral cover to 30% of its previous value. it reads: ⎛ ⎞ 0. Simulations show that Rcor = 1.002 is a plausible value in this respect (recall that the time unit is assumed to be the day).3 with probability p . To overcome this difficulty. a cyclone happens every 5 to 6 years and setting p = 1/(6 × 365) corresponds to the present cyclonic situation. fishing is basically recreational and associated mainly with spear gun technology. • Rcor is the intrinsic productivity at low cover levels.975 ⎜ 1. y1 (t + 1) = y1 (t) × Kcor ⎩ 0. quantitative information on catches and effort in the area is not available. we write hi (t) = qi e(t)Ni (t) with zero catchability q4 = 0. It is assumed to affect only piscivores N1 (t). (7. After a cyclonic event. carnivores N2 (t) and (large) herbivores N3 (t).
e(·) Viab(A. . t = t0 . The indicator of robust viability (co-viability) is given by the robust via- bility kernel2 Viab defined by: . .B ) = (N (t0 ). h3 (t) ≥ L . (7. 1]. y(t0 )) .4 Sustainable management of marine ecosystems through protected areas 181 impose some simplifications hereafter.7. A stronger conservation constraint We adopt a stronger conservation point of view and introduce a biodiversity constraint in the sense that trophic richness is guaranteed at a level B : 4 B(N (t)) = 1{Ni (t)>0} ≥ B . However we do not specify e and we study the results for a range e ∈ [0. (7.13) where υi stands for the mean weight of group i. A direct use value We assume that the ecosystem provides direct uses through harvests of preda- tors N1 and N2 and herbivores N3 . T − 1 . 4} ensures a minimal number of non exhausted groups. .7 0.15) i=1 This guaranteed trophic threshold B which takes its values from {1. . .5 0.1) in kg.5 0. h2 . 3. 2 See the following footnote 3 in this Chapter to explain the presence of P in the robust viability kernel. In other words. Taking into account the protected area. h2 (t). catches are defined by hi (t) = qi e(t)(1 − mpa)Ni (t) . . 2. We further assume that catchabilities are equal for each fished group in the sense: q 1 = q2 = q3 . T − 1 ≥ 1 A protection effect should capture processes through which both the con- servation and catch services are enhanced by the existence of a reserve. . h3 ) = υ1 h1 + υ2 h2 + υ3 h3 .14) where L > 0 stands for some guaranteed satisfaction level.14). The direct use constraint reads L h1 (t). . where mpa is the proportion of the zone closed to fishing.L . sup P (N (t).15) . h(t)) satisfies (7. t = t0 . The direct use L is assumed to take the form of total catch in weight L(h1 . . (7. Weight values for each group are given by υ = (0. (7. it is assumed that only a part of the stock is available for fishing. We first assume that the effort rate in the overall area is targeted at some fixed level e: e(t) = e .
In Fig.67 0. 7. in this case. carnivores and herbivores are depleted because of fishing.00 piscivores piscivores macrocarnivores macrocarnivores herbivores herbivores other fishes other fishes 1.48 1.00 0.33 X(t) X(t) 0.8 = 80% . catch reserve effects are compatible with biodiversity per- formance. namely T = t0 + 31.4) . guaranteed utility of catch resulting from all trophic groups is exhibited. a mpa catch effect is combined with a mpa biodiversity effect.04 0.m−2 .2) .49) g. mpa = 0%.80.L0 . We also set the initial habitat state y1 (t0 ) at equilibrium in the sense that: y(t0 ) = ȳ1 = 0. Results The results are based on simulations using the scientific software Scilab.67 0.L . In (a) without reserve. without reserve (mpa = 0%). The initial time corresponds to year t0 = 1993 and the time horizon is set to 30 years ahead.182 7 Robust and stochastic viability Densities Trajectories for MPA=0%and e=20% Densities paths for maximal MPA=80%and e=20% 2.2(b) the maximal reserve size (mpa = 80%) provides a larger guar- anteed utility of captures L > L0 resulting from every targeted trophic group including carnivores.2. i. We assume that p = 1/(6 × 365) which is a current estimation of cyclonic probability by day. It turns out that a catch reserve effect is significant for low positive ex- ploitation rates e namely 10% ≤ e ≤ 60%. for some guaranteed capture level L0 > 0: (N (t0 ). In other words. Thus.17 0. y(t0 )) ∈ Viab(0. The initial state conditions derived from data of 1993 are: N (t0 ) = (0.33 1. 7. In Fig.2(a). y(t)) in the case of current cyclonic frequency p = 1/(6 × 365) for the moderate fishing effort e = 20%. no guaranteed capture of carnivores is achieved while in (b) under the maximal reserve size mpa = 80%.e.00 2. 7. In other words: (N (t0 ). y(t0 )) ∈ Viab(0.00 1993 2003 2013 2023 1993 2003 2013 2023 t t (a) Without reserve MPA= 0% (b) Optimal MPA= 80% Fig. A catch reserve effect is obtained as displayed in Figs 7. Projections of state (N (t). piscivores and herbivores. . In this sense.2.
In the probabilistic setting. For sake of simplicity. x0 . In particular. In the stochastic setting. T ≥ β (7. for instance.5 The stochastic viability problem 183 7. The viability kernel plays a basic role in the viability analysis. The stochastic viability kernel at confidence level β ∈ [0.i. . .2b)-(7. w(T ) under probability P on the domain of scenarios Ω = ST +1−t0 .16) where x(t) corresponds to the solution map x(t) = xF [t0 .2c) were assumed to hold whatever the disturbances. 1] is3 . 6. within the probabilistic framework. the primitive random process w(·) is assumed to be a sequence of independent identically distributed (i. . . Definition 7. w(T − 1).3. u.5 The stochastic viability problem Here we address the issue of state constraints in the probabilistic sense. Stochastic viable controls and state Probabilistic notations and assumptions are detailed in Sect. 3 Notice that the notation Viab1 (t0 ) is consistent with that of the robust kernel in (7. .d. This is basically related to risk assessment which includes. there exists u ∈ Uad such that Viabβ (t0 ) := x0 ∈ X P w(·) ∈ Ω | x(t) ∈ A(t) for t = t0 . 4. . 6. w(t0 + 1). .7. . Thus. in the field of conserva- tion biology. In the robust setting. . the state constraints (7. In the stochastic case. Uad as defined in (7. T ≥ β . .2. it is the set of initial states x0 such that the stochastic viability property holds true. .3) is now the set of measurable admissible feedbacks. all the objects considered will be implicitly equipped with appropriate measurability properties. Stochastic viable feedbacks are feedback controls that allow the stochastic viability property to hold true.) random variables w(t0 ). one can relax the previous requirement by satisfying the state constraints along time with a given confidence level: P w(·) ∈ Ω | x(t) ∈ A(t) for t = t0 . w(·)](t) defined in Sect. the problems and methods of population viability analysis (pva) and requires some specific tools inspired by the viability and invariance ap- proach already exposed for the certain case in Chap. . 7. .4) when Ω is countable and that every scenario w(·) has strictly positive probability under P. we adapt the notions of viability kernel and vi- able controls.
F t. Assume that the primitive random process w(·) is made of independent and identically distributed (i.) random variables w(t0 ). Sect. x) := 1A(t) (x) sup Ew(t) V t + 1. F (t. associated with dynamics (7.10.2b) and (7.1). x.5. . . u∈B(t. (7. w(t) . w(t)))] = S V (t + 1. x) := 1A(T ) (x) . w))dμ(w). x). The stochastic viability value function is the maximal viability probability defined as follows. Definition 7.x) Stochastic viable feedbacks The backward equation of dynamic programming (7. It turns out that the stochastic viability functions are related to the stochastic viability kernels. x). .184 7 Robust and stochastic viability Definition 7.2c) is defined by the following back- ward induction5 .d. 6. Stochastic dynamic programming equation Consider state and target constraints as in (7. F (t. Hence. Proposition 7. . Stochastic viable feedbacks are those u ∈ Uad for which the above relations hold true4 4 3 ad Uviab β (t0 . x.2c). T ≥ β .8. x0 ) = ∅ . The stochastic viability value function or Bellman function V (t. u. x0 ) := u ∈ U P w(·) ∈ Ω | x(t) ∈ A(t) for t = t0 . u.i.10 is given in the Appendix. x0 .9.2a) state con- straints (7. Similarly to the robust case. 9 : (7.2. and that dynamic pro- gramming induction reveals relevant stochastic feedback controls.2b) and target constraints (7. w(t0 + 4 See the previous footnote 3 in this Chapter for the case β = 1. .18) makes it possible to define the value function V (t. x. u. A. u. we have the following strong link between viable stochastic feedbacks and the viability kernel: x0 ∈ Viabβ (t0 ) ⇐⇒ Uviab β (t0 . we have the formula Ew(t) [V (t + 1. control constraints (7. The proof of the following Proposition 7.17) where x(t) corresponds to the solution map x(t) = xF [t0 . where t runs from T − 1 down to t0 : ⎧ ⎪ ⎨ V (T. 5 All random variables w(t) have the same distribution μ and take values from the same domain S.18) ⎪ ⎩ V (t. w(·)](t) defined in Sect.
• Assessing vulnerability. pva may reveal that population viability is insensitive to particular parameters. 7. A population abundance N (t) evolves according to N (t + 1) = 1 + r N (t). • Ranking management options. The longer term objective is to promote conditions under which species retain their potential for evolutionary change without intensive management. We consider a model similar to that of agricultural land-use introduced in Sect. w(t) (7. w(t) N (t) − h(t) . Research may be guided by targeting factors that may have an important impact on extinction probabilities or on the rank order of management options.19) For any time t and state x. . 9.20) u∈B(t. Population viability analysis is often oriented towards the conservation and management of rare and threatened species. x0 ) for x0 ∈ Viabβ (t0 ). . x) belongs to β (t0 . pva may be used to address three aspects of threatened species management. u. economic imper- atives and taxonomic uniqueness. let us assume that 9 : Bviab (t. Within this context. . . any u ∈ U such that u (t. . weed control. with the goal of applying the principles of population ecology to improve their chances of survival. pva may be used to set policies and priorities for allocating scarce conservation resources. Uviab 7. x0 ) ≥ β ⇐⇒ x0 ∈ Viabβ (t0 ) . Then. Together with cultural priorities. 6. w(T −1).6 From PVA to CVA 185 1). We here advocate the use of a cva (Co-Viability Analysis) approach com- bining pva and viable control frameworks. captive breeding. The short term objective is to minimize the risk of extinction. x) ∈ Bviab (t. (7. pva may be used to predict the likely re- sponse of species to reintroduction.6 and perform a stochastic analysis. The viability kernel at confidence level β is the section of level β of the stochastic value function: V (t0 . 8.x) is not empty. or different designs for nature reserves or corridor networks. habitat rehabilitation. x) := arg max 1A(t) (x)Ew(t) V t + 1. prescribed burning. • Planning research and data collection.6 From PVA to CVA Population viability analysis (pva) is a process of identifying the threats faced by a species and evaluating the likelihood that it will persist for a given time into the future [2. F t. x. 10]. Threatened species management has two broad objectives. w(T ) .
8 0. 7.186 7 Robust and stochastic viability where h(t) are catches of the resource and r N (t).2 and N = 1 respectively. Maximal viability probability V (0. Environmental stochasticity causes r to fluctuate randomly in time with mean r and variance σe2 . w(t) is σ 2 (N (t)) = σe2 + N (t) .4 0. w(t) the uncertain growth rate of the population. The time horizon is set to T = 250.1 0.3 0.7 0. +∞[.5 . w(t) = 1 with probability 1 − p = 0.5 0. Assume now that the uncertainty is specified by the following distribution: −1 with probability p = 0.6 probability 0. The stochastic viability kernel is Viabβ (0) = {N0 . N (t) where w(·) is an i. V (0. The regulating agency aims at ensuring a minimal catch h at every time h(t) ≥ h .0 0 100 200 300 400 500 600 700 800 900 1000 initial abundance Fig. A probabilistic structure on growth rate r N (t). N0 ) as a function of population N0 . σ2 r(N (t). so that the total variance in mean σd2 fitness or population growth r N (t).9 0.3. together with a precautionary stock N at final time T with a confidence level β in the sense that: P N (T ) ≥ N ≥ β .5 .d. Demographic (individual) stochasticity is character- ized by the variance in individual fitness σd2 . Maximal probability viability 1. w(t) is assumed with w(t) including both environmental and demographic stochas- ticity. N0 ) ≥ β} = [Nβ .i.2 0. .0 0. The guaranteed catches and population are h = 0. w(t)) = r + σe2 + d w(t) . We write this as . sequence of random variables.
The straight line corresponds to the certain trajectory. N0 ) rises with confi- dence level β while the stochastic viability kernel Viabβ (0) = {N0 .6 From PVA to CVA 187 N(t) 3 10 2 10 1 10 0 t 10 50 100 150 200 250 N(t) Ncertain Nmin Nmax (a) N0 = 100 ∈ Viab80% : viability at 80%. The Fig.3. built with Scilab code 15. demographic σd = 10% and environmental σe = 20% standard deviations. The Figures are generated with Scilab code 15. 7. The dynamic parameters are mean growth r = 3%. +∞[ decreases with it. 7.2 for two initial sizes of N0 ∈ Viab80% (a) and N0 ∈ Viab90% (b) individuals subject to stochastic and environmental stochasticity w(t). Ten simulated trajectories N (t) of a population with guaranteed catches h = 0.2. demographic σd = 10% and environmental σe = 20% standard deviations. Not surprisingly.4. The dynamic parameters are mean growth r = 3%. 7. . we exhibit simulated trajectories N (t) of a population with an initial size of N0 = 100 ∈ Viab80% (0) (a) or N0 = 200 ∈ Viab90% (0) (b) individuals subject to stochastic and environmental stochasticity w(·) for guaranteed catch h(t) ≥ 0. N(t) 3 10 2 10 1 10 0 t 10 50 100 150 200 250 N(t) Ncertain Nmin Nmax (b) N0 = 200 ∈ Viab90% : viability at 90% Fig.4. N0 ) with guaranteed catch h = 0. the viability probability V (0. N0 ) ≥ β} = [Nβ . In Figs. plots the maximal co-viability probability V (0. 7. V (0.2 as a function of popula- tion N0 .
Some trajectories are not viable in the population sense since extinctions occur. the larger the probability of viability. .188 7 Robust and stochastic viability The straight line corresponds to the certain trajectory. The larger the initial abundance.
. for (i=1:NN) W(Horizon. // exec proba_extinction.delta_x=1.2.h_viab(t).end. // xtitle("Maximal viability probability". while(W(1.. rbar=0."Nmin".[traj_x Nmin Nmax NLin].Horizon.2).2)..-4. g_max(j)=-Phi_u(t. j_opt(t.w_max)).x_max).-4.’time t’.xbasc(1).h_max=0. end. ///////////////////////////////////// //////////////////////////////////////////////////// // Grid state x // Simulations x_min=0. N_min=1.* for(t=Horizon-1:-1:1) w(x>=N_min)).0. xbasc(3).x) W(t.p=0.i(1))<threshold_viab ) then i(1)=int(rand(1)*(NN-1))+1. // Characteristic function of control constraint (approximate) function [y]=Phi_u(t.. xset("window".2.^Tempx’. xtitle("Population".[traj_x Nmin Nmax NLin].x.style=-[1.xx.sce ’x’. ///////////////////////////////////// "probability").3. end..-[1. sig_e=0. /////////////////// else " beta kernel is empty " end xset("window"..N_max]). endfunction end.Viab. for (i=1:NN) // zero when x < N_min xx=Etat_x(i).."Ncertain"]. // Discretized dynamics Nmin=zeros(1.dyna(xx. // .Etat_x(i)).5). function y=dynpop(x. h_min=0.Horizon)’+N_max."initial abundance". function y=Ind_x(t..2.. Temps=1:Horizon-1. rect=[1. // z=Indice(P).’time t’. traj_x(t+1)=Etat_x(i(t+1)). else w(t)=w_max.x_max. endfunction for (j=MM:-1:1) uu=Control_u(j). threshold_viab=0.uu.K=1-W(Horizon.1]). xset("window".3../z)^0.2.w_min)).i(t))).:)’. // Bellman equation y(x>=N_min)= z. // Initialization at horizon T // time horizon Horizon=250 .6 From PVA to CVA 189 Scilab code 15..N_min. xsuiv=dynpop(x-h.w(t)).:)) >= threshold_viab) then u_min=0.u_max]).w_max=1. plot2d(Tempx. sig_d=0. i=int((x-x_min).4].uu)+W(t+1.uu.’N(t)’).plot2d(Tempx. endfunction plot2d(Etat_x. // N0=200. rect=[1.03. Viab=W(1.i)=Ind_x(Horizon.1.i)=Vopt.5.8 // Grid control if (max(W(1.h) // Viability kernel SGN = bool2s(h_min <= h) . //traj_x(1)=N0. y=0*SGN + 1/%eps *(1-SGN) . Tempx=(1:Horizon)-1.’h(t)’)./delta_x).w). x_max=N_max.w) g_min(j)=-Phi_u(t.2. z=min(z..Horizon. function [z]=Projbis(x) // find viable state x(i(1)) z=round(x. NLin=traj_x(1)*(1+rbar)... h_viab(t)=Control_u(j_opt(t. //////////////////////////////////////////////////// grille_x=x_min:delta_x:x_max.. function y=dyna_exp(x. xbasc(2). P=Projbis(xsuiv).. Etat_x(ii)=x_min+(ii-1)*delta_x.plot2d(Temps. for (ii=1:NN) xset("window".Horizon)’+N_min.h.compt=0."lr").NN). NN=S(2)..jopt]=max(g) .05. N_max=10^3. function i=Indice(x) i(t+1)=dyna(traj_x(t)..uu)+W(t+1.w). w_min=-1.3. xtitle("Maximal probability viability". for (k=1:10) u=u_min:delta_u:u_max. i(1)=Indice(N0).3). end.i)=jopt. rect=[1. 7.1).:)’. // State and control Discretization // legends("Maximal probability viability". function [z]=dyna(x.’Max_{h}P(N(T)>=N_min)’). // demographic stochasticity parameters xset("window". endfunction [1.plot2d(Tempx.xx.q=1-p.x_min). // expected value end.delta_u=0.Horizon. W=zeros(Horizon. R=size(u)..h. // Ricker dynamics parameters /////////////////////// Cap=0. for (t=1:Horizon-1) endfunction if (rand(1)<p) then w(t)=w_min. z=x(x>=N_min). S=size(grille_x).h_viab. xtitle("Catches".*delta_x..w) end y=zeros(x).xbasc(1). // environmental stochasticity parameters xset("window". traj_x(1)=Etat_x(i(1)).[traj_x Nmin Nmax NLin]. xset("window". y=bool2s(x>=N_min).dyna(xx.1). MM=R(2).*(1+rbar+((sig_e^2+sig_d^2 . i(1)=int(rand(1)*(NN-1))+1.w) Nmax=zeros(1. u_max=h_max. Control_u(ii)=u_min+(ii-1)*delta_u."Nmax". y=dynpop(x-h.2. endfunction g(j)=p*g_min(j)+(1-p)*g_max(j). endfunction end.leg="N(t)@Nmin@Nmax@Ncertain".3).N_max]).rect=[0. end.4]) for (ii=1:MM) // STOP. z=max(z.N_min./delta_x)+1. // Dynamic programming // carrying capacity /////////////////////// // constraints thresholds x=grille_x. ////////////////// // Graphics end.2).4]) legends(["N(t)".u_min. // Indicator function of state constraint [Vopt.
M. Journal of Environmental Management. [5] L. 62(3):821–841. November 2007. Saether. Doyen. S. 1996. 49:99–112. Environmental Modeling and Assessment. R. Rainer. 2004. Quincampoix. Journal of Wildlife Management. 1998. Morris and D. The viability theorem for stochastic differ- ential inclusions. A viability model to assess the sustainability of mixed herd under climatic uncertainty. 16:1–15.-E. Genin. Buckdahn. 1998. Applied Mathematics and Optimization. Ferraris. Journal of Set-valued Anal- ysis. 69:1– 13. L. C. 2000. Lande. application to small time attain- ability of sets. Doyen and J. 8:149–162. Beissinger and M. Doak. S. Oxford series in ecology and evolution. 17(6):629–656. [7] L. [11] M. F. M. De Lara. Animal Research. [2] S. revision. Westphal. F.-C. and B. Quantitative Conservation Biology: Theory and Practice of Population Viability Analysis. Da Prato. 2003. Rascanu. J. Sustainability of fisheries through marine reserves: a robust modeling analysis. Stochastic control with exit time and contraints. Acta Oecologica. [3] R. Doyen. Matrix population models applied to viability analysis and conservation: theory and practice using the ULM software. Hubert. Ecological Modelling. and J. 208(2-4):353–366. Ferrière. and D. Béné. [10] W. [9] R. Guaranteed output feed-back control for nonlinear uncertain systems under state and control constraints. Stochastic population dynamics in ecology and conservation. Legendre. The precautionary principle as a robust cost- effectiveness problem. Stochastic Analysis and Applications. F.References [1] J. 53(5):405–417. [6] L. Pelletier. 2003. On the use of demographic models of population viability in endangered species management. Doyen. I. Baron. . 2003. [8] R. and D. Sustainability of ex- ploited marine ecosystems through protected areas: a viability model and a coral reef case study.-P Aubin and G. Pereau. [4] L. and A. 2004. Doyen and C. Sarrazin. Engen.-P. Sinauer Associates. Tichit. B.
2. Examples from natural resource modeling illustrate the abstract results and concepts.1. For the uncertain case. . that the so-called Bellman’s principle expresses the fact that every “subpolicy” of an optimal policy remains optimal along the optimal trajectories. 7]. when the criterion is additive [1. After briefly introducing the criterion in the uncertain framework in Sect. especially in- tergenerational equity and conservation issues. The stochastic optimality problem is detailed in Sect. 8. The robust additive payoff case is treated with the dynamic programming method in Sect. 8.8 Robust and stochastic optimization In Chap. In particular. it is worth noting that dynamic programming is a relevant method in the uncertain context in the sense that it is well-suited to both robust and stochastic problems. Such principle makes it possible to split a dynamic optimization problem into a sequence of static optimization problem interrelated by backward induction. Again. 8. The chapter is organised as follows. Green Golden and Chichilnisky ap- proaches. 8. Stochastic optimality approaches to address the sustainability issues and. it is shown how some qualitative results of the certain case can be expanded to the uncertain framework using the certainty equivalent. material for the optimal management or conservation of natural resource and bioeconomic modeling can be found in [4] together with [3]. 8. The present chapter focuses on the optimal- ity process involving worst case or expected performance. We detail this process and these general ideas hereafter in the robust and stochastic cases. as well as the robust “maximin” approach in Sect.3.6. viability issues were addressed in the uncertain context including both robust and stochastic cases. are proposed for instance in [5] including in particular the maximin. the robust optimality problem is pre- sented in Sect. 7. We have already seen in the certain case.2.5.
Dynamics The state equation introduced in (6. u(t). Possible scenarios. x) of admissible controls in U for all time t and state x. x(t). Constraints and feedbacks The admissibility of decisions and states is restricted by non empty subset B(t.12) Uad = {u ∈ U | u(t. . u(t) ∈ B t. feedbacks and criteria We briefly review some basic ingredients and conclude with the evaluation of the criterion along controlled trajectories. . state or target constraints may reduce the relevant paths of the system. (8. x(t) ∈ A(t) ⊂ X . ∀(t. . . x) ∈ B(t. . T − 1.1) where again x(t) ∈ X = Rn represents the system state vector at time t ∈ N. t = t0 . Such a feasibility issue will only be addressed in a robust frame- work.1) as the uncertain dynamic model is considered x(t + 1) = F t. T − 1 with x(t0 ) = x0 (8.194 8 Robust and stochastic optimization 8. . let us consider the set Uad of admissible feedbacks as defined in (6. . (8. constraints.2c) These control. x) ∈ N × X . or disturbance. x(t) ⊂ U . . w(·) are described by: w(·) ∈ Ω := S(t0 ) × · · · × S(T ) ⊂ WT +1−t0 . T > t0 is the horizon. (8. For this purpose. x)} . or paths of uncertainties.1 Dynamics.2a) together with a non empty subset A(t) of the state space X for all t = t0 . x0 ∈ X is the initial condition or initial state at initial time t0 . u(t) ∈ U = Rp represents the decision or the control vector while w(t) ∈ S(t) ⊂ W = Rq stands for the uncertain variable. w(t) . x) .3) where U = {u : (t.2b) and a target x(T ) ∈ A(T ) ⊂ X . (8. noise.
11). .→ u(t. x) ∈ U} is defined in (6.
8.4) where t0 ∈ {0. x0 . 8. . and aim at maximizing this worst pay- off (8. To address minimization problems. x(t) and disturbance scenario w(·). x0 . u. u. The robust optimization results that we shall present in the sequel may be ob- tained with any of these criteria. x0 ) u∈Uad (8. and generated by the dynamic (8. x0 ) := inf π u t0 .14). x0 . we fix an admissible feedback u. w(·) ∈ Ω and xF. w(·)](·). we introduce the worst perfor- mance as in (6. π u t0 . u. In the w(·) by considering the worst case.2 The robust optimality problem 195 Criterion Let us pick up one of the finite horizon criteria π defined previously in Sect.2. driven by feedback u(t) = u t. Thus. starting from x(t 0 ) =x0 . while the stochastic optimization results may be obtained only with the finite horizon additive and multiplicative criteria. w(·) is the evaluation of the criterion π along the unique trajectory x(·) = xF [t0 . u(·) w(·)∈Ω 1 Recall that π measures payoffs. w(·) := π xF [t0 . we let the scenario w(·) vary in Ω and evaluate the criterion by taking the lowest value. uF are the solu- tion maps introduced in Sect. w(·)](·). we let the feedback u vary. Maximal worst payoff Second. . w(·) . x0 . the feedback u being fixed. .5) w(·)∈Ω Thus. u(·) = uF [t0 . u. we put π u t0 . Then. and criterion π : XT +1−t0 × UT −t0 × WT +1−t0 → R. uF [t0 . x0 ) := sup π− (t0 .1). x0 . we aggregate the scenarios w(·) in π t0 .1. namely the minimal payoff1 with respect to the scenarios w(·) ∈ Ω: u π− (t0 . w(·) (8. w(·)](·). x0 . (8. x0 . w(·)](·). For any u ∈ Uad (measurable in the stochastic context). 6. . w(·) . one should simply change the sign and consider −π. Worst payoff First. 6. . u(·).2 The robust optimality problem u robust optimality problem. T − 1}.5) by solving the optimization problem u π− (t0 .6) = sup inf π x(·). x0 . x0 ∈ X.
. T ⎭ instead of Uad as defined in (8. Definition 8.x0 ) is an optimal viable feedback strategy.2. w(·) = L t. x0 . Given an initial condition x0 ∈ X. x0 ) = max π− (t0 . the infimum in (8.6) is taken for u ∈ Uviab 1 (t0 . the optimal value π− (t0 . w(·)](t) and which x(·) u(t) = u t. the maximal viable worst payoff is u π− (t0 . Definition 8. x0 ) (8. w(·)](t) ∈ A(t) . u. in and u(·) need to be replaced by x(t) = xF [t0 . u. x(t) . x0 ) = π− (t0 . .6) is called the maximal worst payoff and any u ∈ Uad such that u u π− (t0 . x0 ) (8.196 8 Robust and stochastic optimization where the last expression is abusively used.3).10) u∈Uviab 1 (t0 .8) ⎩ for t = t0 . x(t). Such principle facilitaties splitting one . x0 ) = max π− (t0 . 6. . x0 ) := u ∈ Uad xF [t0 .5). x0 ) in (8. . x0 .2. referring to state and control solution maps introduced in Sect. (8. Given an initial condition x0 ∈ X at time t0 .3 The robust additive payoff case In the robust additive payoff case. giving ⎧ ⎫ ⎨ for all scenario w(·) ∈ Ω ⎬ Uviab 1 (t0 . 8. x0 ) such that u u π− (t0 . x0 ) defined in (7. In the viability case. but practical and traditional. w(t) + M T.x0 ) and any u ∈ Uviab 1 (t0 . w(T ) .11) t=t0 Robust additive dynamic programming without state constraints We have already seen in the certain case that the so-called Bellman’s prin- ciple expresses the fact that every “subpolicy” of an optimal policy remains optimal along the optimal trajectories. we specify the criterion and consider the finite horizon additive criterion: −1 T π x(·).1. x(T ).9) u∈Uviab 1 (t0 .7) u∈Uad is an optimal feedback. x0 ) := sup π− (t0 . (8. x0 ) (8. x0 ) = π− (t0 . u(·). u(t).
.
12) makes it possible to define the value function V (t. the dynamics (8.14) Robust dynamic programming in the viability case When state constraints restrict the choice of relevant paths. the maximal worst payoff is given by u V (t0 . . It turns out that the value V (t0 .3 The robust additive payoff case 197 optimization problem over time (dynamic) into a sequence of static optimiza- tion problem interrelated by backward induction.x) Optimal robust feedbacks The backward equation of dynamic programming (8. x0 ) . . The value function is defined by backward induction as follows.11).2a).11). Here. x). assume the existence of the following feedback decision 6 7 u (t. u. We detail this process and these general ideas hereafter in the robust case. associated with the additive criterion (8. F (t. x) := sup inf L(t. 7. F (t. x. . namely A(t) = X. Assume that A(t) = X for t = t0 . In fact. w) . . Assume no state constraints. u.12) ⎪ ⎪ V (t. x. T . is defined by the following backward induction. x. Sect. w) + V t + 1.13) u∈B(t. w) . x. The proof of the following Proposition 8. we obtain a stronger result since dynamic programming induction maximization reveals relevant robust feedback controls. Definition 8. The value function or Bellman functionV (t. x0 ) = π− (t0 . when the criterion π is addi- tive. x. 8.6).4 is given in the Appendix. ⎩ w∈S(t) u∈B(t. x). For any time t and state x. x) ∈ arg max inf L(t.x) w∈S(t) Then u ∈ U is an optimal feedback of the robust problem (8. T . . x0 ) coincides with the maximal worst payoff π− (t0 .11). A. x0 ). w) + V t + 1.1) and control constraints (8.4. (8. that is. . w) . x) := inf M (T. (8. for any initial state x0 . we have to adapt the dynamic programming equation using viability tools and especially the robust viability kernel Viab1 introduced in Chap. that is A(t) = X for t = t0 . Proposition 8. where π is given by (8. . The value function is defined by backward induction as follows. x0 ) = π− (t0 .3. and. u. ⎨ w∈S(T ) 6 7 (8. u. given by (8.6. we restrict the study to the case without state constraints. . where t runs from T − 1 down to t0 : ⎧ ⎪ ⎪ V (T. .
For any time t = t0 . x. The proof2 of the following Proposition 8. ∀w ∈ S(t) . and where the supremum in (8.19) 2 For the proof.15) is over viable controls in Bviab 1 (t. u. is defined by the follow- ing backward induction. where π is given by (8. ⎪ ⎨ 9 : V (t.x) w∈S(t) ∀x ∈ Viab1 (t) . x. w > −∞. u. A. x) ∈ arg max inf L(t. x0 ).6. x0 ) . Proposition 8. the dynamics (8. x) | ∀w ∈ S(t) . and. x) given by 1 (t.15) makes it possible to define the value function V (t.9).6. assume the existence of the following feedback decision 9 : u (t. u.15) where Viab1 (t) is given by the backward induction (7. x0 ) coin- cides with the maximal worst payoff π− (t0 . w) ∈ Viab1 (t + 1)} . (8.2b) and target constraints (8. w) . ⎨ Viab1 (t) = {x ∈ A(t) | ∃u ∈ B(t. u. w) ∈ Viab1 (t + 1)} .16) ⎪ ⎪ ⎩ F (t. It turns out that the value V (t0 . the maximal viable worst payoff is given by u V (t0 .18) u∈Bviab w∈S(t) 1 (t. . x. . . w) .u. x.2a). x. x) := M (T.5. T − 1 and state x ∈ Viab1 (t). where t runs from T − 1 down to t0 . x) .17) Bviab Optimal robust viable feedbacks The backward equation of dynamic programming (8. . F (t. Sect. . we obtain a stronger result since dynamic programming induction maximization reveals relevant feedbacks. x). x. F (t.2c). u.11). ⎪ ⎪ ⎪ ⎩ u∈Bviab 1 (t. In fact. associated with the additive criterion (8. w > −∞ and inf x. F (t. ⎧ ⎪ ⎪ V (T.198 8 Robust and stochastic optimization Definition 8. (8.w M T. we require additional technical assumptions: inf x. ∀x ∈ Viab1 (T ) = A(T ) .6 is given in the Appendix. x. w) + V t + 1. x0 ) = π− (t0 . x). x) := sup inf L(t.1). (8.11) ⎧ ⎪ ⎪ Viab1 (T ) = A(T ) . w) + V t + 1. for any initial state x0 . x) = {u ∈ B(t. x0 ) = π− (t0 . The value function or Bellman functionV (t. x. u. (8.w L t. state constraints (8.x) Then u ∈ U is an optimal feedback of the viable robust problem (8.11). x) . u. (8. control constraints (8.
4 Robust harvest of a renewable resource over two periods 199 Hence. one has 0 1 V (0. B(2) = R(2) B(1) − h(1) . R ] ⊂ W = R. B) = sup inf ρph + V 2. R(1)(B − h) 0≤h≤B R(1)∈[R .R ] 0≤h≤B 4 3 = p sup h(1 − ρR ) + ρR B 0≤h≤B where R = inf R(1)∈[R . • Time t = 0. B) = 0. . B) = sup inf ph + V 1. We aim at maximizing the worst benefit namely the minimal sum of the discounted successive harvesting revenues 6 7 sup inf ph(0) + ρph(1) . The uncertain resource productivity R(t) is supposed to vary within an interval S = [R . with R < R . B) = ⎩ 0 if ρR > 1 and the value function is ⎧ ⎨ pB if ρR < 1 V (0. By virtue of dynamic programming equation (8.R(2) where the resource dynamics corresponds to B(1) = R(1) B(0) − h(0) . • Final time t = T = 2. 8. one has 0 1 V (1. B) = ρpB . B) = B while the value function is V (1.12). The robust value function is V (2. This will no longer be the situation in the stochastic case. The optimality problem over h is linear and we obtain ⎧ ⎨ B if ρR < 1 u (0. 0≤h(0)≤B(0).R ] 0≤h≤B The optimality problem over h is linear and we obtain similarly the optimal feedback u (1.R ] R(1). 8. B) = ⎩ ρpR B if ρR > 1 .4 Robust harvest of a renewable resource over two periods We consider a model of the management of a renewable resource over two periods T = 2 and we perform a robust analysis. there is no theoretical problem in coupling viability and optimality requirements in the robust framework.R ] ) * = sup ph + inf [ρpR(1)(B − h)] R(1)∈[R . By virtue of dynamic programming equation (8. R(2)(B − h) = sup {ρph} . 0≤h≤B R(2)∈[R . 0≤h(1)≤B(1) R(1). • Time t = 1.12).
We deduce that sustainability is even more difficult to achieve in such a robust framework.. .. control constraints (8. the results are similar to the certain case using the worst equivalent R .200 8 Robust and stochastic optimization Thus. x) := sup inf min L(t. The value function is defined by backward induction as follows. x(t).20) t=t0 .2a). . x. The value function or Bellman functionV (t. x(T ). u. M T.. x). u(t). w(·) = min min L t.. t=t0 . 8. The proof of the following Proposition 8. associated with the maximin criterion (8. Definition 8. u. x. u(·)... w).6. A. x.7. u.21) makes it possible to define the value function V (t. w) . we consider the finite horizon maximin criterion π x(·). x) := inf M (T. In fact. x(t). .. x0 ) coin- cides with the maximal worst payoff π− (t0 . . w . Robust dynamic programming equation We state the results without state constraints.5 The robust “maximin” approach Here. w(t) . Assume no state constraints A(t) = X for t ∈ {t0 . is defined by the following backward induction. where t runs from T − 1 down to t0 : ⎧ ⎪ ⎨ V (T. T }. w) = M T. u(·). though robust ones would not pose problems. w(T ) . u(t).20).. u∈B(t. . x.21) ⎪ ⎩ V (t. Sect.8 is given in the Appendix.T −1 However. w(·) = inf L t. It turns out that the value V (t0 .1). x. by changing T in T + 1 and defining L(T. F (t. we obtain a stronger result since dynamic programming induction maximization reveals relevant feedbacks. the dynamics (8.x) w∈S(t) Optimal robust feedbacks The backward equation of dynamic programming (8. w) . V t + 1.T −1 We shall also consider the final payoff case with & ' π x(·). x). x0 ). w(t) . the minimax with final payoff may be interpreted as one without on a longer time horizon. (8. w∈S(T ) (8.
(8. w).20). (8. . T .6). V t + 1. w(T − 1). x0 ) := sup E π t0 . x0 ) = π− (t0 . x) ⊂ U be a non empty subset of the control space U for all (t. . For any admissible feedback strategy u ∈ Uad and initial condition x0 ∈ X at time t0 . and. Mean payoff We aim at computing the optimal expected value of the criterion π. . and Uad be the set of measurable admissible feedbacks as defined in (8. where π is given by (8. u(·) .22) u∈B(t.) random variables w(t0 ).6 The stochastic optimality problem Suppose that L and M in (8. w(·) u u∈Uad6 7 (8. In all that follows.3 are satisfied. w(·) .d. For any time t and state x. w(T ) under probability P on the domain of scenarios Ω = ST +1−t0 . x.25) = sup E π x(·). . x. x0 ) . x). we aim at identifying the maximal mean payoffs and the associated feedbacks or pure Markovian strategies. x0 ) = π− (t0 . the primitive random process w(·) is assumed to be a sequence of independent identically distributed (i. u(·). (8. let us consider the or mean payoff as in (6. . x0 .15): 6 7 π u (t0 . u. 8. Assume that A(t) = X for t = t0 .23) 8. . u. Suppose that the assumptions in Sect.3).8. .i. . . Let B(t. F (t. x0 ) := E π u t0 . x) ∈ arg max inf min L(t. w) .24) Maximal mean payoff The stochastic optimization problem is 6 7 π (t0 . 6. As long as the criterion π represents payoffs.11) are measurable and either bounded or non- negative so as to be integrable when composed with measurable state and decision maps. the maximal worst payoff is given by u V (t0 .6 The stochastic optimality problem 201 Proposition 8.x) w∈S(t) Then u ∈ U is an optimal feedback of the robust problem (8. assume the existence of the following feedback decision u (t. x0 . w(t0 + 1). for any initial state x0 . w(·) .
11) is additive. the maximum in (8. . let us emphasize that the stochastic optimality problem with stochastic state constraints is not easy to cope with and that substantial mathematical difficulties arise. the maximal viable mean payoff is u π− (t0 . x0 ) in (8.10. instead of Uad as defined in (8. x0 ) = π u (t0 . x(t) . T = 1 . Definition 8. Consider any initial condition x0 ∈ X. the expectation operator is linear. . 6.28) u∈Uviab 1 (t0 . This is why we restrict the viability problem to the robust approach. x0 ) defined as follows 3 4 3 Uviab 1 (t0 . namely A(t) = X for t = t0 .26) u∈Uad is an optimal feedback. but practical and traditional.2.2. w(·)](t) defined in Sect. x0 ) = max π− (t0 . 6.x0 ) is an optimal viable feedback.3). 3 See the footnotes 3 and 4 in the previous Chap. x0 ) = max π u (t0 . T . .9.25) is taken for robust feedbacks u ∈ Uviab 1 (t0 . u. . constraints at time t depend only on time t and state x. x0 . The optimal value π (t0 . . Hence. Stochastic dynamic programming without state constraints We first restrict the study to the case without state constraints. u. the dynamic is a first order induction equation and. x0 ) := u ∈ Uad P w(·) ∈ Ω | x(t) ∈ A(t) for t = t0 .25) is called the maximal expected payoff or maximal mean payoff and any u ∈ Uad such that π (t0 . Definition 8. . . finally.27) where x(t) corresponds to the solution map x(t) = xF [t0 . Given an initial condition x0 ∈ X. . w(·)](t) and which x(·) u(t) = u t. referring to state and control solution maps introduced in Sect. In the viability case where state constraints reduce the admissibility of de- cisions and feedbacks. .202 8 Robust and stochastic optimization where the last expression is abusively used. x0 ) such that u u π− (t0 .29) u∈Uviab 1 (t0 . (8. x0 ) = π− (t0 . x) and we can split up the maximization operation into two parts for the following reasons: the criterion π in (8. x0 ) (8. Again a backward inductive equation defines the value function V (t. in and u(·) need to be replaced by x(t) = xF [t0 . x0 ) (8. 7. x0 . x0 ) (8.x0 ) and any u ∈ Uviab 1 (t0 . x0 ) := sup π− (t0 .
the optimal expected payoff is given by: V (t0 . x. w(t) + V t + 1. . x) := sup Ew(t) L t. The value function or Bellman functionV (t. .12 is given in the Appendix. u. u. x). . assuming the additional hypothesis that the infimum is achieved in (8.x) If u : (t. (8. 9 : ⎪ ⎪ ⎩ V (t. u. w(T ) . is defined by the following backward induction4 . associ- ated with the additive criterion (8. x) := Ew(T ) M T. . x.6 The stochastic optimality problem 203 Definition 8. u∈B(t.11). then u (t. T . The proof of the following Proposition 8. for any initial state x0 . we thus have an optimal strategy of the maximization problem (8.32) Stochastic dynamic programming with state constraints If we introduce state constraints and deal with them in a robust sense.11) and. x).30) makes it possible to define the value function V (t. assume the existence of the following feedback decision: 6 7 u (t. . x) → u (t. F (t. Proposition 8. x0 ) = π u (t0 . control con- straints (8. x. if we denote by u (t. x. .31) u∈B(t. Indeed.1). x0 ) = π (t0 . w(t) + V t + 1. Moreover. A. the dynamics (8. w(t) . 4 See the footnote 5 in Definition 7. It turns out that the value V (t0 . x).30) for at least one decision. x) is measurable. where t runs from T − 1 down to t0 : ⎧ 6 7 ⎪ ⎪ ⎨ V (T. where π is given by (8.30) Stochastic optimal feedback The backward equation of dynamic programming (8. Assume that A(t) = X for t = t0 .6. the hereabove results hold true with B(t. For any time t and state x. x) is an optimal feedback for the optimal control problem in the following sense.x) (8. 8. dynamic programming induction maximization reveals relevant feedback controls or pure Markovian strategies. x0 ) . x0 ) at time t0 coincides with the optimal mean payoff π (t0 . x0 ).9. u. . F t. x) which achieves the maximum in equation (8. w) . Sect. x) ∈ arg max Ew(t) L t. x) replaced by Bviab 1 (t.11. x) a value u ∈ B(t. .2a) and no state constraints (A(t) = X for t = t0 . . T ).30).12.25). x. (8.
associ- ated with the additive criterion (8. and where the supremum in (8. x) . F t. x). x) = {u ∈ B(t.13. w(T ) . x. and. (8. maximal payoffs are smaller in a robust perspective than in a mean approach since the inequality 5 For the proof. we thus have an optimal strategy of the maximization problem (8. x) given by 1 (t.36) If u : (t. w) ∈ Viab1 (t + 1)} .11). ⎪ ⎨ Viab1 (t) = {x ∈ A(t) | ∃u ∈ B(t. x.6.33) is over viable controls in Bviab 1 (t. where π is given by (8. ∀x ∈ Viab1 (T ) = A(T ) . The value function or Bellman functionV (t. x) is measurable. F (t.2b) and target constraints (8. ⎧ 6 7 ⎪ ⎪ ⎪ V (T.2a).x) ∀x ∈ Viab1 (t) . x. is defined by the following backward induction. x. For any time t and state x.14. w) ∈ Viab1 (t + 1)} .11). x0 ) = π u (t0 . ⎪ ⎨ 6 7 ⎪ ⎪ V (t. x) → u (t.1). x. w(t) + V t + 1. u.x) (8. u. (8.33) where Viab1 (t) is given by the backward induction (7. w(t) + V t + 1. Sect.37) Robust is more stringent than stochastic Not surprisingly. x) | ∀w ∈ S(t) . u. (8. x. x0 ) . ⎪ ⎪ w(t) ⎩ u∈B(t. u. assume the existence of the following feedback decision 6 7 u (t. for any initial state x0 .35) Bviab The proof5 of the following Proposition 8.204 8 Robust and stochastic optimization Definition 8. ∀w ∈ S(t) . x0 ) = π (t0 . u∈Bviab 1 (t.11) ⎧ ⎪ ⎪ Viab1 (T ) = A(T ) . x) ∈ arg max Ew(t) L t.14 is given in the Appendix. control con- straints (8. w(t) . state constraints (8.2c). Proposition 8. w(t) . F t. the optimal expected payoff is given by: V (t0 . where t runs from T − 1 down to t0 . x) := Ew(T ) M T.28).34) ⎪ ⎪ ⎪ ⎩ F (t. we require the additional technical assumptions that L and M are bounded. (8. A. x) := sup E L t. . u. x. u. the dynamics (8.
The value function is V (2.7 Stochastic management of a renewable resource Over two periods We consider the biomass linear model over two periods T = 2. R(1)(B − h) 0≤h≤B . the robust and stochastic maximization problems coincide whenever the uncertainty disappears. B(0)) = sup ER(1). B(1) = R(1) B(0) − h(0) . / = sup ph + ER(1) [ρpR(1)(B − h))] 0≤h≤B . In the certain case where S = {w}. 0≤h≤B 0≤h≤B The optimality problem over h is linear and we obtain the optimal feedback harvesting u (1. R(2)(B − h) = sup {ρph} . x0 ) = π (t0 . one has 0 1 V (0. Moreover. 8. which corresponds to the determinis- tic case. B(2) = R(2) B(1) − h(1) . By virtue of dynamic programming equation (8.30). B) = sup ER(1) ph + V 1. By (8.R(2) ph(0) + ρph(1) . • Time t = 0. 0≤h(0)≤B(0). B) = 0. x0 ) ≥ π− (t0 . • Time t = 1. for which we aim at maximizing the expectation of the sum of the discounted successive harvesting revenues 6 7 V (0. the maximal expected payoff and the maximal worst payoff coincide: S = {w} =⇒ π− (t0 . 0≤h(1)≤B(1) where R(1) and R(2) are two independent random variables.7 Stochastic management of a renewable resource 205 Ew [A(w)] ≥ inf A(w) w∈S holds. B) = ρpB . B) = B while the value function is: V (1.30). for any initial state x0 . x0 ) . • Final time t = T = 2. / = p sup h(1 − ρR) + ρRB 0≤h≤B . Thus. B) = sup ER(2) ρph + V 2. x0 ) . one has: 0 1 V (1. the maximal expected payoff is larger than the maximal worst payoff: π (t0 . 8.
B) = sup ρt L(h) + ER V t + 1.. T − 1. . B) are characterized by .h(T −1) t=t0 We restrict the study to the isoelastic case where L(h) = hη with 0<η<1. B) = ⎩ 0 if ρR > 1 . .30) gives 0 1 V (t. dynamic programming equation (8. The value function is ⎧ ⎨ pB if ρR < 1 V (0. . . Using a backward induction starting from V (T. it turns out that the optimal strategies of harvesting h (t. R(T − 1). Thus the results are similar to the certain case using the certainty equivalent R. • conservation problems are stronger if R is weaker since the resource is completely harvested at the first period in this case. B) = ρT L(B). . Over T periods The dynamic model still is B(t + 1) = R(t) B(t) − h(t) . . ..B] where R is a random variable standing for the uncertain growth of the resource and having the same distribution as any of the random variables R(t0 ). . R(T − 1) are independent and identically distributed posi- tive random variables. h∈[0. B) along with the value function V (t. 0 ≤ h(t) ≤ B(t) . • no intergenerational equity occurs since either the whole resource is cap- tured in the first or second period. The optimality problem over h is linear and we obtain: ⎧ ⎨ B if ρR < 1 u (0. . we deduce that: • the resource B becomes extinct in at least in two periods.206 8 Robust and stochastic optimization where R = E [R(1)]. . . R(B − h) .. For t = t0 . Consequently. We consider expected intertemporal discounted utility maximization +T −1 - sup E t T ρ L h(t) + ρ L B(t) .. h(t0 ). . B) = ⎩ pρRB if ρR > 1 . where R(t0 ).
9 0.95 while initial biomass is B0 = 10. Resource growth parameters R = 1.8 0. b(T ) = 1 .6 0 1 2 3 4 5 6 7 8 9 10 time t (b) Optimal catches h (t) Fig.3) = 0. The recursive relation revealing b(t) is given by ab(t + 1) b(t) = . 1 + ab(t + 1) depending on the term <η ) η−1 a = (ρR 1 .3 1.1 1. where the certainty equivalent R< is defined by the implicit equation (the utility function L(h) = hη is strictly increasing) .3. 8.7 Stochastic management of a renewable resource 207 Optimal biomass 10 9 8 7 6 B(t) 5 4 3 2 1 0 1 2 3 4 5 6 7 8 9 10 11 time t (a) Optimal biomasses B (t) Optimal catch 1. B) = b(t)B .1. B) = ρt b(t)η−1 B η and h (t. Consequently. V (t.7 0.1.028 and sustainability problems occurs as catches are strong for first periods and resource is exhausted. certainty equivalent is R < ≈ 1. R = 1 and p = P(R = 1.5 .0 h(t) 0.2 1. discount factor ρ = 0. 8. Preference for present: optimal stochastic paths B (t) and h (t) over time horizon T = 10 with catch utility function L(h) = h0.
9. 8. a a Since L(h) = hη . Preference for future: optimal stochastic paths B (t) and h (t) over time horizon T = 10 with catch utility function L(h) = h0.3.3) = 0. R = 1 and < = 1. Thus resource certainty equivalent is R problems occurs as catches are weak for first periods.26. L(R) (8.208 8 Robust and stochastic optimization Optimal biomass 40 35 30 25 B(t) 20 15 10 5 1 2 3 4 5 6 7 8 9 10 11 time t (a) Optimal biomasses B (t) Optimal catch 20 15 h(t) 10 5 0 0 1 2 3 4 5 6 7 8 9 10 time t (b) Optimal catches h (t) Fig. < = ER [L(R)] . we obtain that . Resource parameters are R = 1. h (t) = h t.5 . discount factor ρ = 0.38) Optimal stochastic biomasses B (t) and catches h (t) are defined by B (t + 1) = R(t) B (t) − h (t) . B (t) = b(t)B (t) . Sustainability p = P(R = 1.95 while initial biomass is B0 = 10.2. which gives R(t)b(t) R(t) h (t+1) = b(t+1)B (t+1) = b(t+1)R(t)B (t)(1−b(t)) = B (t) = h (t).
L h (t) < < 1. we have P(R = 1. then the utility of optimal stochastic catches remains stationary 3. so that the resource stocks B (t) quickly decrease.3) = 0. In the second case displayed by Fig.39) !"#$ !"#$ economic discount factor biological growth factor which mixes economic and biological characteristics of the problem. If ρR time in the mean following sense: + - L h (t + 1) E >1. However a problem of intergenerational equity appears since the catches h (t) are very weak (al- most zero) for the first periods before they quickly increase at the end of the concerned period.9 yields the certainty equivalent R< = 1. intergenerational equity is not guaranteed. 8. 8. If ρR in the mean following sense: + - L h (t + 1) E =1. As a consequence.028. There is a clear preference for the future.3) = 0. If ρR time in the mean following sense: + - L h (t + 1) E <1. <η ) η−1 η L(h (t)) L(a) L(a) (ρR It turns out that the sustainability issues depend critically upon the product ρ × R< (8. 8. 8.3 and R = 1. . then the utility of optimal stochastic catches increases along 1. resource natural growth features are more favorable and P(R = 1.1 and thus R <= 1. there is a preference for the present which condemns the conservation of both the resource and exploitation. In the first case depicted by Fig. Result 8. In such a case.1 and 8.26: conservation of the resource is achieved. It is assumed that resource productivity R is a random variable taking values R = 1.7 Stochastic management of a renewable resource 209 6 7 < <η 1−η ER [L(R)] L(R) η L(h (t + 1)) R < ER = = = = ρR .2.15 The relative variation of the utility of optimal stochastic catches < as follows. then the utility of optimal stochastic catches decreases along 2.1 where the uncertain resource natural growth features are not favorable. depends on the index ρR < > 1. L h (t) Figs.2 show that sustainability problems occur with such optimal stochastic catches. L h (t) < = 1. Similarly. the catches h (t) decrease and tend to collapse.
Horizon."h(t)") h =b(t)*B endfunction end function [x]=DYN_OPT(t.210 8 Robust and stochastic optimization Scilab code 16. .3. for t=1: Horizon // certainty equivalent hopt(t)=PREL_OPT(t. if (z(t) <= p) then Rsimu(t)=R#. plot2d(1:Horizon+1.1) . p=0.95 .Bopt. q=1-p. end a=(rho * util(Rchap))^(1/(puis-1)) .1. R w(t) . end xset("window".hopt. for t=1:Horizon p=0. pi Bi (t) ui (t) := υ(t) . B0=10."time t". N_simu=3.Bopt(t)). for t=Horizon:-1:1 xtitle("Optimal biomass". plot2d(1:Horizon.B) xtitle("Optimal catch".sce xset("window"."time t".hopt.B. Rchap=(p*util(R#)+q*util(Rb))^(1/puis) .Rsimu(t)). // graphics // proportion of consumption b(t) xset("window".J=0. .2) .8 Optimal expected land-use and specialization We now cope with the problem introduced in Sect.R) x=R*(B-PREL_OPT(t. else Rsimu(t)=Rb.Bopt. // simulation of random productivity R(t) z=rand(1.style=-i) . plot2d(1:Horizon+1.style=i) . 6.1) . q=1-p. xbasc() //parameters puis=0. Rn (w) and .6. . xbasc() xset("window". b(Horizon+1)=1.style=-i) . denotes scalar product on Rn .’uniform’). R#=1."B(t)") b(t)=a*b(t+1)/(1+a*b(t+1)) . function [h]=PREL_OPT(t. i=1 where R(w) = R1 w .9. for i=1:N_simu rho=0. // optimal catches and resource plot2d(1:Horizon. . Horizon=10.style=i) . The annual wealth evolution of the farm was described by & n ' υ(t + 1) = υ(t) ui (t)Ri w(t) = υ(t)ui (t).Bopt(t).Rb=1. Bopt(t+1)=DYN_OPT(t.B)) // endfunction 8. b=[]. // // exec opti_uncertain_resource. end // isoelastic utility end function [u]=util(x) u=x^puis // computation of optimal trajectories endfunction Bopt(1)=B0.5.2) .
un ) ∈ S n . belonging to the simplex S n of Rn . The allocation u = (u1 .n stood for the proportion of wealth generated by use i ( i=1 ui (t) = 1. to the different land-uses appeared as a decision variable representing the land-use structure. . . ui (t) ≥ 0). and w(t) corresponded to environmental uncertainties varying in a given domain S ⊂ W. . . .
. υ) = υρT Ew [Ri (w)]T −t .n Ew [Ri (w)] in the sense that ⎧ ) ⎨ u (t. u is a linear programming problem which admits ui (t. 8.. υ) = υρT Ew [Ri (w)]T −t .. υ) = υρ Ew [Ri (w)] T T . . The chosen use is the i ∈ arg maxi=1.41) at time t + 1. we obtain the desired result: V (t. F (υ. w) u∈S n 6 7 T −(t+1) = sup Ew υ(R(w).. The optimal allocation and value are given by: ⎧ ) ⎨ u (t. To prove this. we deduce that: 6 7 V (t.. Result 8. υ) = υρT . From dynamic programming equation (8. u u∈S n . υ) = 0 if i = i ⎪ i 1 if i = i (8.40) ⎪ ⎩ −t V (t. u] u∈S n T −(t+1) = υρ Ew [Ri (w)] T sup Ew [R(w)].. we reason backward. u Let us prove that the optimal allocation is a specialized one defined by use i ∈ arg maxi=1. This result suggests that without risk aversion (utility is linear). special- ization in one land-use is optimal when the land-use remains constant. Clearly the relation holds at final time since we have V (T. υ) = sup Ew V t + 1.12). υ) as solution.16 Without risk aversion (utility L is linear). u.. υ) = 0 if i = i ⎪ i 1 if i = i (8. specialization in one land-use is optimal in the stochastic sense. u)ρ Ew [Ri (w)] T u∈S n = υρT Ew [Ri (w)]T −(t+1) sup Ew [R(w). Therefore. The optimization problem supu∈S n Ew [R(w)]. The chosen use is the one which maximizes the expected growth Ew [Ri (w)].n Ew [Ri (w)] which maximizes the expected growth Ew [Ri (w)]..8 Optimal expected land-use and specialization 211 Now the farmer aims at optimizing the expected discounted final wealth at time T : 0 1 sup E ρT υ(T ) .41) ⎪ ⎩ V (t. Assume the relation (8.
Data used for model calibration come from the wet grasslands of the Marais Poitevin (France).3. grazing strategies and uncertain climatic impacts on a discrete monthly basis at a lo- cal scale. Both live and dead grass are lost through grazing. w(t) 0 A t.m−2 ). Targeting agricultural practices may therefore help to restore habitat quality and enhance biodiversity. we present a bio-economic model of habitat . The sward state consists of a biomass (or- ganic matter) including live BL (t) and standing dead BD (t) grass in (g. (8.9 Cost-effectiveness of grazing and bird community management in farmland Farmland biodiversity has undergone severe and widespread decline in recent decades. The numerical method relies on stochastic dynamic programming under the context of robust constraints. . B(t) . 8. especially for wader populations foraging and nesting in wet grasslands. w(t) B(t) − G u(t). The live grass increases via new growth and senesces to become dead grass. Redshanks and Godwit species. 1 − exp − rS (t) exp − rD (t) • rS (t) and rD (t) stand respectively for the senescence and decay rate coef- ficients which are time dependent. B(t). with dead grass also vanishing through decay. B.212 8 Robust and stochastic optimization 8. • The matrix A reads: & ' exp − rS (t) + rG t.2 and 8. BD (t) controlled by grazing u(t) may be summarized in the following compact form: B(t + 1) = A t. The wader community here includes Lapwings. The management decision is represented by graz- ing intensity u(t) expressed in livestock unit (LU. B. The whole set of variables and parameters are summarized in Tabs. Such is particularly true for bird species and agricultural intensifi- cation is designated as a major cause. Hence. Major constraints are based on specific sward heights which promote bird viability. w(t) = . following [6]. Dynamics The first component of the model represents a grass sward grazed by suck- ling cattle on a monthly basis. The model integrates sward and bird population dynamics.m−2 ).biodiversity interactions to provide intensity and timing of grazing for the sustainability of both wader populations and farmer prac- tices. The evaluation is conducted in terms of cost-effectiveness as the grazing profile is chosen from among the robust viable strategies which min- imize the expected economic cost of indoor livestock feeding.42) Here we comment the different terms.1. Hereafter. live- stock raising and grazing should be considered as effective tools for the con- servation of bird biodiversity. 8. The grass dynamics B(t) = BL (t).
the monthly dynamics of the species i corresponds to Ni (t + 1) = Mi t. h) if t = t∗i ⎨ [modulo 12] .d. • It is here assumed that cow grazing exhibits a preference for live biomass. 3 is modeled by a life-cycle graph with two age-classes. • Stochastic uncertainty w(t) ∈ {−1.i. B. si1 si2 Mi t. B) . random variables under probability P with common law P(w(t) = 1) = p ∈]0. BL ) GD (u. w) = rP (t) (1 − σ) with probability 1 − p . rP (t.m−2 ) as follows GL (u. h) fi2 (N. h B(t) Ni (t) (8. B. To meet this requirement. 1[ and P(w(t) = −1) = 1 − p. w(t) = rP t. cattle first consume all available live grass GL and then all available dead grass GD (in g. The matrix Mi is defined by: ⎧ ⎪ ⎪ fi1 (N.44) We detail the parameters.9 Cost-effectiveness of grazing and bird community management in farmland 213 • The uncertain growth rate rG t. B) = min(qu. The first class Ni1 (t) consists of sub-adults (first-year individuals) and the second class Ni2 (t) of adults (second-year or older). w(t) . Hence the potential growth fluctuates around its mean value rP (t) with a dispersion level of σ. Assuming a pre- breeding census. The life history of each species i = 1. giving a random potential growth rate rP (t. . The second component of the model describes a community of three wader species breeding in the grass sward. Only females are considered. w(t) is the product of a potential growth rate rP t. 0 1 (8. 2.43) where h B(t) is the height of grass sward B(t). B) = qu − GL (u. BL + BD with β a coefficient attenuation related to sun angle and μ a specific leaf area. Ni (t).8. N. 1} is assumed to be a sequence of i. h = ⎪ ⎪ 1 0 ⎩ if t = t∗i [modulo 12] . w) as follows: (1 + σ) with probability p . with q the amount of grass required per month. w(t) which varies according to the year and the relative light interception by live mass based on Beer’s law: 1 − exp − βμ(BL + BD ) rG t.
clutch size fij . 8. Such breeding success is the product of the proportion of breeding females γi .10 0.45 0.3. • fij (N.3. In this context.25 0. hi (t∗i )] = arg max si0 (h) .05 0. appropriate sward quality consists of both minimal hi (t) and maximal hi (t) grass heights. a maximal survival for each species can be required at the appropriate rearing period t∗i through the height cor- ridor: [hi (t∗i ). h The combination of these thresholds for every species i yields a global height corridor summarized by the following constraints: . • We rely on field data from the Marais Poitevin to determine a linear rela- tionship between grass height and biomass: h = h(B) = a1 (BL + BD ) + a0 . for each bird species i. h) = γi υi fij (8.e. lapwings (circle) and redhsanks (diamond).00 sward height (cm) 0 5 10 15 20 25 30 Fig.3 and density of breeders Ni .40 0. 8. primary sex-ratio (i.30 0.214 8 Robust and stochastic optimization • sij is the survival of class j in species i. Chick survival rates si0 (h) depending on sward height h (cm) for two breeding wader species. Specifically.20 0. This survival depends on two factors that affect repro- duction: grass height h as depicted by Fig. the proportion of females at birth) υi and chick survival. (8. Typically.15 0. we use a Beverton-Holt-like density-dependence.45) 1 + bi (Ni1 + Ni2 ) where si0 (h) is depicted by Fig. chick survival probability 0.35 0.46) Biodiversity and production constraints We first consider an ecological constraint that requires sward states suitable for the chick rearing period of the different bird species. 8. • t∗i is the month of chick rearing. The breeding success of individuals of class j in species i at time t is thus si0 (h) fij (N. h) is the breeding success of individuals of class j in species i.
4b) which are characterized by dense grazing intensity in spring followed by autumn grazing. (8. u∈Uviab 1 (t0 .4c) despite the uncertain climatic scenarios. 8. Numerical results Here dynamic programming and simulations are performed over a period of T = 48 months with neiter present nor future preference ρ = 1. 8. B0 ) means that control u(t) is a viable feedback in the robust sense. 8. Redshanks.B0 ) t=0 where ρ ∈ [0. Godwit). 8. During all periods.4a). in Tab.48) Moreover the size of the herd is assumed to be set at u which implies the following control constraint: u(t) ≤ u . 1] stands for the discount factor and Uviab 1 (t0 . B) give grazing de- cisions u (t) = u (t. Spring grazing is the major determinant for sward height requirements (Fig. (8. w(t)). Expected cost-effective grazing strategies u (t.1 for birds (Lapwings. (8.49) Cost-effectiveness We focus on the economic grazing strategy that consists in minimizing the expected discounted cost related to indoor cattle feeding: + T - min Ew(·) ρt c u − u(t) . A linear relation is here assumed for costs through the relation c(u −u) with c standing for the indoor feeding cost of one livestock unit.3 for the agronomic and economic data.9 Cost-effectiveness of grazing and bird community management in farmland 215 h (t) = max hi (t) ≤ h(t) ≤ min hi (t) = h (t) .8. productive constraints related to feeding requirements are satisfied. The whole set of used variables and parameters detailed in [6] are expounded in Tab. 8. .47) i i Another important requirement we impose is related to the satisfaction of cattle feeding requirements along the months. The environmental uncertainty w(t) is characterized by a dispersion level σ = 5% of potential growth rate rP (t. 8. B(t)) (Fig.2 for the sward and in Tab. This production constraint as- sumes that the demand of sward mass for grazing cannot exceed the available biomass: qu(t) ≤ BL (t) + BD (t) . The bird population dynamics Ni (t) resulting from the sward requirements are viable in the robust sense (Fig. Autumn grazing is the key to increasing the economic efficiency of this strategy.
05) height . 0.7 3. 150.35 14 if t∗1 =May 20 if t∗2 =June Upper desirable sward height hi (t) (cm) +∞ +∞ otherwise +∞ otherwise ∗ 10 if t2 =June Lower desirable sward height hi (t) (cm) 0 0 0 otherwise Capacity charge parameter bi 0. 0.1 Leaf area μ (m2 g −1 ) 0. 0.35.45 0.biomass Table 8.8 0.6 0. Bird demographic parameters.216 8 Robust and stochastic optimization Table 8. 1.75 0.2 Sub-adult cluth size fi1 3. 1.ha−1 ) 5 .52.5 Maximal deviation σ of high growth 0. 0.45.01 Attenuation β 0. 0.7 Proportion of breeding females γi 0.75 Sex ratio υi 0. Lapwings Redshanks Godwit Sub-adult survival si1 0. 150.2.7 Adult survival si2 0. Sward parameters Senescence of green biomass rS (t) (0.52. 0.9.9.07.2 4. 0.45.1.52.LU−1 . 0. 0) Decay rate of death biomass rD (t) (0.LU−1 . 0.05. 330. 4. 0. 0. 0.7 0. Agronomic and economic parameters Livestock demand q (g.5 Maximal chick survival si0 0.3. 390.103 Feeding cost c (euros.8 Adult clutch-size fi2 4. 0.05.45.7 3. 60.month−1 ) 30 Maximal livestock u (LU. 3.35 0.9.2 4. 0. 150.75 0. 0.5 Slope a1 and intercept a0 relation (0. 0. 0) Probability p of high growth 0. 1.5 0.52) Mean potential growth rate rP (t) (3. 0. 0.7 0. 150.0077 Table 8.5 0.month−1 ) 412. 150.0077 0. 0.0077 0.
Godwit) is maintained at a sustainable level through robust grazing strate- gies u (t. sward height h (t). Expected cost-effectiveness paths over time over 4 years from viable ini- tial sward states B0 = (475.00 2005 2006 2007 2008 2009 t (a) Optimal sward height h (t).2698 0.1226 0. Red- shanks.04).25 5.1472 Ni(t) 0.4.9 Cost-effectiveness of grazing and bird community management in farmland 217 45.02.2207 0. and population densities Ni (t) for different climatic scenarios w(t).13 h(t) 22.05) and N30 = (0. B) despite climatic uncertainties w(t).00 39.63 0.01.50 16. Every bird population (Lapwings.0491 0.0000 2005 2006 2007 2008 2009 t −1 (c) Bird populations N (t) (abundances. upper and lower viable heights h (t) and h (t) (cm) 5. N20 = (0.0245 0.88 11. Redshanks.0736 0.38 33. 150) (in g.m−2 ) and bird states N10 = (0. God- wit) Fig.ha ) (Lapwings.ha ) 0. 0. Optimal viable paths are plotted including grazing u (t).05) (abundances.ha−1 ). 8.1717 0.8. 0.0981 0.00 u(t) 2.75 28.01.2453 0.50 0 2005 2006 2007 2008 2009 t −1 (b) Livestock unit u (t) (LU.1962 0. . 0.
Athena Scientific. second edition. Belmont. Massachusets. volume 1. Ecological Mod- elling. August 2007. P. . Dynamic Programming and Optimal Control. Economic Theory and Sustainability. Stochastic Optimal Control: The Discrete-Time Case. Columbia University Press. Wiley. second edi- tion. 2000. J. Renault. Belmont. [6] M. Athena Scientific. [4] C. D. J. Tichit. E. L. P. New York. Bertsekas.References [1] D. Analysis and Management of Animal Populations. and M. [3] K. Heal. Doyen. 206(3-4):277–293. Conroy. J. [2] D. Whittle. Volumes 1 and 2. Clark. New York. Shreve. Nichols. Lemel. 2002. 1996. [7] P. W. W. John Wiley & Sons. New York. Massachusets. Byron. 1990. [5] G. and O. A co-viability model of grazing and bird community management in farmland. 1998. Bertsekas and S.Y. 1982. Optimization over Time: Dynamic Programming and Stochas- tic Control. Academic Press. Mathematical Bioeconomics. Valuing the Future.
First. These situations correspond to imperfect infor- mation problems [4. being partially known and/or cor- rupted by uncertainty. This context where information is at stake is of particular relevance for envi- ronmental problems since it is related to notions such as value of information. The concept of value of information is introduced in Sect. 9. Likewise. only a partial component of the state is known. we must specify the dynamics/observation cou- ple. admissible feedbacks have to be redefined as now being a function of observation only. 9. Unfortunately. 9. The intertemporal decision problem with imperfect observation is detailed in Sect.1 Intertemporal decision problem with imperfect observation Now. even in the uncertain framework. and use this knowledge for appropriate feedback con- trols. 9. such a context may deeply alter the quality of the decisions and change the global controlled dynamics and trajectories. Second.5 and related to monotone variation of the value of information. in many problems. This situation refers to the case of perfect information. For instance. . and illustrated by precautionary catches and climate change mitigation. The chapter is organised as follows. the state is not available in totality.9 Sequential decision under imperfect information Up to now.2. 14]. flexibility or learning effect and precautionary issues. Of course. it has been postulated that decision makers. The so-called precautionary effect is presented in Sect. In a renewable resource management problem. a fish- ery only provides data on targeted species within an ecosystem whose global state remains unknown. data on catch effort may be quite uncertain because of non compliance of agents exploiting the natural stock. the observation of the state may be corrupted by noise.1. regulating agencies or planners know the whole state of the system at each time step.
w(t) . T − 1 ⎨ x(t0 ) = x0 (9. Vector y(t) ∈ Y = Rm represents the system’s observation or output at time t which implies that the decisions strategies will now be feedbacks of the outputs. u(t) ∈ U = Rp stands for the control or decision and T ∈ N∗ corresponds to the time horizon.1). refers to: H(t. wY ) = x + wX . x(t). which includes both uncertainties wX (t) ∈ WX = RqX affecting the state via the dynamics F and uncertainties wY (t) ∈ WY = RqY affecting the observation via the output function 1 H in (9. The initial state x0 is also uncertain now. where again x(t) ∈ X = Rn is the state. x) . .222 9 Sequential decision under imperfect information 9. t = t0 . x. w(t) . • Deterministic systems can be associated with the case: H(t.1 Dynamics and observation The control dynamical system of previous chapters is now assumed not to provide the exact state. • The case of observations corrupted by additive noise is depicted by the situation where y(t) = x(t) + wX (t): H(t. x. x0 . w) . Here we find important instances of output functions. x. The initial observation is y0 ∈ Y. • The case of perfect information. treated in the previous chapters. . . 1 The output function H depends on time t. . However. but only a partial and/or corrupted function of it. w(t0 ) . . . . . The observation function H : N × X × W → Y represents the system’s output which may depend on state x and on uncertainty w. w) = (t. state x and disturbance w. wY (t) evolving in some space WX × WY .1. u(t). t = t0 . w) = (t. . only partially known through the relation y0 = H t0 . T − 1 ⎩ y(t0 ) = y0 . Comparedto the perfect information case. we shall not treat this case. It is described by ⎧ ⎪ ⎪ x(t + 1) = F t.1) ⎪ ⎪ y(t) = H t. x(t). w) = H(t. It might also depend on the control u. x. The set of possible scenar- T −t0 ios for the uncertainties is again represented by Ω ⊂ (WX × WY ) in the sense that: T −t0 w(·) ∈ Ω ⊂ (WX × WY ) . wX . w(t) is now an extended distur- bance w(t) = wX (t). x.
y(t) now depend on the output y(t) which stands for the information available to the decision maker. . . . . w(·)]. u. (9. . . where x(·) satisfies the dy- namic x(t + 1) = F t. . Decision issues are more complicated than in the perfect observation case in the sense that decisions u(t) = u t. w(t) . x(t). w(·)] = y(t) and uH [t0 . . y(t) ⊂ U . given a feedback u ∈ U. . ⎪ ⎨ x(t) ∈ A(t) ⊂ X . w(·)](t) = x(t). y(t) respectively. H(t. w(·)](t) = u t. However. . We thus now define feedbacks as the set of all mappings from N × Y to U (and no longer from N × X to U): U = {u : N × Y → U} . . we extend the notion of admissible feedbacks u ∈ Uad H as follows treating state constraints in the robust sense: . t = t0 .2) ⎪ ⎪ ⎪ ⎩ x(T ) ∈ A(T ) . T −1 and y(t) = 0 for t = t0 . y(t) and not u(t) ∈ B t. . Notice also that the control constraints are written as u(t) ∈ B t. x0 . yH [t0 . w(·)] are now defined by xH [t0 . u. solution map and admissible feedback strategies As in the certain case. . a scenario w(·) ∈ Ω and an initial state x0 at time t0 ∈ {0. . . 9. . . 9. the question arises as to whether state constraints may be achieved by decisions depending only upon partial and corrupted knowledge of the state.3) Furthermore. w(·). . w(·)] and observation map yH [t0 . In this context. . with initial condition x(t0 ) = x0 . . . we may require state and decision constraints to be satisfied: ⎧ ⎪ ⎪ u(t) ∈ B t. u. T − 1 . T − 1 . t∗ − 1 . x0 . t∗ − 1. since the state x(t) is only partially known by the decision maker. . u. x0 . . x0 . u. x(t) . T − 1 . . w(·).2 Decisions. x0 . u. t = t0 . x. u t. . x(t). namely y(t) = h x(t) for t = t∗ . T − 1}. . .1. . the state map xH [t0 . (9. w(·). y(t) . control map uH [t0 . x0 . w(·). w(t) . and where y(t) = H t. w) = h(x) if t = t∗ .1 Intertemporal decision problem with imperfect observation 223 • The case of learning may correspond to information on the state after a given time t∗ < T . The corresponding observation function is: 0 if t = t0 .
3 In the sequel. y0 ) := u ∈ U x(t) = xH [t0 . w(·) = L t. x(t). and that all measurability and integrability assumptions are satisfied for the following expressions to hold true. 9. w(t0 ) compatible with the output y0 at time t0 . x0 . w(·)](t) and ad . u. w(t0 )) = y0 . u(·). . x0 . 2 For the robust case. x(T ). y(t) the so- lution maps introduced hereabove. u∈U ad H (t0 .2). x(·). x0 . The maximal value criterion VH (t0 . x) with respect to the state depending on the context. u(t). an appropriate new state for indexing the maximal value criterion is the conditional law of the state knowing past observations. we assume that a probability P is given on the space X × Ω (recall that the initial state x0 is an uncertain variable). y0 ) := sup E(x0 .224 9 Sequential decision under imperfect information ⎧ ⎫ ⎪ for all scenario w(·) ∈ Ω ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎨ for all x0 ∈ X such that H(t0 . ⎭ Notice how the initial state x0 has now been treated as an uncertain variable as the scenario w(·).4) with states x(t) = xF [t0 . w(t) + M T. a parallel between probability and cost measures may be found in [1. 3]. x0 . u(·). w(T ) . More generally. ⎪ ⎪ u(t) = uH [t0 . For this purpose.3 Criterion to optimize The criterion π is introduced as in Sect. See the following footnote 4 for the mathematical proper dependence with respect to a new state.y0 ) (9. w0 ) = y0 ⎪ ⎬ UH (t0 . w(·)](t) and controls u(t) = u t. y0 ) of the criterion π with respect to acceptable feedbacks depends on the observation function H and is now assessed with respect to the initial observation3 y0 6 7 VH (t0 . The usual case is the separable or additive one: −1 T π x(·).1.w(·)) π t0 . u. w(·) | H(t0 . t=t0 We shall focus on expected2 criterion. 6. w(·)](t) ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎩ satisfy (9.1. the reader will also see an evaluation VH (t. The maximal value criterion is an expec- respect to probability P on X × Ω. x0 . We shall not develop this point in this monograph. 4 The maximal value criterion could be assessed with respect to the conditional law of the state x0 knowing the output y0 . u. and is conditional to those 4 tation with x0 .
We define the value of information between Hβ and Hγ as the difference between the two associated optimal criteria: Δ(Hγ . an information effect oc- curs which means that the information structure Hγ improves the perfor- mance5 through more adequate decisions compared to the information struc- ture Hβ . Productivity R(t) of the pop- ulation is uncertain between two values 0 < R ≤ R : R(t) ∈ S = {R . It is postulated that the policy goal is to constrain the biomass level of the population within an ecological window. y0 ) is the value of information between Hβ and Hγ . Hβ ) := VHγ (t0 .3 Precautionary catches 225 9. Hγ ) = VHβ (t0 . the population. and that P(R(t) = R ) > 0 and P(R(t) = R ) > 0. Conservation intensity corresponds to 1 − e(t). consists of independent and identically distributed random variables. R } ⊂ W = R . varies in time according to uncertain dynamics g and catches h(t) as follows B(t + 1) = g R(t). . we obtain B(t + 1) = R(t)B(t) 1 − e(t) . 9. described by its biomass B(t). conservation) and 5 In the following examples.3 Precautionary catches We consider the management of an animal population focusing on the trade-off between conservation and invasion issues. . R(1). where R(t) plays the role of uncertainty. . 1] ⊂ U = R .5) Whenever the value Δ(Hγ . We assume that the sequence R(0). 9. Assuming a no density-dependent and linear function g(R. it may happen that the performance is measured by cost minimization. y0 ) . Hβ ) is strictly positive. Δ(Hβ . B) = RB with r = R − 1 the natural resource growth rate. In this case. We shall consider a two-periods problem: t0 = 0 and T = 2. (9. y0 )−VHγ (t0 . (9. y0 ) − VHβ (t0 . According to [12]. namely between minimal (survival.6) where e(t) = h(t)/B(t) stands for the catch effort decision constrained by e(t) ∈ B = [0. B(t) − h(t) .2 Value of information Consider two information structures Hβ and Hγ (observation functions) tak- ing values from the same space Y.
.
while the infimum can go deeper into the expectation in VHγ (0. we have: =0 ) ≥ VH (0. R) . B. e(0)∈[0.1] The difference between the expressions of VHβ (0. B. 1. 6 This differs from the general utility maximization approach followed thus far in the book. R) = B for t = 0. B0 ) which reads ER(1) inf e(1)∈[0.7. where the cost function C(·) is assumed to be linear C(1 − e) = c × (1 − e) . B ] ⊂ X = R . B0 ) (recall that we minimize costs and see the footnote 6). R) = (B. B. it is only assumed information on state B(t) at each time t and we aim at computing 6 7 0 1 VHβ (0. 1[ is a discount factor. B0 ) is the following: without information one evaluates inf e(1)∈[0.1] ER(1) in VHβ (0. B0 ) = inf ER(0) ER(1) inf C 1 − e(0) + ρC 1 − e(1) . γ A question that arises is whether a value of information occurs. R) = B . The observation function is thus: Hβ (t.1] e(1)∈[0.7) 6 We focus on cost-effective policies which minimize the expected intertemporal costs of conservation C 1 − e(t) . First.6) and safety target (9. the answer depends on the relative size of both the conservation window and the growth uncertainty. The decision maker faces a more informative structure of information: Hγ (1. we aim at computing: 6 6 77 0 1 VHγ (0. M VHβ (0. B0 ) and VHγ (0.7).1] where ρ ∈ [0. e(0)∈[0.1] when information is available. Now assume that learning of the population growth R(1) occurs at the second period (t∗ = 1). VHβ (0. B0 ) > VHγ (0. B0 ). (9. Sect. .1] e(1)∈[0. and under the dynamics constraints (9. i. A. As exam- ined in [6].e. and which ensure that the target (9.7) is achieved for all scenario. Focusing on cost-effective policies.226 9 Sequential decision under imperfect information maximal (invasive threshold) safety values 0 < B < B at time horizon T = 2: B(2) ∈ A(2) = [B . Hence. M =0 ) . The proof is exposed in the Appendix. Hγ (0. B0 ) = inf ER(0) inf ER(1) C 1 − e(0) + ρC 1 − e(1) .
Hence it is the opposite of indecision before the arrival of the information.< Furthermore note that this initial decision e 0. However. B Moreover. B) = 1 − . In the linear case. no decisions exist which can ensure a safe final state in the robust sense. .3 Precautionary catches 227 Result 9. B0 ) = +∞ and VHγ (0. B(0) combines distinct population features as it involves both viability biomass B and certainty equivalent productivity R. 9.9the value of information Δ(Hβ . For invasive species management and conservation. In9 this case. B0 ) < +∞.1 An information effect occurs if the safety ratio B /B is strictly smaller that the growth ratio R /R . with the harmonic mean R This result shows that. <2 B R <−1 = ER [R−1 ]. when the uncertainty concerning the growth rate of the resource is too large and when no information is revealed to the deci- sion maker. it is worth pointing out that the “precautionary” decision (with learning) at first period e 0. Hγ ) is strictly positive for B0 ∈ (RB )2 . for any B ≥ (R )2 . the optimal catch feedback (with learning) at first period is given by . this suggests that a precautionary biomass lower bound makes sense. B(0) is not zero. +∞ since VHβ (0. the resolution of the uncertainty allows for cost-effective man- agement with initial biomass higher than a precautionary threshold given by B /(R )2 . ρB e (0.
Parameters are R = 0.3 0.0 1.1.8 1.9.3 0. B = 1.8 2.5 biomass B(t) 1.6 0. e(1)) obtained with the Scilab code 17.5 lower threshold upper threshold 0.8 0. .6 effort e(t) 0.0 time t Fig. B(2)) and cost-effective (with learning) efforts (e(0).1 0.2 1.0 0.4 0.4 0.1 0. R = 2.0 0.5 0.0 0.7 0.2 0.6 1.0 time t Catch effort 1.4 0.0 0.9.2 0.0 1.7 0.5 0.6 0.228 9 Sequential decision under imperfect information Population state 2. B(1).4 1.2 0. Biomasses (B(0). 9.9 0.0 0. B = 2 while ρ = 0.9 1.0 0.8 0.
9./(y(2).2). w_min=0. xset("window". if t==1 then y=[B.B’.9) where we have assumed stationary emissions Ebau . // two period problem /////////////////////////////////////////////////////// B_min=1. Consider a version of mitigation policies for carbon dioxyde emissions as exposed in Sect.’biomass B(t)’).0].3). endfunction rect1=[0.*y(1)).’lr’).0. end // parameters dynamics w_hat=(w_max-w_min)/(log(w_max)-log(w_min)). /////////////////////////////////////////////////////// // Precautionnary state // rho=1/1..e).e(t). xtitle("Catch effort"."upper threshold"]. // B(0)>= B_min/(w_min^(Horizon-1)) endfunction w=w_min+(w_max-w_min)*rand(1.Horizon)’ .9.’effort e(t)’). legends(["lower threshold".3. // 9.Horizon-2. abcisse=linspace(0.. t = 1 for 25 years ahead and t = 2 for 50 years. // observation with learning rect3=[0. e=max(0. // controlled uncertain dynamics // precautionnary initial conditions z=f(B*(1-e).w).8) the carbon cycle (2. // drawing diamonds.20) may be written as =(t + 1) = (1 − δ) M M =(t) + αEbau 1 − a(t) .rect=rect3). w_max=2.4 Information effect in climate change mitigation 229 Scilab code 17.2).5]. 1 (9.sce Horizon=3./((w_r^2).5]). xset("window".xbasc().style=1).w) B_simu=10.Horizon)*(B_max-B_min).20).. style=-[4.w].B. function y=Obser(t.rect=rect1).w_min. say t = 0 being today. only two periods are considered.-[4. // plot2d(xB. xset("window".w) rect2=[0.’time t’. endfunction plot2d(xB.’uncertainty w(t)’). y=zeros(1. Introducing the following difference between co2 concentrations =(t) := M (t) − M−∞ M (9.) w_r=w_hat. xB=[0:1:Horizon-1]. t = 0. //discount factor function [y]=f(B.xbasc().’time t’.Horizon-1).1]. 1].4 Information effect in climate change mitigation We first present an example developed in [8] (see also [9]). y=Obser(t. 2.xe=[0:1:Horizon-2].1*w_min).Horizon)’]. // xtitle("Uncertainty".[B’ B_min+zeros(1.plot2d(xe.05.xbasc().w(t)). if t==1 then e=1-sqrt(rho*B_min.1). xset("window". plot2d(abcisse.[B_min*ones(abcisse)’ B_max*ones(abcisse)’]. B_max=B_min*w_max/(1. // // Certainty equivalent of 1/w // exec precaution. xset("window".1).rect=rect2). endfunction for i=1:B_simu // Simulations function z=dyna(B.w(t)). to identify the curves xtitle("Population state"..B(t). crosses.Horizon-2.end // if t==2 then y=[B. etc.w) B=B_prec+rand(1.y).2).*y(1))).e. // Cost-effectiveness // Safety Constraint // for renewable resource management with learning B_prec=B_min/(w_min^(Horizon-1)). // linear population dynamics // Simulation number y=w*B.y) for t=1:Horizon-1 // cost-effective effort // precautionary Trajectory B(.end e(t)=cost_effective(t.’time t’.plot2d(xe.3). if t==2 then e=1-B_min.w. Here.Horizon-1. // Random or growth along time function e=cost_effective(t.) e(.end xset("window".Horizon-1..w_max]. end. B_max+zeros(1.e.(Horizon-1)*B_prec].end B(t+1)=dyna(B(t).0. . with abatement rate a(t) ∈ [0.
θ) = M Hβ (t. θ(t) is observed at each time t. θ(·). only part M=(t) of the whole state is observed. θ. with here also a quadratic expression =) = M D(M =2 (9. inspired by [5]. (9. the initial decision a(0) will only depend upon M =(0). scientific information may be revealed at mid-term t∗ = 1. while M =0 = M =(0) is supposed to be known. 0) =. a probability distribution P0 on θ is supposed to be given. M =. θ) . 9 The expression EPθ00 denotes an expectation with respect to the probability distri- bution P0 of the random variable θ0 = θ. In absence of information. θ+w) for instance. t = 0. w) = (M =. 1 and θ(0) = θ0 . We have introduced a new state variable θ(t) with state equation θ(t + 1) = θ(t) . In both cases of information structure.14) Notice that no additional disturbance set W is needed. the whole state M=(t). the observations8 or the costs. a(1) will only depend upon M=(1) and we obtain9 7 See the previous footnote 6 in this Chapter. a(·)) = C a(0) + ρC a(1) + θ(2)D M =(2) . Abate- ment costs are C a(0) and C a(1) . θ)). Two successive reduction decisions a(0) and a(1) have to be taken in order to minimize7 the whole discounted cost π(M=(·). since no disturbances affect the dynamics. 8 Noisy observations would require an uncertainty w and H(1. θ) = (M and Hγ (1. after the first decision. M =. We shall not consider this case. In the stochastic framework. This corresponds to an output function =.11) and θ ≥ 0 an unknown parameter which measures the sensibility of damages to the co2 concentration level. with the convex functional form C(a) = ca2 (9. but before the climatic damages. This corresponds to perfect knowledge of θ. M =.12) Thus θ(2) = θ(1) = θ0 is the value of the unknown parameter. (9. There is a final cost θD(M due to climate change. . In the perfect information case.230 9 Sequential decision under imperfect information The decision problem is one of cost minimization. 1 .13) Now. M =. (9.10) =(2)) corresponding to damages taken for simplicity. In absence of information about the parameter θ (now become component of the state (M=. t = 0. θ) = (M Hγ (0. Such a case of learning about the parameter θ is depicted by =.
there is an information effect in the sense that =0 ) − VH (0. Result 9. M =0 ) and VH (0. 9. θ ] such that ρc 0 ≤ θ < θ ≤ . we have: =0 ) ≥ VH (0. (9. the value of θ =(1) and θ. M =0 ) . an important issue is the so called “irreversibility effect”. Hence.5 Monotone variation of the value of information and precautionary effect In the theoretical literature on environmental irreversibility and uncertainty [2.5. M =0 ) is γ P0 =0 ). 9. This effect states roughly that.7.15) =0 + αEbau αEbau (1 − δ) (1 − δ)M Then. γ The question whether first optimal abatement a (0) is also reduced with such a learning mechanism is examined in Sect. Sect. 0≤a(0)≤1 0≤a(1)≤1 The difference between the expressions of VHβ (0. the following: without information one evaluates inf 0≤a(1)≤1 Eθ0 in VHβ (0. M while the infimum can go deeper into the expectation in VH (0. M =0 ) > 0 . M =0 ) which γ reads EPθ00 inf 0≤a(1)≤1 when information is available. 0≤a(0)≤1 0≤a(1)≤1 When scientific information may be revealed at mid-term.2 Assume that the unknown parameter θ follows a probability dis- tribution P0 having support not reduced to a single point and included in [θ . Hγ ) = VHβ (0. M inf C a(0) + EPθ00 inf = ρC a(1) + θ(2)D(M (2)) . so that a(1) will depend upon both M thus + 6 7- =0 ) = VHγ (0. M VHβ (0. M Δ(Hβ . when there is a source of irreversibility in the system we . 10. γ It turns out that an information effect generally holds for such a mitigation problem.5 Monotone variation of the value of information and precautionary effect 231 6 9 : 7 =0 ) = inf VHβ (0. 11]. M C a(0) + inf EPθ00 ρC a(1) + θ(2)D(M =(2)) .9. A. The proof is given in the Appendix. This suggests that costs of co2 mitigation are reduced when learning of uncertainties occurs. giving is revealed at t∗ = 1.
x1 ) − VHβ (1. and the same for uHγ (0). (9. more cautious) with than without information prospect. w(1) +M 2. x(1). 1 ⎩ y(t0 ) = y0 . w(1) + M 2. where the set B(1. x(2). 1 ⎨ x(t0 ) = x0 (9. By learning effect we refer to how the first-period optimal decision is modified when the decision maker considers that information will arrive in the future. x(t). two information structures (not necessarily comparable in the sense that one is finer than the other). let us consider Hβ and Hγ . Consider a two-periods control system where. We present here a general framework and an analysis which focuses upon the value of information as a function of any possible initial decision. we mean that the first-period optimal decision is lower (less emissions. x(1)) Suppose that the initial decision u(0) is taken without information. Irreversibility may be captured by the property that the second decision u(1) belongs to B(1. For the second time. (9. that is H(0. let uHβ (0) be the optimal initial decision with information structure Hβ . Hβ )(x1 ) := VHγ (1. less consumption. Define the value of information at time t = 1 starting from state x1 by: 9 : VHβ (1. w(t) . Suppose that the control variable u is scalar: u ∈ B(0) ⊂ U = R . t = 0.16) ⎪ ⎪ y(t) = H t. w(0) +L 1. u(1). x) indeed depends upon state x. the dynamics is not affected by uncertainty as in ⎧ ⎪ ⎪ x(t + 1) = F t.232 9 Sequential decision under imperfect information control. 13]. x(1)). w0 ) = 0. Such question is also treated in [7. u(1). By precautionary. for simplicity. If the function u0 ∈ B(0) . ⎨ u(0) ∈ B(0) ⎩ u(1) ∈ B(1. The optimization problem is (without discount factor) 9 : ⎧ sup E L 0.x1 ) The value of substituting information structure Hβ for Hγ at time t = 1 is the following function of the state x1 at time t = 1: Δ(1) (Hγ . Assuming their existence and uniqueness. t = 0.18) Proposition 9.3. x1 ) := sup E L 1. x1 . w(2) . x0 . u(0). x(t). w(2) . x1 ) .17) u(1)∈B(t. then “the learning effect is precautionary” in the following sense. x(0). u(t) . x(2).
. x0 .→ Δ(1) (Hγ . u0 ) is decreasing. Hβ ) F (0.
Sect.6 Precautionary effect in climate change mitigation 233 then precautionary effect holds in the sense that the initial optimal decisions are ranked as follows: uHγ (0) ≤ uHβ (0) . exposed in [8] and given in the Appendix. 9. relies on the mathematical property that two functions fβ and fγ having the increasing differences property (u . A.7. The proof.
θ0 0≤a(1)≤1 Similarly. M =1 ) = 6 7 θρc EPθ00 [θ] ρc P0 Eθ0 − =1 + αEbau 2 . Indeed. 9. 9. M Vγ (1. Without information. M = dM1 β 6 7 θρc EPθ00 [θ] ρc P0 Eθ0 − =1 +αEbau < 0. that =1 ) − Vβ (1. θ0 0≤a(1)≤1 Under the assumptions of Result 9. the value of substituting information structure Hβ for Hγ at time t = 1 (recall that we minimize costs and see the footnote 6 in this Chapter) is decreasing with the state M=1 . M =1 + αEbau 1 − a(1) . A.4. M =1 ) = VHγ (1. (1 − δ)M P 2 2 ρc + θα Ebau ρc + Eθ0 [θ] α Ebau 0 2 2 Thus. let us see whether precautionary effect holds true. we compute 6 7 =1 ) = EP0 Vγ (1.7. we have d =1 ) − VH (1. in the case of learning about damage intensity ϑ = θ0 . where uβ := arg maxu fβ (u) and uγ := arg maxu fγ (u) are supposed to exist and to be unique. Sect. it is proved in the Appendix.6 Precautionary effect in climate change mitigation Returning to the climate change mitigation problem exposed in Sect. M inf ρC a(1) +θ(2)D (1 − δ) =1 +αEbau (1 − a(1)) M .2. we have: 9 : =1 ) = inf EP0 ρC a(1) +θ(2)D (1 − δ)M Vβ (1. (1 − δ) (1 − δ)M ρc+θα2 Ebau 2 P0 2 2 ρc+Eθ0 [θ] α Ebau θρc This follows from the strict concavity of θ .→ fβ (u) − fγ (u) is increasing) verify uγ ≤ uβ .
→ and from Jensen ρc + θα2 Ebau 2 inequality. Now since the function a(0) .
→ M =(1) = (1 − δ) M =0 + αEbau 1 − a(0) is strictly decreasing. . This gives the following Result.3. we can apply Proposition 9.
2. there is a precautionary effect in the sense that the initial optimal abatement is lower with information than without: aHγ (0) ≤ aHβ (0) .234 9 Sequential decision under imperfect information Result 9. .4 Under the assumptions of Result 9.
Sophia Antipolis. Jullien. [6] L. . Gilotte. Journal of Economic Theory. In J. E. [10] C. École des ponts. Pereau. editor. 64(6):1006–1012. Bertsekas and S. Technical report. [5] A. 75:229–253. Pindick. Review of Economic Studies. Gollier. A separation theorem for expected value and feared value discrete time control. 1974. [2] K. Shreve. J. Journal of Public Economics. PhD thesis. [4] D. Akian. Fisher. Epstein. International Economic Review. Scientific progress and irreversibility: an economic interpretation of the “precautionary principle”. 21:269–283. [11] C. [9] C. J. Bernhard. 2000. Investment under Uncertainty. Projet Miaou. 1974. Roy. Investment decisions under uncertainty: The “irreversibility effect”. G. P. Treich. Quadrat. uncertainty. [12] L. 1998. Environmental preservation. Idempotency. J. Dixit and R. American Economic Review. Decision making and temporal resolution of uncertainty. Incertitude. Quarterly Journal of Economics. 2004. 41:89–104. Cambridge University Press. Dynamic efficiency of conservation of renewable resources under uncertainty. 1994. 1996. December 2000. Gunawardena. 1974. Duality between probability and optimization. B. and M. and irreversibity. [8] L.-P. 88:312–319. 95(2):186–214. Belmont. Doyen and J. Environmental Modeling and Assessment. Stochastic Optimal Control: The Discrete-Time Case. Princeton Uni- versity Press. 1980. Henry. Arrow and A. Henry. inertie et choix optimal. Olson and S.References [1] M.-C. Modèles de contrôle optimal appliqués au choix de politiques de réduction des émissions de gaz à effet de serre. The precautionary principle as a robust cost- effectiveness problem. INRIA. Massachusets. ParisTech. Athena Scientific. Viot. [3] P. [7] L. Option values in the economics of irreplaceable assets. revision. Décembre 1995. Université Paris-Est. C. and N.
John Wiley & Sons. 1982. Whittle. irreversibility and learning. Ulph.236 References [13] A. volume 1. . Optimization over Time: Dynamic Programming and Stochastic Control. [14] P. Global warming. Ulph and D. 1997. The Economic Journal. 107(442):636–650. New York.
. ⎟ ⎝ . 0 ⎟ ⎜ ⎟ ⎜ . . . ⎟ ⎜ ⎟ Ji = ⎜ . This proof is inspired by [5]. . . ⎜ . The Jordan Block Ji takes the form of ⎛ ⎞ λi 1 0 . . Jr ] . . . . .. Jrt ]P −1 tk−1 λti Rik . . i=1 k=1 where the matrix with general term Rik depends upon P and the upper part of the Ji . .. there exists a nonsingular matrix P (possibly complex) that transforms A into its Jordan form. λr }). . 0 λi ν ×ν i i where νi = ν(λi ) is the order of multiplicity of eigenvalue λi of A. . . . . ⎟ . .3 Proof. The state x(t) converges toward 0 if and only if limt→+∞ At = 0. ⎟ ⎜ . . we have . Equivalently. . for any matrix A. . J2t . 1⎠ 0 . . that is P −1 AP = J = Diag[J1 . . 3 Proof of Theorem 3. . . Recall that the solution of equation x(t + 1) = Ax(t) is given by: x(t) = At x(0) . . Mathematical Proofs A. Therefore r νi At = P J t P −1 = P Diag[J1t . 0 ⎜ 0 λi 1 0 . .. . . 0 ⎟ ⎜ ⎟ ⎜ . . where r is the number of distinct eigenvalues of A and Ji is the Jordan block associated with the eigenvalue λi of A (spec(A) = {λ1 . .A Appendix. J2 .1 Mathematical proofs of Chap. .. Moreover. ...
e ⎩ 0 if i = n .23a)- (3. . ⎟ ∂x ⎜ . . 0 . . as- sume temporarily that ie = n in the sense that: ⎧ ⎪ dn ⎪ ⎪ Re = . For the sake of simplicity.r |λi | < 1. . . Re ) = ⎜ ⎜ ⎟. ⎟ ∂F ⎜ 0 0 . . 1 − Δt (a + wn fn Nn.e ) − λ) + Δ2t Nn. Re ) − λI) = 0. ∀i = 1.. . . (Ne .23b). Δt Nn. . . .. ⎟ ⎜ . The last two λn and λn+1 are solution of P (λ) = 0 where P (λ) = (1 − λ)(1 − Δt (a + wn fn Nn. This is the exclusion principle. characterized as follows with Se large enough. From (3. We thus have at most n possible equilibria. .6 Proof. .. r . ⎟ ⎜ .e fn2 wn Re .23b) at xe = (Ne . ... 0 = Ni. 0 0 ⎜ 0 1 + Δt (f2 Re − d2 ) 0 0 0 ⎟ ⎜ ⎟ ⎜ ⎟ ⎜ .. a non-zero equilibrium Ne has only one non-zero component. Re ) is an equilibrium if.e ) ∂x (Ne .238 A Appendix. . . . Mathematical Proofs lim tk−1 λti = 0 . n . R). . ⎟ ⎜ ⎟ ⎝ 0 . ⎪ ⎪ fn ⎨ ⎧ ⎪ ⎨ Se − Re a > 0 if i = n .. 1 − Δt (a + wn fn Nn. ⎟ ⎜ .. .. . . . i=1 Excluding the exceptional case where di /fi = dj /fj for at least one pair i = j. ⎟ (Ne . 0 1 Δt Nn. t→+∞ which holds true if and only if supi=1. . ..e fn 0= (1 + Δt (fi Re − di ) − λ) . .e ) − λ i=1 We can see at once that the n − 1 first eigenvalues are λi = 1 + Δt (fi Re − di ). n 0 = Se − aRe − wi fi Re Ni.e (fi Re − di ) .. . Let us focus on one of them. Re ) is: ⎛ ⎞ 1 + Δt (f1 Re − d1 ) 0 0 . i = 1. −Δt wn fn Re .e fn ⎠ −Δt w1 f1 Re −Δt w2 f2 Re . ⎪ ⎪ ⎪ ⎪ N = Re wn fn ⎩ i. Proof of Result 3. .23a)-(3. −Δt wn fn Re ... that is: The eigenvalues λi are solutions of Det( ∂F n−1 1−λ ..e . and only if. the Jacobian matrix of dynamic F given by (3. Putting x = (N. .
then fi Re − di = 0 for i = 1. since Re = dn /fn and since we have excluded the exceptional case where di /fi = dj /fj for at least one pair i = j.. ⎪ ⎪ i=1. . P (0) = 1 − Δt (a + wn fn Nn. A.4.e ⎩ 0 if i = ie . among the possible equilibria.e fn2 wn Re . . it appears that |λn | < 1 and |λn+1 | < 1 because the necessary and sufficient conditions P (1) > 0. On the other hand. . we can write . 1] are satisfied. n − 1.. . then 0 < λi = 1 + Δt (fi Re − di ) < 1 for a small enough Δt > 0 and the equilibrium xe = (Ne . From the very definition of the viability kernel at time t...4. 4 Proof of Proposition 4.e ) . Re ) is unstable by Theorem 3. P (−1) = 2 2 − Δt (a + wn fn Nn. A. Indeed.2 Mathematical proofs of Chap. If fi Re − di < 0 for i = 1. The proof is by backward induction.e ) + Δ2t Nn.2 Mathematical proofs of Chap. . Proof. it is clear that Viab(T ) = A(T ). If fi Re − di > 0 for at least one i. . n − 1.11) is true at time t + 1 ≤ T . the only asymptotic stable equilib- rium satisfies the conditions: ⎧ ⎪ di di ⎪ ⎪ Re = min = e .n f fie ⎨ i ⎧ ⎪ ⎨ Se − Re a > 0 if i = i . At final time t = T .e fn2 wn Re . P (−1) > 0 and P (0) < 1 (valid for a second-order polynomial P ) of the so-called Jury test [4. P (1) = Δ2t Nn. Thus.2. Assume that the relation (4. then λi = 1 + Δt (fi Re − di ) > 1 and the equilibrium xe = (Ne . Re ) is asymptotically stable by Theorem 3. ⎪ ⎪ e ⎪ ⎪ N = Re wie fie ⎩ i... 4 239 For a small enough Δt .
this is equivalent to claiming the existence of u ∈ B(t. x. we have: 0 = min {W t + 1. let us evaluate the right hand side .240 A Appendix. . . u(T − 1)) and ∃ (x(t). Proof of Proposition 4. . u) ∈ Viab(t + 1). we have the equivalent of the desired statement: W (T. Expressed with characteristic functions. u(T − 1)) and ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎨ ∃ (x(t + 1). .3. Expressed with charac- teristic functions. u∈B(t. . x(T − 1). . . . x. x ∈ A(t) yields ΨA(t) (x) = 0 and. ∀s = t. x) such that ΨViab(t+1) F (t. F (t. / inf ΨA(t) (x) + W t + 1. x. u) = 0. F (t. ·) = ΨViab(T ) (·) = ΨA(T ) (·) . x(T − 1). ⎪ ⎪ ⎪ ⎪ ∀s = t. . . T − 1 ⎪ ⎪ ⎪ ⎩ ⎪ ⎭ x(s) ∈ A(s).x) Moreover. . For the sake of simplicity. u(s) . . . u) u∈B(t. x(s) . . . F (t. . . .13). . let us denote W (t. u) } . Whenever x ∈ Viab(t). T − 1 ⎪ ⎪ ⎪ ⎩ ⎪ ⎭ x(s) ∈ A(s). T − 1 ) * = x ∈ A(t) | ∃ u ∈ B(t. x. . ∀s = t + 1. F (t. ⎪ ⎬ Viab(t) = x ∈ X x(s + 1) = F s.x) Thus the assertion holds true since W (t. T − 1 ⎧ ⎫ ⎪ ∃ u ∈ B(t. x(T )) ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎨ such that x(t) = x. x) = ΨViab(t) (x) = 0. . ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ∀s = t + 1.2 that there exists u ∈ B(t. .x) of (4. u(s) . u(s) ∈ B s. x) := ΨViab(t) (x). . At time t ≤ T − 1. x. The unicity of equation (4. x(s) . x) satisfying F (t. x. x) . . .13) is clear. . we distinguish two cases. u∈B(t. u) ⎪ ⎪ ⎪ ⎪ x(s + 1) = F s. At final time t = T . u(s) ∈ B s. Proof. u) ∈ Viab(t + 1) and we conclude. u) } . x(s). . . . x. . Whenever x ∈ / Viab(t). . . it is clear that Viab(T ) = A(T ). x(s). we know from Proposition 4. x(T )) ⎪ ⎬ = x ∈ A(t) such that x(t + 1) = F (t. . consequently: 0 = min {ΨA(t) (x) + W t + 1. Mathematical Proofs ⎧ ⎫ ⎪ ∃ (u(t). In other words. x) ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ∃ (u(t + 1).
2 that. x. B (T ) B (T ) Denoting B (T ) = B . 4 241 • If x ∈ / A(t). we have F (t. We illustrate how dynamic programming equation (4. Proof of Result 4. B (T − 1)]. Consequently. B (T −1) = R(1−e ) . B ≤ RB(1 − e) ≤ B . u) } . B (T ) = B . B ] and: B ∈ Viab(T − 1) ⇐⇒ ∃e ∈ [e . x) = +∞ = inf {ΨA(t) (x) + W t + 1. RB RB which occurs precisely when B ∈ [B (T − 1).x) • If x ∈ A(t)\Viab(t). RB RB Hence. u∈B(t. in the same way. We have Viab(T ) = [B . e ] = ∅ .10. u) ∈ / Viab(t + 1). because B (T ) B (T ) B ≥ B (T − 1) ⇒ 1 − ≥1− = 1 − (1 − e ) = e RB RB (T − 1) and. for any u ∈ B(t. F (t. e ] . B (T −1) = R(1−e ) . Proof. we proceed in the same way by induction. e ] such that B (T ) ≤ RB(1 − e) ≤ B (T ). obviously ΨA(t) (x) = +∞ and therefore: W (t. F (t. thus meaning that: [B (T − 1). since B > 0. B (T − 1)]. for the other bound.11) can be used here. our claim is proved as soon as B (T ) B (T ) [1 − . we claim that whenever B ∈ [B (T − 1). . there exists e ∈ [e . u∈B(t.1 − ] ∩ [e . x) = +∞ = inf {W t + 1. Indeed. x). On the other hand. u) } . A. x. we know from Proposition 4. e ] . we have thus obtained that: Viab(T − 1) ⊂ [B (T − 1).x) which concludes the proof. B (T − 1)] . B B ⇐⇒ ∃e ∈ [e .2 Mathematical proofs of Chap. x. we have: B (T ) B (T ) B (T ) ≤ RB(1 − e) ≤ B (T ) ⇐⇒ 1 − ≤e≤1− . we obtain W (t. ≤B≤ R(1 − e) R(1 − e) where we used the fact that 0 ≤ e ≤ 1 . B (T − 1)] ⊂ Viab(T − 1) . For the rest of the proof. B B ⇒ ≤ B ≤ R(1 − e ) R(1 − e ) where we used the fact that 0 ≤ e ≤ e ≤ e ≤ 1 .
the viability kernel at final time T is given by: Viab(T ) = [−∞. M ≤ . we deduce that M (t + 1) − δM∞ = M (t) . we deduce the existence of a time T such that B(T ) ≤ B (T ) < hlim . A. Proof. M (t + 1)] × R+ . we deduce that: .12. inf M + E(Q)(1 − a) − δ(M − M∞ ) ≤ M (t + 1) a∈[0. A. h(·) with B(0) = B0 that remains in Viab in the sense that: hlim ≤ h(t) ≤ B(t) . 1−δ From definition of M (t) in (4. Viab(t) = (M.1. Now we assume that hlim ≤ hmse .242 A Appendix. Then. there exists a path B(·).2 and A.From the very definition of the viability kernel.13). combining Lem- mas A.13). The main proof is detailed below. We use the three Lemmas A. Suppose for a moment that Viab = ∅ and pick any B0 ∈ Viab. The proof relies on the three Lemmas A.3 in this case. Since hlim > hmse . Q)| ∃a ∈ [0. M + E(Q)(1 − a) − δ(M − M∞ ) / ≤ M (t + 1). Using the Bellman equation (4. a contradiction occurs.1 yields Bpa = +∞. M (t)] × R+ . we reason backward using the dynamic program- ming method as in (4. Q(1 + g) ≥ 0 ) * = (M. Q)| Q ≥ 0.1] 4 3 = (M.25). Q)| Q ≥ 0.2 and A. Proof of Result 4. M − δ(M − M∞ ) ≤ M (t + 1) ) * M (t + 1) − δM∞ = (M. M ] × R+ . Assume now that at time t + 1 the viability kernel is: Viab(t + 1) = [−∞. To prove this result. .3 to obtain the desired assertion. 1−δ and conclude that Viab(t) = [−∞. Consequently.11. Q)| Q ≥ 0.3 that are exposed at the end of the proof.2 and A. 1]. Mathematical Proofs Proof of Result 4.1. First assume that hlim > hmse . Proof. Lemma A. First. we proceed in two steps as follows. Following Thorem 4.8. Therefore B0 ∈/ Viab which ends this part of the proof.
B ≥ hlim . g(B − hlim ) ≥ B} . there exists an admissible h such that g(B − h) ∈ V . There then exists a solution B(·) starting from B0 that remains in Viab. Thus we conclude that V ⊂ Viab. consider any B ∈ V . Therefore B0 ∈ / Viab which ends this part of the proof. g(B − h) ∈ Viab . A. 2.1. Given any initial state B ∈ Viab. we can write that: g(Bmse − hlim ) ≥ g(Bmse − hmse ) = Bmse . Since g is increasing. 4 243 1. . Now. (A.2. B ≥ hlim . we know that Bpa < +∞ and the set V makes sense. Indeed. namely B ≥ Bpa . Second. we prove that [hlim . Now consider any B0 such that hlim ≤ B0 < Bpa and assume for a moment that B0 ∈ Viab. Lemma A.1) This set A is not empty because Bmse belongs to it. Combining Lemmas A. Moreover since hlim ≤ hmse and g increasing. Proof. Pick the lowest admissible catch hlim .1) Assume that hlim ≤ hmse . Consider the set: A = {B. Consequently. The set of viable catches corresponds to: ) * H Viab (B) = h ≥ hlim . this means equivalently that B − h∗ (B) ≥ Bpa − hlim or the desired result: hlim ≤ h∗ (B) ≤ B − Bpa + hlim . Bmse ≥ hmse ≥ hlim . We derive a contradiction with B0 ∈ Viab. g(B − hlim ) ≥ B = Bpa < +∞ if hlim ≤ hmse . any h∗ (B) ∈ H Viab (B) satisfies: g B − h∗ (B) ≥ g(Bpa − hlim ) = Bpa . B) ≥ g(Bpa − h ) = Bpa . Furthermore A is bounded from below by hlim which implies the existence of the minimum for this set.3 and A.2 Mathematical proofs of Chap. 2. this set H Viab (B) is not empty. Since Bpa > hlim we also have V ⊂ [hlim . Since g is increasing. (Lemma A. We first prove that the set V = [Bpa . 1. we deduce the existence of a time T such that B(T ) ≤ B (T ) < hlim . Such a minimum lies on the lower boundary of the set and satisfies the equality g(B − hlim ) = B. From Lemma A. Thus Bpa exists. +∞[. V is a viability domain. Thus for any B ∈ V . we can write: g(B − hlim .1 We have: ) * +∞ if hlim > hmse . +∞[ is a viability domain and a subset of Viab. inf B. Since dy- namic g is increasing and Bpa = g(Bpa −hlim ). Bpa [ ⊂ R+ \Viab.
A. . Assume the relation holds true at time t. Lemma A. x(t) .2) The maximum is achieved because g is continuous. Proof.1). ⎬ T ad (t. . T − 1 . t = t. (Lemma A. T − 1 . At time t = 0. B0 ] such that: g(B ∗ − hlim ) − B ∗ ≥ 0 . . we have: B0 = B(0) ≤ B (0) ≤ B0 + tM = B0 ≤ B0 .3 Mathematical proofs of Chap.4 Proof. 5 Proof of Proposition 5. Thus: B ∗ ≥ min B = Bpa . Then: B (t+1) = B (t)+g(B (t)−hlim )−B (t) ≤ B (t)+M ≤ B0 +(t+1)M ≤ B0 . . for any admissible h(t) ≥ hlim and B(t) ≤ B (t). u(·) x(t + 1) = F t. There then exists B ∗ ∈ [hlim . . ⎩ ⎭ u(t) ∈ Bviab t. let us recall (4. for any t ≥ 0. . Moreover.2 Consider any B0 such that hlim ≤ B0 < Bpa and M= max g(B − hlim ) − B . .244 A Appendix. . we claim B(t + 1) = g B(t) − h(t) ≤ g(B (t) − hlim ) = B (t + 1) . Proof.4. we have: B(t) ≤ B (t) ≤ B0 + tM ≤ B0 .3 Consider B (t) the solution of B (t+1) = g(B (t)−hlim ) start- ing from B0 with hlim ≤ B0 < Bpa . This situation implies that B ∗ ∈ A where A is the set defined in (A.3) Recursive proof. u(t) .16) ⎧ ⎫ ⎨ x(t) = x. x(t). Mathematical Proofs Lemma A. Then. hlim ≤B≤B0 Then M < 0. since g is increasing. x) = x(·). As- sume for a moment that M ≥ 0. and any admissible solution B(·). B. t = t. B∈A We derive a contradiction since B ∗ ≤ B0 < Bpa . In Proposition 4. thus concluding the proof. (Lemma A.
u(·) ∈ T ad t + 1.x) s=t = sup sup ⎧ ⎨ x(t) = x ∈ A(t) x(·). u(·) ∈ T ad (t. x ∈ Viab(t)). x(t). u(s) + M T. x) = ∅. we may have T ad (t. u(t) . x.x. x(s). x) ⎪ ⎩ x(·).F t. x) = ∅ (that is.u(t) ⎩ u(t) ∈ B(t. u) u∈B(t. F t. x(s). x(T ) s=t+1 = sup L(t. x) ⇐⇒ u(t) ∈ B (t. x) = sup L s. x(T ) x(·).3 Mathematical proofs of Chap. as well as Bviab (t. In the above expression. u(s) + M T. A.x). 5 245 which gives ⎧ ⎪ ∈ A(t) ⎨ x(t) = xviab x(·). x.x∈A(t) . We have: T −1 V (t. u(t) + L s.u(·) ∈T ad (t. x) T −1 L t.u(·) ∈T ad t+1.
supz∈Z b(z) . u) + V t + 1.x). the minimax with final payoff may be interpreted as one without payoff on a longer time horizon. b(z) = min a. Notice that by changing T into T + 1 and defining L(T. x(T ) T −1 + sup x(·).4 given above. u∈B(t. Proof of Proposition 5. We proceed similarly to the additive case. . x. u(s) + M T. x .x∈A(t) Then we distinguish the cases x ∈ Viab(t) and x ∈ Viab(t). Proof of Proposition 5.x. F (t. x. We have1 : 1 From the relation supz∈Z min a. u) = M T. L s.20 Proof.F (t. x. x(s).u(·) ∈T ad t+1.5 Just adapt the proof of Proposition 5. u) .u) s=t+1 = sup L(t.
f (x.x∈A(t) Then we distinguish the cases x ∈ Viab(t) and x ∈ Viab(t).x.T −1 L s. x... x (t) ∂x ∂x & ' ∂V ∂F + t + 1.u(·) ∈T ad (t...T −1 x(·).. At time T . x (T ) = ( ) T. x → maxy∈V f (x. This proof is by backward induction.246 A Appendix. min L s. x. u∈B(t. x (t). y) = g(x)}. u t. y) and V< (x) = {y ∈ V. u t. x (T ) . y). F t. V t + 1. x. x (t). x) = sup min L s. ∂x ∂x By assumption. u) .F t..T −1 & = sup min L(t. ∀h ∈ Rn . u(s) s=t. x(s).13 Proof. u). x) & ' min L(t. u t. u(s) x(·). ∂x ∂x Using the induction hypothesis 2 We recall here the Danskin theorem (1966) that expresses the derivative of the superior hull of functions in a particular case [3].x∈A(t) ' sup mins=t+1. the equality q (T − 1) = ( ∂M ∂x ) T.16) at point x = x (t): ∂V ∂L t.u(·) ∈T ad t+1. u)..u(t) ⎩ u(t) ∈ B(t. Theorem A. x (t) . C 1 with respect to the first variable. x (t). u).x). g has > a directional ? derivative in the direction h given by Dg(x.. Thus. according to induction (5. x).u(t) & ' = sup min L(t. Let V be a compact of Rm and f : Rn × V −→ R.x) = ⎧ sup sup ⎨ x(t) = x ∈ A(t) x(·). Mathematical Proofs V (t.16).. jointly continuous.F t. x (t) = t.. x. . F (t.40) for the adjoint state.20) is unique. h . x(s). we have V (T.x). x (t) in (5.. h) = maxy∈V< (x) ∂f ∂x (x. x(s). x (t) t. Let us denote g : Rn → R. u(s) s=t+1. Then.x. x (T ) holds true.. u∈B(t. we may apply the Danskin theorem2 to (5.4. Thus: ∂M ∂V q (T − 1) = ( ) T. u t. On the other hand.u(·) ∈T ad t+1. x) = M (T. according to equa- tion (5. Proof of Proposition 5.
x0 ) ≥ inf L(t. this implies the existence of a feasible path @(·). from the definition of the value function V (t0 . u t. t=t0 . un (·) n≥1 in the sense that: 1 V (t0 . A.T −1 L t..3 Mathematical proofs of Chap. . L ). x (t + 1) . consider the initial time t0 and the initial state x0 . u @(t) ≥ L and we deduce that: V (t0 .. L )} .. Hence the equality holds true. 5 247 ∂V q (t) = ( ) t + 1. From the very definition of the viability kernel. Conversely. x0 ) − .. T − 1 ⎪ ⎪ ⎨x@(t0 ) = x0 @(t) ∈ A(t) x . x0 ) − n1 which leads to 1 V (t0 . ∂x we can deduce that ∂V ∂L ∂F t. . x @(t) ≥ L . x (t) + q (t) t. T − 1 ⎩ L t. T − 1 . x0 ) ≤ sup{L ∈ R | x0 ∈ Viab(t0 . We proceed in two steps. . x0 ) − ≤ sup{L ∈ R | x0 ∈ Viab(t0 . . x (t) . t = t 0 . x (t) + q (t) t. t = t0 . . for any N. u t.. First.22 Proof. x (t). x @(t) ≥ L . x (t) .. t= t0 . . . xn (t). ⎧ ⎪ ⎪ @(t + 1) = F t.@ x Since the inequality holds for any L . t = t0 .2) ⎪ ⎪ ⎪ @ ⎪ u (t) ∈ B t. . ∂x ∂x Proof of Proposition 5. .T −1 u(·) satisfying (A. ∂x ∂x ∂x and thus ∂L ∂F q (t − 1) = t. u L t. . . Pick some L such that x0 ∈ Viab(t0 . u t. x (t). . u t. ... u x @(·) such that. x0 ) = sup inf @(t).. T (A. . x (t) = t. . V (t0 . . .2)) and maximizing sequence n ∈ xn (·). u @(t) . t=t0 . u We thus have inf t=t0 . L )} n and finally: V (t0 .T −1 n This situation implies x0 ∈ Viab t0 . x (t). x0 ) ≥ sup{L ∈ R | x0 ∈ Viab(t0 . x x @(t)... x0 ).. x(t) . this leads to: V (t0 . un (t)) ≥ V (t0 . thereexists an admissible (satisfying (A. @(t). x (t). x @(t). L )} .2) @ (·).
x(t). (A. (A.ω2 ) [A (ω1 . (A.ω2 ) [A (ω1 . for an adequate function A.P1 ) E(Ω2 .3) ω∈Ω When Ω = Ω1 × Ω2 . When Ω = Ω1 × Ω2 .F1 .5) Ω When Ω = Ω1 × Ω2 . ⎨ t = t0 . ω2 )] = Gω1 [Gω2 [A (ω1 . w(T )) . The so- called expectation operator E(Ω.1 is purely notational. we shall stress the dependency of the criterion upon the initial time by considering a criterion π as a function π : N × XT +1 × UT × WT +1 .4) Consider a probability space Ω with σ-field F and probability P. u(·). u(·). .P) [A] = Eω [A (ω)] = EP [A (ω)] = A (ω) dP(ω) . x(·).P2 ) [A (ω1 . ω2 )]] . (A.P) [A] = E(Ω1 .248 A Appendix. ω2 )]] .F2 .8) . w(t).F .7) Maximization problem In this proof. F = F1 ⊗ F2 and P = P1 ⊗ P2 . and for the parallel treatment with the stochastic case.F . π t + 1. ω2 )] . x(·). The so-called fear operator FΩ on Ω is defined on the set of functions A : Ω → R by: FΩ [A] = Fω [A (ω)] := inf A (ω) . T − 1 . Fear and expectation operators Let R = R ∪ {−∞} ∪ {+∞}.6) Let G denote either F or E depending on the context. we have the formula: FΩ [A] = F(ω1 . ω2 )] = Fω1 [Fω2 [A (ω1 . Let us call a criterion π in the Whittle form [6] whenever it is given by a backward induction of the form: ⎧ ⎪ ⎪ π t. (A. . u(t). ⎪ ⎪ ⎩ π T. (A. w(·) = M (T.4 Robust and stochastic dynamic programming equations We follow [2] for the introduction of the so-called fear operator. . Mathematical Proofs A. w(·) = ψ t. x(T ). we have GΩ [A] = G(ω1 . Consider a general set Ω. . 6.F . u(·). we have the Fubini formula: 0 1 E(Ω. x(·). The difference with the definition in Sect. w(·) .P) is defined on the set of measurable and integrable functions A : Ω → R by: 2 E(Ω.
C). . w) + C and the multi- plicative case for which ψ(t. u. w(·) . w(·) (A. x0 .w(t+1). (A. uF are the solution maps of Sect. w). u. . w(·)](·). . . . u. x0 ) := Gw(·) π u t0 . x) ∈ B(t. u. Define 0 1 u πG (t0 . . u. x. x0 ) . x. . . ∀(t. u. w(t). w(·) ∈ Ω. x. w) + β(t. u. x. with Ω = S(t0 ) × · · · × S(T ) . Recall the admissible feedbacks set (6.2. T − 1} × X × U × W × R → R is assumed to be G-linear in its last argument in the sense that: Gw(t). x0 ∈ X.9) We illustrate what means to be G-linear when G is either F or E. (A. u. x. T − 1}.. . This form includes the additive and the multiplicative cases. x. (A. and Cn → C ⇒ ψ(t. . u.13) where t0 ∈ {0. (A. x. w. t = t0 . x. C) = L(t.15) u∈Uad 3 ψ(t. T − 1 with x(t0 ) = x0 . . Cn ) → ψ(t. A. u. C ) whenever −∞ ≤ C ≤ C ≤ +∞. • When G is the expectation operator E.14) and consider the maximization problem: u πG (t0 . u. . G [A (w(t + 1). w)C.. u. . x0 . w. . . . T ).12) and. . . x0 ) := sup πG (t0 . w. x. the evaluation (8. x. w(·) := π t0 . x(t) ⊂ U. u. ψ is assumed to be continuously increasing in its last argument3 . .11) and no state constraints (A(t) = X for t = t0 . w(·)](·). . w. C) = min(L(t. w) × C. 6.1) x(t + 1) = F t. . x. C) = L(t.4 Robust and stochastic dynamic programming equations 249 The function ψ : {t0 . xF [t0 . and xF . w. w. We consider the dynamics (6. x0 .10) the control constraints (6. u. w(T )))] = Gw(t) [ψ (t. • When G is the fear operator F. C) = g(t.5a) u(t) ∈ B t. . x)} . C) and includes both the additive case for which ψ(t. C ) ≥ ψ(t.. w. x) .w(T ) [ψ (t. A (w(t + 1). w(T ))])] . (A. . w(t) . x. . This form is adapted to maximin dynamic program- ming with ψ(t. for any admissible decision strategy u ∈ Uad . (A. u(t). w. .4) of the criterion π u t0 . x. u.. x(t).12) Uad = {u ∈ U | u(t. x0 . uF [t0 . u. x. w. u. ψ(t. x.
V t + 1. u (t. x. F (t. Proof. u. Furthermore. w . Assume that A(t) = X for t = t0 . x) = Gw∈S(t) ψ t.250 A Appendix.16) = V (T. u (t. w. x. .16).17) u∈B(t. V t + 1. for any u ∈ Uad . x. w. For any time t and state x. . the control constraints (A. F (t.10). . x) = Gw(·)∈Ω π u T. πG t+1. x) := sup Gw∈S(t) ψ t.16) ⎪ ⎩ V (t. x).17) u∈B(t. F (t. x) by (A. w. u. the dynamics (A. First. x) by (A. w) by (A.7 (proved below) implies that: 9 : u u πG (t. x. Let u ∈ Uad denote one of the optimal feedback strategies given by dynamic programming (A. the equality at t = T holds true since: 9 : u πG (T. . x) . where t runs from T − 1 down to t0 : ⎧ ⎪ V (T. w)] by (A.14) 9 : = Gw(·)∈S(t0 )×···×S(T ) π u T. u.8). . . w.15). w(·) by (A. . w) by (A.15). x. V t + 1. u (t.18) 9 : = max Gw∈S(t) ψ t. x).17). F (t. . x. w . assume the existence of the following feedback decision: 9 : u (t. x). w) by (A. u. x).x) = V (t.18) u∈Uad The very definition (A.16). w. V t + 1. We perform a backward induction to prove (A. suppose that: u u πG (t + 1.19) 9 : = Gw∈S(t) ψ t. ⎨ 9 : (A. x). x. x. u∈B(t. we obtain: . (A.x) Proposition A. x. x. x) := Gw∈S(T ) [M (T. x. x.11) and no state constraints (A(t) = X for t = t0 .16) of the value function V combined with (A.x) Then u ∈ Uad is an optimal feedback of the maximization problem (A.6.19) in Lemma A. u (t. u. (A. Mathematical Proofs Dynamic programming equation Definition A.5. x) = V (t + 1. x) ∈ arg max Gw∈S(t) ψ t. x) = sup πG (t + 1. The value function V (t. w)] . Now. F (t. u. associated with the Whittle cri- terion (A. x. T ) is defined by the following backward induction. T . x. w(·) = Gw∈S(T ) [M (T.
π t. . (Lemma A. x) = Gw∈S(t) ψ t. x) = Gw∈S(t) [ψ (t.13). u(t. w(·) = π u t.) By (A. .7. x). x) = πG (t. x) = V (t.8) and (A. according to (6. x). x. w(t). . x.21) We have: . u (t. A. . for t = t0 . (A. x. u. Proof. V t + 1. w)))] . Consequently. x) = Gw∈S(T ) [M (T. x) by (A. x).7. u. π u t + 1. x). x. (A. πG t+1.18) 9 : ≥ max Gw∈S(t) ψ t. x. . . x). x. u(t. x. w. F (t.4 Robust and stochastic dynamic programming equations 251 9 : u u πG (t. w) u∈B(t. w(t). x). u∈Uad Lemma A.13). u(t. x.19) ⎩ πGu (t. the desired statement is obtained since u πG (t. x. w) by (A. . w)] (A.20) u Notice that. x.19) 9 : ≥ Gw∈S(t) ψ t. x. x) . u(t. . w(T ) ⎪ ⎩ π u t. . x) u∈Uad yields the equality: u u V (t. w. x. x. w(·) depends in fact only upon w(t). w. w(·) . x. x). T − 1 and u ∈ U: ⎧ u ⎨ πG (T. w(t)). V t + 1. x) ∈ B(t. we have: ⎧ u ⎪ ⎨ π T. x. We have. F (t.x) since u ∈ Uad hence u(t. x. w(·) = M T. . w(T − 1) insofar as w(·) is concerned: π u t. πGu (t + 1. w(T − 1) . x) = V (t. F (t. u(t.16). . x) ≤ sup πG u (t. w) by (A. x. x). F (t. u (t. w. . u(t. w(·) = ψ t. x) = max πG (t. F (t.
x.14) = Gw(·)∈Ω [ψ (t.20) 6 = Gw(·)∈S(t)×···×S(T ) ψ t. F (t. . x. w. x. x). x. w(T − 1))) by (A.. πG u (t+1. w. x) = Gw(·)∈Ω [π u (t. w))) by (A.21) + - = Gw∈S(t) ψ (t. x). w(t+1). x). w(·) = 1A(t) (x(t)) . x. w(t). . w(·)))] by (A. Apply the generic Proposition A. x. 7 Proof of Proposition 7. π u (t+1. w..252 A Appendix. Viab1 (t) = x0 ∈ X sup inf π t0 . u(t. w(·) = 1 . w(·))] by (A. x). . x). x(·). 7 w(t + 1). x. w(t)). x. u(t. u(t.7)6 = Gw∈S(t) ψ t. u(·).w(T −1))∈S(t+1)×···×S(T ) 7 1 ψ (t.6 with the expectation operator G = Ew(·) and with ψ(t.. . u(t. x). x).5 Mathematical proofs of Chap.w(T −1))∈S(t+1)×···×S(T ) 7 0 × π u (t + 1. u(t. w(t + 1). Mathematical Proofs u πG (t. A. . u. w(t)). u(t. G(w(t+1). w(·) u by (A. t=t0 Notice that: . π u (t + 1. x. w. w.. . w(T − 1)) by (A. u(t. . Apply the generic Proposition A. w(T −1))) by (A. .. . x.6 with the fear operator G = FΩ and with ψ(t. . F t. x(·).14). w(t). x). w(t). F (t. Gw(·)∈S(t)×···×S(T ) 9 - : × π t + 1. x.. x. x. . u(t. u(t.21) 6 0 = Gw(t)∈S(t) G(w(t+1). w(t)).9) + because ψ is G -linear in its last argument = Gw∈S(t) ψ t. u(·) w(·) Proof of Proposition 7. F (t. x. π u (t + 1..5 Proof. F (t.. x). C) = 1A(t) (x) × C and: T π t0 .10 Proof. F (t. u(·). . u. C) = 1A(t) (x) × C and: . x.
w.u. w. u. x.4 with ) @ ψ(t. x(·). C) = L(t. x. x.6 Mathematical proofs of Chap. C) = min(L(t.4 Proof. u. x. x.12 Proof. x. w(·) = 1A(t) (x(t)) .6 Mathematical proofs of Chap. x. u(·). x. u. w. C) = L(t.6 with the fear operator G = FΩ and with ψ(t. . w) = M (t. w) if x ∈ A(T ) M −∞ if not. A. x) > −∞ . Apply the generic Proposition A. w. w) + C. x. Under the additional technical assumptions inf x. w) + C.6 with the expectation operator G = Ew(·) and with ψ(t. u. Apply the generic Proposition A. u. Proof of Proposition 8. x(·). we prove that x ∈ Viab1 (t) ⇐⇒ V (t. Proof of Proposition 8. Adapt the previous proof of Proposition 8. and ) =(T. x. 8 253 T π t0 . C) if x ∈ A(t) ψ(t. w > −∞ and inf x. u. u(·).w L t. w. u. 8 Proof of Proposition 8. x. u.w M T. x. w > −∞. w(·) ≥ β . Proof of Proposition 8.6 with the fear operator G = FΩ and with ψ(t. u(·) A. u. C) = −∞ if not. w).8 Proof. 0 1 Viabβ (t) = x0 ∈ X sup Ew(·) π t0 . C).6 Proof. t=t0 Notice that: . Apply the generic Proposition A.
Adapt the previous proof of Proposition 8. R R R∈S R∈{R . we write 9 : ER Ψ A(2) (B(1−e)) = P(R(1) = R )Ψ A(2) (B(1 − e)) R R +P(R(1) = R )Ψ A(2) (B(1 − e)) R = Ψ A(2) (B(1 − e)) + Ψ A(2) (B(1 − e)) R R = Ψ A(2) ∩ A(2) (B(1 − e)) .14 Proof.254 A Appendix. x. w. u. A. w. Mathematical Proofs Proof of Proposition 8.12 with ) @ ψ(t. x. R R Thus Vβ (1. On the one hand. B ] = =∅. w) = M (t. B) = inf ρC(1 − e) + ΨA A(2) (B(1 − e)) . e∈[0. x. We use the notation ΨA (·) for the characteristic function of the domain A defined by: ) 0 if B ∈ A ΨA (B) = +∞ otherwise.1] R(1) Using the fact that resource productivity R(1) has a discrete support S = {R .7 Mathematical proofs of Chap. C) if x ∈ A(t) ψ(t. u.R } . e∈[0. w) if x ∈ A(T ) M −∞ if not.1] 6 7 = inf ρC(1 − e) + ER(1) Ψ A(2) (B(1 − e)) . R }. Proof.1] R∈S R B R The condition B < R yields that: B A(2) B [B . We reason backward using the dynamic programming method. 9 Proof of Result 9. C) = −∞ if not. B) = inf ER(1) ρC(1 − e) + ΨA(2) (R(1)(B(1 − e))) e∈[0. x.1. the Vβ value function at time 1 is given by: 6 7 Vβ (1. and that P(R(1) = R ) > 0 and P(R(1) = R ) > 0. and ) =(T.
R. then. R) = ρC(1 − e (1. B) = +∞. 9 255 Consequently. R We now have to distinguish two cases to compute ER(1) [Vγ (1. Thus: Vγ (1.+∞[ (B) . 1]. e ∈ [0. In R <−1 = E[R−1 ]. B) = 1 − RB because A(2) = [B . R. R. B) = ER [ρC(1 − e (1. for any R ∈ S = {R . RB(1 − e) ∈ A(2)} is not empty if and only if B ≥ BR . [ . By dynamic programming and backward reasoning. we deduce that Vβ (0. then. since effort cost C(·) is positive: υ(1. In this case.+∞[ (B) = +∞ . 1]. B ].7 Mathematical proofs of Chap. R(1))] = υ(1. which means that the target cannot be reached no matter what the state B is at time 1. (B) . we obtain ΨA A(2) (B) = +∞ and thus R∈S R Vβ (1.1] =) inf ρC(1 − e) . since C(1 − e) = c(1 − e) decreases with e and is linear. B)). the Vγ value function with learning at time 1 is given by: Vγ (1. 1]. using the certainty equivalent R < ρC(1 − e (1. R. B. B)) e ∈ [0. RB(1 − e) ∈ A(2) The constraint set {e ∈ [0. B) = ρC(1 − e (1. B))]. R) = inf ρC(1 − e) + ΨA(2) (RB(1 − e))) e∈[0. B) = that case.+∞[ (B) = 0 and consequently υ(1. R • If B ≥ BR .+∞[ R Using the dynamic programming method and similar reasonings. R }. B • If B < R . we also de- rive the adaptive precautionary value function at initial time t = 0: . B) ≥ Ψ[ B . R. Therefore: < B)) + Ψ B υ(1. B) = +∞ . R. B) . B. B)) + Ψ[ B . B. RB(1 − e) ∈ A(2) B where e (1. we can write ) inf ρC(1 − e) = ρC(1 − e (1. for any B. A. we have B ≥ BR or equivalently Ψ[ B . On the other hand. we write υ(1.
we obtain: Vγ (0.1] 6 7 +ER(0) Ψ[ B . R. <2 B(1 − e)2 R C ρB The solution is given by e (0. θ) = C(a1 ) + θD (1 − δ)M . 1]. R. R. < R(0)B(1 − e))) e∈[0.+∞[ 2 R For any B ∈ [ RB 2 . ⎩1−e≥ B R 2 B Now we compute the optimal initial feedback e (0. we have: 9 : =1 ) = inf EP0 ρC a(1) + θ(2)D (1 − δ)M Vβ (1.2.256 A Appendix. B) = 1− < 2B R which turns out to be an interior solution if 0 < ρ < 1 and B ∈ [ RB 2 . ⎨e ∈ [0. B) = ⎧ inf < < C(1 − e) + ρC(1 − e (1. < RB(1−e)))+Ψ < (B(1−e)) . in the case of learning about damage intensity θ = θ0 . We combine the first order optimality conditions associated with Vγ (0.1] [ B .+∞[ (R(0)B(1 − e)) R = inf C(1−e)+ρC(1−e (1. R(0)B(1 − e))] e∈[0. e∈[0. M =1 + αEbau 1 − a(1) . M inf ρC a(1) +θ(2)D (1−δ) =1 +αEbau (1−a(1)) M .1] = inf C(1 − e) + ER(0) [υ(1. +∞[. we first compute the second period cost minimization with and without information. R(0)B(1 − e))) e∈[0. RB(1 − e))) . Proof of Result 9. Proof. B) and the linear costs C(1− e) = c(1 − e) to obtain: & ' ρB 0 = c −1 + . Without information. f (a1 . ·). Mathematical Proofs 6 7 Vγ (0. θ0 0≤a(1)≤1 Similarly. +∞[. appears the quantity =1 + αEbau 1 − a1 . we compute 6 7 =1 ) = EP0 Vγ (1. To solve the overall optimization problem. B) = inf ER(0) C(1 − e) + υ (1. θ0 0≤a(1)≤1 In both expressions.1] 9 : = inf C(1 − e) + ER(0) ρC(1 − e (1.
θ0 0≤a1 ≤1 Since C(a) = ca2 and D(M =) = M =2 are quadratic. θ) . M inf f (a1 .7 Mathematical proofs of Chap. M inf f (a1 . θ) . 9 257 with =1 ) = Vβ (1. 0≤a1 ≤1 where θ = EPθ00 [θ0 ]. so is a1 . while 6 7 =1 ) = EP0 Vγ (1. A.
(1 − δ)M a1 ∈R 2 2 ρc + θα Ebau It can be proved that the function θ .→ f (a1 . θ) = =1 + αEbau 2 . θ) = f (a1 (θ). and its minimum is achieved at =1 + αEbau θαEbau (1 − δ)M a1 (θ) = . ρc + θα2 Ebau 2 giving θρc inf f (a1 . θ).
θ ] and θρc inf f (a1 . using assumption (9. =0 + αEbau αEbau (1 − δ) (1 − δ)M Thus a1 (θ) ∈ [0. since the unknown parameter θ0 is supposed to follow a probability distribution P0 having support within [θ . θ) = =1 + αEbau 2 . M =1 + αEbau (1 − δ)M . 0≤a1 ≤1 2 2 ρc + θα Ebau Thus. (1 − δ)M ∀θ ∈ [θ . 1] for any θ ∈ [θ .15) & ' ρc 0 = a1 (0) ≤ a1 (θ ) ≤ a1 (θ ) ≤ a1 . θ ] . θ ]. =0 + αEbau αEbau (1 − δ) (1 − δ)M By virtue of inequalities =1 ≤ (1 − δ)M M =0 + αEbau (1 − a) ≤ (1 − δ)M =0 + αEbau .→ a1 (θ) is increasing. we obtain that EPθ00 [θ] ρc 2 =1 ) = Vβ (1. we claim that & ' ρc a1 ≤1. ρc + EPθ00 [θ] α2 Ebau 2 and that . Consequently.
we deduce that: Vγ (1. (1 − δ)M P 2 2 ρc + θα Ebau ρc + Eθ0 [θ] α2 Ebau 0 2 θρc This follows from the strict concavity of θ . Mathematical Proofs 6 7 θρc =1 ) = EP0 Vγ (1. M=1 ) − Vβ (1.258 A Appendix. M =1 ) = 6 7 θρc EPθ00 [θ] ρc EPθ00 − =1 + αEbau 2 < 0 . M =1 + αEbau 2 . (1 − δ)M θ0 2 2 ρc + θα Ebau Hence.
Let ug ∈ Dg . 3. sup Dg ]. If h is strictly decreasing on [inf Dg . then sup Dg+h ≤ inf Dg . For any u ∈ D. Proof of Proposition 9. then sup Dg ≤ inf Dg+h .3. +∞[. Proposition A.→ and from Jensen ρc + θα2 Ebau 2 inequality. 2. +∞[. then sup Dg ≤ sup Dg+h . Proof. then inf Dg+h ≤ inf Dg . We denote Dg := arg max g(u) ⊂ D and Dg+h := arg max(g + h)(u) ⊂ D . +∞[. we have h(u) < h(ug ) if h is strictly increasing. sup Dg ]. If h is strictly increasing on ] − ∞. we have g(u) ≤ g(ug ). We conclude that Dg+h ⊂ [ug . 1. g ∈Dg u thus proving that sup Dg ≤ inf Dg+h . so that: B Dg+h ⊂ [ug . . Thus: u ∈] − ∞. If h is increasing on ] − ∞. If h is decreasing on [inf Dg . We prove the first statement. ug [ ⇒ g(u) + h(u) < g(ug ) + h(ug ) . let g : D → R and h : D → R. the others being minor variations. Let D ⊂ R. +∞[ = [sup Dg . +∞[ . ug [. u∈D u∈D and we assume that Dg = ∅ and Dg+h = ∅.8. 4. For any u ∈] − ∞.
Theory and Application of the z-transform Method. New York. siam. Technical report. Optimization over Time: Dynamic Programming and Stochas- tic Control. Prentice-Hall.J. Décembre 1995. H. Åström and B. Computer Controlled Systems: Theory and Design. Philadelphia. New York. 1995. John Wiley & Sons. 1990. Nonlinear Systems. Khalil. Classics in mathe- matics. K. Projet Miaou. 1982. . Information and Systems Sciences Series. second edition. Prentice-Hall.References [1] K. Wiley. Sophia Antipolis. Englewood Cliffs. Whittle. Jury. A separation theorem for expected value and feared value discrete time control. [4] E. Optimization and Nonsmooth Analysis. 1984. Bernhard. Wittenmark. volume 1. [2] P. [3] F. 1964. Clarke. I. INRIA. [6] P. [5] H.
198. 68 adjoint equilibrium. 3. 82. 113. 111 Bellman certainty equivalent equation. 132. 197. 206 maximin. 193. 68. 156 function climate change. 172. 24. 16. 140 expected. 133 bird variable. 85. 164 agriculture. 76 maximin. 141. 2. 109. 18. 203. 184 mitigation. 137 state. 158.Index abatement. 102 criterion. 22. 24. 111 bau. 43. 24. 19. 64 catchability coefficient. 204 climate-economy. 27 Beverton-Holt additive model. 164 principle. 196 abundance. 200 optimality. 57 baseline. 173 Chichilnisky viability. 24. 224 stock-recruitment relationship. 114 characteristic function. 173 abatement. 197. 212 control. 41. 122. 203. 113. 24. 204 bioeconomic. 146 worst. 212 Allee effect. 223 “business as usual”. 134 ambiguity. 24. 75 dynamics. 156. 139 co-viability. 18 criterion. 3 additive. 163 Green Golden. 8 capital. 200 co2 robust viability. 158 basin of attraction. 18. 212 feedback. 77 cake eating economy. 164 ce. 198. 77. 164 dynamics. 36. 58. 212 admissible community. 52 carrying capacity. 113. 82 robust viability. 167 autonomous carbon cycle. 32 value biodiversity. 61 cb. 229 . 132 biodiversity. 77 stochastic viability. 78. 212 function. 146. 164 causality. 196. 39. 35.
8 precautionary. 7. 196. 114 coexistence. 77 optimal. 193. 102 biology. 158. 113. 173 common property equilibrium. 148. 39. 156 Gordon’s bionomic. 167. 222 admissible. 181 feasible decision. 57 viability. 39 eigenvalue. 52. 7. 223 dynamic programming. 7 flexibility. 7. 155 ecosystemic approach. 75 dynamics. 35. 161 existence curse of dimensionality. 63 attractive. 156 spawners per recruits. 40. 156. 109. 108. 161 stable. 146 constraints. 24. 73. 201 making support. 17. 113 constraint. 7 depensation model. 107. 155. 68 robust viability. 202 control. 160. 3 optimality. 2 constraints. 56 maximin. 223 stochastic. 7. 156 maximum sustainable. 62 cost-benefit. 108. 225 invariance. 158. 5. 172 effect map. 109. 164. 39. 221 strategy. 43. 7. 36. 10 feedback optimal . 27 intertemporal. 141. 36. 212. 172 viability. 156 age-structured. 41. 16. 82 space. 39 externalities density. 38. 155. 25. 109. 38 direct use value. 61 criterion. 156 140. 85. 221 theory. 158. 76 autonomous. 19 extinction. 102 conservation. 56 Hurwicz. 68. 109. 61 multiplicative. 95 target. 84 111.262 Index Cobb-Douglas equation production function. 75. 77. 155. 78. 221 trajectory. 22. 107 control. 157. 57 additive. 60 expected. 107. 141. 223 disturbance. 109. 40. 36 optimality. 42 feedback. 52. equilibrium. 167 stationary. 140 constraint. 82. 160 instable. 54 multi-prior. 248 common property. 166 variance. 109. 57. 160 exhaustible resource. 102. 222 state. 120 difference equation. 107. 223 learning. 61 Green Golden. 224 globally asymptotically stable. 111 elasticity. 86. 19. 111 decision. 107. 28. 52 consumption. 158. 61 cpe. 40 discount factor. 160 private property. 135 cost-effectiveness. 122. 41. 2. 29 value. 7 extended function. 226 asymptotically stable. 172. 157 exclusion principle. 52 contingent valuation method. 156. 181 maximin. 223 Allee. 238 optimistic. 113. 61 Chichilnisky. 66. Rawls. 155 expected criterion. 117. 39. 81 decision.
90 invariance. 27 effect. 135 model.i. Index 263 robust. 159. 22 Lotka-Volterra horizon. 56 193 yield.. 83. 77 linear dynamical system. 173 function. 61 habitat. 5 principle. 39. 18 Hamiltonian. 68 ices. 95 mathematical expectation. 24. 95 utility. 144. 76. 79 guaranteed catch. 37 kernel. 173 mean payoff. 231 forcing. 78 maximal indicator function. 54 irreversibility. 2. 144. 56. 230 function. 164 weak. 179 Hotelling rule. 111 criterion. 109.d. 33. 221 viable worst payoff. 101. 146 observation. 56. 226. 44 interdisciplinary. 132 interest rate. 43. 107. 155 dynamics. 39 function. 74. 180 model. 80 isoelastic. 206 forestry. 201 domain. 3 Jury test. 202 information viable mean payoff. 111 migration. 156 state. 100 mean payoff. 221 maximin. 197 invasion. 100 mitigation. 222 criterion. 33. 22 Green Golden kernel Bellman robust. 84 mse. 200 instantaneous utility. 196 perfect. 135 precautionary approach. 160 management i. 134. 39 value time. 223. 95 marginal indicators. equilibrium. 202 imperfect. 37 strong. 184. 62 ghg. 135 sustainable intergenerational equity. 10. 118. 44 increasing function. 221 worst payoff. 18 harvesting effort. 7 food web. 132 logistic model. 146. 39. 139. 159 reference points. 196 value. 80. 139 Leslie matrix. 148 initial Bellman condition. 225 fixed point. 156 maximum. 201 of renewable resource. 239 Gordon model. 103 metapopulation. 28. 3. 156 value learning. 42. 68 Hurwicz criterion. 10. 139 viability. 27. 2. 79 Jacobian matrix. 95 max. 155 function. 110. 63 . 8. 120. 29. 109. 131. 183.
222 Bellman viability. 73 multi-prior approach. 74. 156 condition. 77 performance. 81 open access. 225 multiplicative criterion. 17. 8 viability analysis. 185 robust ppe. 159 trajectory. 116 renewable resource. 196 Rawls optimality criterion. 160 rent. 18 feedback. 222 repeller. 160 . 111 primitive random variables. 202 space. 95 criterion. 205 random variable. 222 Bellman invariance. 178 performance. 32 pollution. 74. 199 maximin. 159 path. 222 renewable. 40 stock-recruitment relationship. 41. 107. 158. 196. 18 feedback strategy. 225 criterion. 132 principle. 76 ices approach. 160 model. 200 quasi-extinction threshold. 42. 159 feedback. 68 instantaneous. 78 perfect information. 222 price versus quantity. 2. 24. 8. 222 principle function. 110 primitive. 38 payoff resource final. 55. 37 effect. 113 noisy. 185 management. 109 Ricker pessimistic. 66 private property equilibrium. 110 profit. 206 criterion. 42 noise. 22 output function. 8 population assessment. 29 stochastic management. 3. 159 observation. 86 over-exploitation. 17. 56. 56 precautionary multi-criteria. 232 multiplier. 110 rate viable of growth. 3. 22 payoff. 155. 109 exhaustible. 63 control. 42 robust pva. 102 map. 159 utility. 18 policy. 223 Bellman optimality. 78. 109. 4 present value. 224 management optimistic stochastic. 8 ppm. 202 rate of growth. 53 risk. 164 criterion. 110 PV (present value). 2 reserve. 110 protected area.264 Index msy. 157 effect. 161 catches. 43 based model. 37. 56 optimal probability.
23 technology. 223 additive. 61 utility state. 173 stationary stochastic viability. 155 deterministic. 43. 39 invasive. 232 criterion. 61 attractive. 174 sustainable feedback. 222 stable unconstrained case. 55. 39. 3 steady state. 137 of information. 109 asymptotically stable. 21 stationary. 2 viability value function. 3 dynamic programming. 39 endangered . 198. 160 option. 250 map. 200 variable. 179 spectrum. 62 spillover. 39 maximin. 132 threatened. 203. 158. 44 viable supremum. 61 existence. 61 value globally asymptotically stable. 80. 84 viability kernel. 184 optimal viability kernel. 197. 36. 184 dynamics. 61 Green Golden. 172 final. 40 feedback. 155. 83 security barrier. 156 target. 86 trophic web. 133 instantaneous. 8. 109 adjoint. 201 viability. 83. 167 species tolerable window. 212 domain. 197 strictly increasing function. 110. 27. 7. 132 autonomous. 86 separable. 37 uncertain variable. 139 trajectory. 86 transpose. 41 social planner. 38 robust viability. 111 . 4 yield. 68 approach. 202 use. 212 substitutability. 3 transition equation. 74 competition. 155 stability. 73 system. 158 equilibrium. 113. 173 value function. 73 feedback. 39. 3 optimal variance criterion. 83 scenario. 78 viability. 146. 52 indirect use. 204 stable. 3 instable. 195 strategy. 161 control. 86 optimality. 75 coexistence. 38 scalar product. 44 control. 68 trajectories space. 41. 52. 203 barrier. 8. 173 development. 7 uncertainty. 173 sup. 183 control. 222 Schaefer model. 61 function. 82. 226 stochastic of substituting information. 137 safe minimum standards. 90. Index 265 kernel. 8.
82 margins. 174 worst controls. 110 Whittle form. 86 set. 195 regulation inertial. 82. 85 case. 99 sustainable. 183 regulation set. 84 viable control.266 Index stochastic. 55 . 160 feedback. 99 yield maximal. 82 performance. 248 robust.
|
https://www.scribd.com/document/375202676/Sustainable-Management-Of-Natural-Resources-Mathematical-Models-And-Methods-pdf
|
CC-MAIN-2018-51
|
refinedweb
| 86,463
| 61.02
|
source tools to describe the behaviour of devices and their interactions:
from gpiozero import LED, MotionSensor, LightSensor from gpiozero.tools import booleanized, all_values from signal import pause garden = LED Raspbian desktop image, available from raspberrypi.org. To install on Raspbian. Pi Zero USB OTG
- 7. Source/Values
- 8. Command-line Tools
- 9. Frequently Asked Questions
- 10. Migrating from RPi.GPIO
- 11. Contributing
- 12. Development
- 13. API - Input Devices
- 14. API - Output Devices
- 15. API - SPI Devices
- 16. API - Boards and Accessories
- 17. API - Internal Devices
- 18. API - Generic Classes
- 19. API - Device Source Tools
- 20. API - Tones
- 21. API - Pi Information
- 22. API - Pins
- 23. API - Exceptions
- 24. Changelog
- 25. License
|
https://gpiozero.readthedocs.io/en/v1.5.1/
|
CC-MAIN-2021-49
|
refinedweb
| 111
| 57.03
|
// $Id: btree.dox 128 2011-05-18 07:23:35Z tb $ -*- fill-column: 79 -*- /** \file btree.dox * Contains the doxygen comments. This header is not needed to compile the B+ * tree. */ /* * STX B+ Tree Template Classes v0.8.6 * Copyright (C) 2008-2011 Timo Bingmann * * STX B+ Tree Template Classes README \author Timo Bingmann (Mail: tb a-with-circle idlebox dot net) \date 2008-09-07 and 2011-05-17 \section sec1 Summary The STX B+ Tree package is a set of C++ template classes implementing a B+ tree key/data container in main memory. The classes are designed as drop-in replacements of the STL containers <tt>set</tt>, <tt>map</tt>, <tt>multiset</tt> and <tt>multimap</tt>. \section sec2 Website / API Docs / Bugs / License. \section sec3 Original Application \ref speedtest "speed test experiments". A third inspiration was that no working C++ template implementation of a B+ tree could be found on the Internet. Now this one can be found. \section sec4 Implementation Overview This implementation contains five main classes within the \ref stx namespace (blandly named Some Template eXtensions). The base class \ref stx::btree \ref speedtest "speed test results" for details. The base class is then specialized into \ref stx::btree_set "btree_set", \ref stx::btree_multiset "btree_multiset", \ref stx::btree_map "btree_map" and \ref stx::btree_multim (\ref stx::btree_set "btree_set" and \ref stx::btree_multiset "btree_multiset") are derived from the base implementation \ref stx::btree . \section sec5 Problem with Separated Key/Data Arrays. \section sec6 Test Suite The B+ tree distribution contains an extensive test suite using cppunit. According to gcov 91.9% of the btree.h implementation is covered. \section sec7 STL Incompatibilities \subsection sec7-1 Key and Data Type Requirements The tree algorithms currently do not use copy-construction. All key/data items are allocated in the nodes using the default-constructor and are subsequently only assigned new data (using <tt>operator=</tt>). \subsection sec7-2 Iterators' Operators The most important incompatibility are the non-writable <tt>operator*</tt> and <tt>operator-></tt> of the \ref stx::btree::iterator "iterator". See above for a discussion of the problem on separated key/data arrays. Instead of <tt>*iter</tt> and <tt>iter-></tt> use the new function <tt>iter.data()</tt> which returns a writable reference to the data value in the tree. \subsection sec7-3 Erase Functions The B+ tree supports three erase functions: \code size_type erase(const key_type &key); // erase all data pairs matching key bool erase_one(const key_type &key); // erase one data pair matching key void erase(iterator iter); // erase pair referenced by iter \endcode The following STL-required function is currently not supported: \code void erase(iterator first, iterator last); \endcode \section sec8 Extensions Beyond the usual STL interface the B+ tree classes support some extra goodies. \code //); \endcode \section sec9 B+ Tree Traits All tree template classes take a template parameter structure which holds important options of the implementation. The following structure shows which static variables specify the options and the corresponding defaults: \code*)) ); }; \endcode \section sec10 Speed Tests See the extra page \ref speedtest "Speed Test Results". */ /** \page speedtest Speed Test Results \section sec11 Speed Test Experiments The B+ tree source package contains a speedtest program which compares the libstdc++ STL red-black tree with the implemented B+ tree with many different parameters. The newer STL hash table container from the __gnu_cxx namespace \a n random integers into the tree / hash table. The second test first inserts \a n random integers, then performs \a n lookups for those integers and finally erases all \a n integers. The last test only performs \a n lookups on a tree pre-filled with \a n integers. All lookups are successful. These three test sequences are preformed for \a n from 125 to 4,096,000 or 32,768,000 where \a n is doubled after each test run. For each \a n the test procedure is repeated until at least one second execution time elapses during the repeated cycle. This way the measured speed for small \a test, only every other slot size is actually tested. Two test results are included in the package: one done in \ref sec12 "2007 with version 0.7" and another done in \ref sec13 "2011 with version 0.8.6". \section sec12 Results 2007 The speed test source code was compiled with g++ 4.1.2 -O3 -fomit-frame-pointer \attention \image html speedtest-2007-01.png \image html speedtest-2007-02.png The first two plots above show the absolute time measured for inserting \a n items into seven different tree variants. For small \a n (the first plot) the speed of red-black tree and B+ tree are very similar. For large \a n the red-black tree slows down, and for \a n > 1,024,000 items the red-black tree requires almost twice as much time as a B+ tree with 32 slots. The STL hash table performs better than the STL map but not as good as the B+ tree implementations with higher slot counts. The next plot shows the insertion time per item, which is calculated by dividing the absolute time by the number of inserted items. Notice that insertion time is now in microseconds. The plot shows that the red-black tree reaches some limitation at about \a n = 16,000 items. Beyond this item count the B+ tree (with 32 slots) performs much better than the STL multiset. The STL hash table resizes itself in defined intervals, which leads to non-linearly increasing insert times. \image html speedtest-2007-03.png \image html speedtest-2007-04.png The last plots goal is to find the best node size for the B+ tree. It displays the total measured time of the insertion test depending on the number of slots in inner and leaf nodes. Only runs with more than 1 million inserted items are plotted. One can see that the minimum is around 65 slots for each of the curves. However to reduce unused memory in the nodes the most practical slot size is around 35. This amounts to total node sizes of about 280 bytes. Thus in the implementation a target size of 256 bytes was chosen. The following two plots show the same aspects as above, except that not only insertion time was measured. Instead in the first plot a whole insert/find/delete cycle was performed and measured. The second plot is restricted to the lookup / find part. \image html speedtest-2007-07.png \image html speedtest-2007-11.png The results for the trees are in general accordance to those of only insertion. However the hash table implementation performs much faster in both tests. This is expected, because hash table lookup (and deletion) requires fewer memory accesses than tree traversal. Thus a hash table implementation will always be faster than trees. But of course hash tables do not store items in sorted order. Interestingly the hash table's performance is not linear in the number of items: it's peak performance is not with small number of items, but with around 10,000 items. And for item counts larger than 100,000 the hash table slows down: lookup time more than doubles. However, after doubling, the lookup time does not change much: lookup on tables with 1 million items takes approximately the same time as with 4 million items. \section sec13 Results 2011 In 2011, after some smaller patches and fixes to the main code, I decided to rerun the old speed test on my new hardware and with up-to-date compilers. The speedtest source code was compiled on a x86_64 architecture using gcc 4.4.5 with flags -O3 -fomit-frame-pointer. It was run in an Intel Core i7 950 clocked at 3,07 GHz. According to cpuinfo, this processor contains 8 MB L2 cache. The full results of the newly run tests are found in the package at speedtest/results-2011/speedtest.pdf \image html speedtest-2011-03.png This plot is maybe the most interesting, especially compared with the old run from 2007. Again the B+ tree multiset implementation is faster than the red-black tree for large number of items in the tree. However, due to the faster hardware and larger cache sizes, the average insertion speed plots diverge notable at around 100,000 items instead of at 16,000 items for the older Pentium 4 CPU. Nevertheless, the graphs diverge for larger \a n in approximately the same fashion as in the older plots. This lets one assume that the basic cache hierarchy architecture has not changed and the B+ tree implementation still works much better for larger item counts than the red-black tree. */
|
http://panthema.net/2007/stx-btree/stx-btree-0.8.6/include/stx/btree.dox.html
|
CC-MAIN-2013-20
|
refinedweb
| 1,454
| 63.7
|
The partitions for any integer N? There’s a way to create a generating function, but it’s quite complicated (check Wikipedia’s entry if you are interested).
An easier solution is to use an algorithm to find all the different partitions. More specifically we want to use the divide and conquer method. So first of all we need to break the problem into smaller sub-problems.
Suppose we want to find all the partitions of the number 5. We could split all the solutions into two groups: a group which uses the number 5 itself at least once, and a group that doesn’t use it. The group that uses the number 5 has only one solution: five itself. The group that doesn’t use the number five is basically the problem of finding all the ways to come up with 5 using the sub-set 1,2,3 and 4.
Now repeat the process. We can again split the solutions to our second problem into two groups: a group with all the solutions that contain the number 4, and a group that doesn’t.
There you go, we can apply this split recursively and we’ll break the problem down into many sub-problems.
Below is the algorithm. The variable sum is the sum we are trying to reach, and largestNumber is the largest number on the sub-set we have available to reach that sum.
When sum equals zero it means we just reached the sum exactly, so the function returns 1 (i.e. it just found one way to do the sum). If sum goes below zero it means the last available number was larger than what we needed, so the function returns 0. Similarly if the largest number available is zero it means we can’t reach the sum, so the function returns 0.
#include <stdio.h> int partition(int sum, int largestNumber){ if (largestNumber==0) return 0; if (sum==0) return 1; if (sum<0) return 0; return partition(sum,largestNumber-1) + partition(sum-largestNumber,largestNumber); } int main(){ int sum = 100; int largestNumber = 99; printf("%dn",partition(sum,largestNumber)); return 0; }
Notice that this algorithm re-computes solution to the same sub-problems many times (i.e., we have overlapping sub-problems). As usual, therefore, we can use dynamic programming to make it more efficient.
The above program partitioned 100 in 15 seconds. The code below reduced this time to 0.002 seconds (i.e., 2 milliseconds).
#include <stdio.h> int table[100][100]={0}; int partition(int sum, int largestNumber){ if (largestNumber==0) return 0; if (sum==0) return 1; if (sum<0) return 0; if (table[sum][largestNumber]!=0) return table[sum][largestNumber]; table[sum][largestNumber]=partition(sum,largestNumber-1) + partition(sum-largestNumber,largestNumber); return table[sum][largestNumber]; } int main(){ int sum = 100; int largestNumber = 99; printf("%dn",partition(sum,largestNumber)); return 0; }
We can also use the bottom-up dynamic programming approach. That is, we create a table where each column represents the larger number we have available, and each row represents a possible sum we want to reach. Then we initialize it with the base cases (i.e., mark a 0 on the column that represents the largest number being 0, and a 1 on the first row, which represents the sum being equal to 0).
After that we simply need to traverse the table, where each position table[i][j] will be equal to the sum of table[i][j-1] (the part where we don’t take the largest number) and table[i-j][j] (the part where we take the largest number, so the sum will be reduced by the size of the number we just took). Just be careful to check if i-j<0, cause in this case you don't add the second part (else it would give a segmentation fault). Here's the code:
When I partitioned 900 the top-down approach took 17 milliseconds to compute, while the bottom-up one took 11 milliseconds. Both were very fast, but once you start working with huge numbers the bottom-up one is probably your best choice.When I partitioned 900 the top-down approach took 17 milliseconds to compute, while the bottom-up one took 11 milliseconds. Both were very fast, but once you start working with huge numbers the bottom-up one is probably your best choice.
#include <stdio.h> int table[150][150]; int partition(int sum, int largestNumber){ int i,j; for (i=1;i<=sum;i++){ for (j=1;j<=largestNumber;j++){ if (i-j<0){ table[i][j]=table[i][j-1]; continue; } table[i][j]=table[i][j-1]+table[i-j][j]; } } return table[sum][largestNumber]; } int main(){ int sum = 100; int largestNumber = 99; int i; /*initialize table with base cases*/ for (i=0;i<=sum;i++) table[i][0]=0; for (i=1;i<=largestNumber;i++) table[0][i]=1; printf("%dn",partition(sum,largestNumber)); return 0; }
This just looks great Daniel, and right on time for me as I’m starting to make some tricks here and there programming too.
Will keep tune =)
Good luck!
Hi Daniel. Good stuff, thank you. You should add 3+1+1 to the list at the beginning.
Keep going on ProjectEuler! Hint your algorithm above will come in very handy.
Hai Daniel . can you provide me the source code to print the fixed size partitions of given number
for example if n=5 and length is 4
then
1+1+1+2
1+2+2+0
1+1+3+0
2+3+0+0
1+4+0+0
5+0+0+0
I have already tried this in Ruby, but it is HYPER expensive. It’s the second try on a process, and for n=30, the first process took about 0.82 seconds to complete, and this one had gone for minutes before I just cancelled it. How may I submit my idea?
Thanks for the program. One small correction: you should add 1 to the final answer as the largest number can be equal to the number itself.
I’d rather think of this problem as the coin change problem with denominations = [1,2…n-1] and target coin size to reach as n.
Also, a dumb q: why does passing 3,2 to the naive version of your code gives the answer 2?
shouldn’t it be:
3
2+1
1+1+1
so 3?
Passing 3,2 you are restricting the largest number to be 2. Means you are going to partition 3 as a combinations of 1 and 2. That is
1+1+1
1+2
So the answer is 2 combinations.
There are actually 7 partitions for n=5.
the list at the beginning omits the partition 3+1+1);
Your comment is awaiting moderation.);
5 has seven partitions. You have missed 3+1+1
The first method call should start like partition(sum, sum) to capture the first, 5 here, in the count.
So how would you modify the last algorithm to also save the partitions ?
I have been trying to figure that out with no success.
what’s the algorithm for counting distinct partitions of any particular number
|
https://www.programminglogic.com/integer-partition-algorithm/
|
CC-MAIN-2019-13
|
refinedweb
| 1,208
| 71.04
|
Hi Team,
I have created a sidebar with radio buttons and each radio button will load their individual pages but the variable information will be passed from one page to another page.
The sequence is like this:
Data Load -> transform -> EDA
So a person has to click load the dataset and pass the loaded dataset into next page i.e., EDA or Transform.
I have created a sample code for it:
import src.pages.data_injection as data_load import src.pages.EDA as EDA import streamlit as st import pandas as pd import numpy as np def main(): st.sidebar.title("Navigate") selection = st.sidebar.radio("Choose a module", PAGES) if selection == "Data Injection": df = data_load.load_page() # this loads page of Data Injection data = df # create copy of df .... I am getting error here "local variable 'df' referenced before assignment" if selection == "EDA": EDA.load_page(data) # this should load EDA page by passing "data" as a variable if __name__ == '__main__': main()
Please let me know how to solve this issue?
|
https://discuss.streamlit.io/t/passing-variable-from-one-page-to-other/3127
|
CC-MAIN-2020-34
|
refinedweb
| 169
| 57.16
|
Problem: You want to use a mock object framework in your ScalaTest tests, such as Mockito.
Solution
ScalaTest offers support for the following mock testing frameworks:
Because the support for each framework is similar, let’s take a look at using Mockito.
Before starting, imagine that you have a login web service for your application, and rather than call the real web service during your tests, you just want to mock one up.
In your application you have “login service” code in a file named src/main/scala/tests/LoginService.scala, which looks like this:
package tests // a very simple User class case class User(name: String) // a LoginService must have a 'login' method trait LoginService { def login(name: String, password: String): Option[User] } // the code for our real/live LoginService class RealLoginService extends LoginService { // implementation here ... }
Notice that there’s a
LoginService trait, and the
RealLoginService implements that trait. By following this pattern, you can use Mockito to “mock” your
LoginService trait in your unit tests.
The following code shows how to create and use a mock
LoginService using Mockito and ScalaTest:
package tests import org.scalatest.FunSuite import org.scalatest.BeforeAndAfter import org.scalatest.mockito.MockitoSugar import org.mockito.Mockito._ class LoginServiceTests extends FunSuite with BeforeAndAfter with MockitoSugar { test ("test login service") { // (1) init val service = mock[LoginService] // (2) setup: when someone logs in as "johndoe", the service should work; // when they try to log in as "joehacker", it should fail. when(service.login("johndoe", "secret")).thenReturn(Some(User("johndoe"))) when(service.login("joehacker", "secret")).thenReturn(None) // (3) access the service val johndoe = service.login("johndoe", "secret") val joehacker = service.login("joehacker", "secret") // (4) verify the results assert(johndoe.get == User("johndoe")) assert(joehacker == None) } }
Here’s a quick description of the code:
- In the “init” step, you create a mock version of the
LoginService. Notice that this mocks a a trait that doesn’t have an implementation. Because you can do this, you don’t have to write a separate
MockLoginServiceclass, which is nice. (You also don’t have to access Test or Production versions of the “real” login service, which would slow down your unit tests.)
- In the “setup” portion of the code, you work with Mockito to define how the mock
LoginServiceshould respond when it’s given two sets of data. When “johndoe” logs in, the mock login service should return a
Some(User(“johndoe”))instance, and when “joehacker” attempts to log in, it should return a
None.
- In the “access” portion of the code, you write the code just like you would normally in your application. You call the
LoginServiceinstance with some data, and get objects in return.
- In the “verify” portion of the code, you verify that you received the data you expected from your login service.
In more real-world tests, you’d do things slightly differently. First, you’d use a more robust
User class. Second, you’d take the objects that are received from the
LoginService and attempt to do more things with them. There isn’t much value in testing a mock
LoginService by itself, but because this mock service lets you test the next steps in your application, a mock service becomes a very useful thing.
This example is just intended to get you started in the right direction. The important part of the test is that you got a
User object back from the
LoginService, just as though you had called a real, live, production login service.
Note: The
MockitoSugarimport statement apparently changed since I originally wrote this article. I updated the source code here, and I hope it now includes the correct import. See the comment in the Comments section below for the old and new import statement.
Steps to using Mockito
To use Mockito like this in a ScalaTest project, the first step is to include the Mockito JAR file in your project. Assuming you’re using SBT, either add the Mockito JAR file to your project’s lib directory, or add Mockito as a dependency in your build.sbt file. With ScalaTest 1.9.1, this is the correct line to add to your build.sbt file:
libraryDependencies += "org.mockito" % "mockito-all" % "1.8.4"
The next step is to add the necessary imports to your unit test classes. These were shown in the example, and are repeated here:
import org.scalatest.mockito.MockitoSugar import org.mockito.Mockito._
Next, mix the
MockitoSugar trait into your test class:
class PizzaTests extends FunSuite with BeforeAndAfter with MockitoSugar {
Once you have these configuration steps out of the way, you can begin creating mock objects in your ScalaTest tests with Mockito.
See Also
There are many more ways to use Mockito and other mock object frameworks in your ScalaTest tests. These links will help you get started:
- This link on the ScalaTest website shows many ScalaMock, EasyMock, JMock, and Mockito examples:
- The Mockito website has many more examples:.
|
http://alvinalexander.com/scala/how-to-use-mock-objects-with-scalatest/
|
CC-MAIN-2021-04
|
refinedweb
| 822
| 54.52
|
Representing a Tree
In this section, we consider some different ways to represent a tree-like shape with data types in Python. It is important to become familiar with multiple representations since trees occur in many contexts and the right choice of representation in one may not quite fit another.
In Python, many of the libraries that deal with trees (such as the html5lib for parsing html, or ast for working with the abstract syntax grammar of Python) use the object oriented “nodes and references” representation we discuss first. However, when building functionality around our own trees it is generally simpler to use a representation constructed from dicts and lists, which we discuss later. This simpler representation is also more portable to other languages and contexts, even those without a notion of objects (such as pen and paper!).
Nodes and references representation
Our first method to represent a tree uses instances of a
Node class along
with references between node instances.
Let us consider a small example:
Using nodes and references, we might think of this tree as being structured like:
We will start out with a simple class definition for the nodes and
references approach as shown below. In this case we will consider binary
trees, so will directly reference
left and
right nodes. For trees where
nodes may have more than two children, a
children list could be used to
contain these references instead.
The important thing to remember about this representation is that the attributes
left and
right will become references to other instances of the
Node
class. For example, when we insert a new left child into the tree we create
another instance of
Node and modify
self.left in the root to reference the
new subtree.
class Node(object): def __init__(self, val): self.val = val self.left = None self.right = None
Notice that the constructor function expects to get some kind of value to store
in the node. Just like you can store any object you like in a list, the
val
attribute for a node can be a reference to any object. For our early examples,
we will store the name of the node as the value. Using nodes and references to
represent the tree illustrated above, we would create six instances of the Node
class.
Next let’s look at a function that can help us build the tree beyond the root
node. To add a left child to the tree, we will instantiate a new
Node instance
and pass it as
child to the
insert_left function defined here:
def insert_left(self, child): if self.left is None: self.left = child else: child.left = self.left self.left = child
We must consider two cases for insertion. The first case is characterized by a node with no existing left child. When there is no left child, simply add a node to the tree. The second case is characterized by a node with an existing left child. In the second case, we insert a node and push the existing child down one level in the tree.
The code for
insert_right must consider a symmetric set of cases. There will
either be no right child, or we must insert the node between the root and an
existing right child:
def insert_right(self, child): if self.right is None: self.right = child else: child.right = self.right self.right = child
Now that we have all the pieces to create and manipulate a binary tree, let’s
use them to check on the structure a bit more. Let’s make a simple tree with
node a as the root, and add nodes b and c as children. Below we create the tree
and look at the some of the values stored in
key,
left, and
right. Notice
that both the left and right children of the root are themselves distinct
instances of the
Node class. As we said in our original recursive definition
for a tree, this allows us to treat any child of a binary tree as a binary tree
itself.
root = Node('a') root.val # => 'a' root.left # => None root.insert_left(Node('b')) root.left # => <__main__.Node object> root.left.val # => 'b' root.insert_right(Node('c')) root.right # => <__main__.Node object> root.right.val # => 'c' root.right.val = 'hello' root.right.val # => 'hello'
List of lists representation
A common way to represent trees succinctly using pure data is as a list of lists. Consider that in a list of lists, each element has one and only one parent (up to the outermost list) so meets our expectation of a tree as a hierarchical structure with no cycles.
In a list of lists tree, we will store the value of the each node as the first element of the list. The second element of the list will itself be a list that represents the left subtree. The third element of the list will be another list that represents the right subtree. To illustrate this technique, let’s consider a list of lists representation of our example tree:
tree = [ 'a', #root [ 'b', # left subtree ['d' [], []], ['e' [], []] ], [ 'c', # right subtree ['f' [], []], [] ] ]
Notice that we can access subtrees of the list using standard list indexing. The
root of the tree is
tree[0], the left subtree of the root is
tree[1], and
the right subtree is
tree[2]. Below we illustrate creating a simple tree using
a list. Once the tree is constructed, we can access the root and the left and
right subtrees.
tree = ['a', ['b', ['d', [], []], ['e', [], []]], ['c', ['f', [], []], []]] # the left subtree tree[1] # => ['b', ['d', [], []], ['e', [], []]] # the right subtree tree[2] # => ['c', ['f', [], []], []] # the root tree[0] # => 'a'
One very nice property of this list of lists approach is that the structure of a list representing a subtree adheres to the structure defined for a tree; the structure itself is recursive! A subtree that has a root value and two empty lists is a leaf node. Another nice feature of the list of lists approach is that it generalizes to a tree that has many subtrees. In the case where the tree is more than a binary tree, another subtree is just another list.
Since this representation is simply a composite of lists, we will use functions to manipulate the structure as a tree, analogous to the methods in our object oriented “nodes and references” representation above.
To add a left subtree to the root of a tree, we need to insert a new list into the second position of the root list. We must be careful. If the list already has something in the second position, we need to keep track of it and push it down the tree as the left child of the list we are adding. Here is a possible function for inserting a left child:
def insert_left(root, child_val): subtree = root.pop(1) if len(subtree) > 1: root.insert(1, [child_val, subtree, []]) else: root.insert(1, [child_val, [], []]) return root
Notice that to insert a left child, we first obtain the (possibly empty)
list that corresponds to the current left child. We then add the new
left child, installing the old left child as the left child of the new
one. This allows us to splice a new node into the tree at any position.
The code for
insert_right is similar to
insert_left and is shown below:
def insert_right(root, child_val): subtree = root.pop(2) if len(subtree) > 1: root.insert(2, [child_val, [], subtree]) else: root.insert(2, [child_val, [], []]) return root
To round out this set of tree-making functions, let’s write a couple of access functions for getting and setting the root value, as well as getting the left or right subtrees. This way we can abstract away the fact that we use the positions in a list to represent values, left subtrees and right subtrees:
def get_root_val(root): return root[0] def set_root_val(root, new_val): root[0] = new_val def get_left_child(root): return root[1] def get_root_child(root): return root[2]
We can now use our function definitions to build a tree and retrieve children of given nodes:
root = [3, [], []] insert_left(root, 4) insert_left(root, 5) insert_right(root, 6) insert_right(root, 7) left = get_left_child(root) left # => [5, [4, [], []], []] set_root_val(left, 9) root # => [3, [9, [4, [], []], []], [7, [], [6, [], []]]] insert_left(left, 11) root # => [3, [9, [11, [4, [], []], []], []], [7, [], [6, [], []]]] get_root_child(get_root_child(root)) # => [6, [], []]
Map-based representation
Our list of list representation has a handful of benefits:
- It is succinct;
- We can easily construct the tree as Python list literals;
- We can easily serialize and print the tree; and,
- It is portable to languages and contexts without objects.
However, it has the significant disadvantage that it is somewhat difficult to see the tree-like nature of the composite lists simply by looking at one, particularly if it is printed on a single line.
For this reason, our preference in this book (and often in real-life
programming, for that matter) is to use a very similar representation using
nested mappings (i.e. of
dicts in Python) such that we can name children,
values and potentially other data related to a tree node.
Using maps, our example tree may look like:
{ 'val': 'A', 'left': { 'val': 'B', 'left': {'val': 'D'}, 'right': {'val': 'E'} }, 'right': { 'val': 'C', 'right': {'val': 'F'} } }
In this case, each of our nodes becomes a map with at least the
val key, and
in some cases a
left and/or
right key(s).
If we were dealing with a tree that is not a binary tree, we could use a
children key instead:
{ 'val': 'A', 'children': [ { 'val': 'B', 'children': [ {'val': 'D'}, {'val': 'E'}, ] }, { 'val': 'C', 'children': [ {'val': 'F'}, {'val': 'G'}, {'val': 'H'} ] } ] }
This is almost as compact as our list of lists representation, and significantly more readable, so we will continue to use this map-based representation throughout the book.
|
https://bradfieldcs.com/algos/trees/representing-a-tree/
|
CC-MAIN-2018-26
|
refinedweb
| 1,639
| 68.3
|
A simple package that uses url_launcher to launch the maps app with the proper scheme on both iOS and Android.
On iOS, map links as specified by Apple are launched. On Android, the geo intent is used as documented here.
import 'package:maps_launcher/maps_launcher.dart'; ... MapsLauncher.launchQuery('1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA'); MapsLauncher.launchCoordinates(37.4220041, -122.0862462);: maps_launcher: ^1.0.0
You can install packages from the command line:
with Flutter:
$ flutter pub get
Alternatively, your editor might support
flutter pub get.
Check the docs for your editor to learn more.
Now in your Dart code, you can use:
import 'package:maps_launcher/maps_launcher.dart';
We analyzed this package on Aug 16, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using:
Detected platforms: Flutter
References Flutter, and has no conflicting libraries.
|
https://pub.dev/packages/maps_launcher
|
CC-MAIN-2019-35
|
refinedweb
| 141
| 58.58
|
For some reason the following code gives me a debug error. As far as I can see I typed it over with no mistakes from the book.
Please do not give me any other options of coding this piece. I would just like to know what the error refers to.
Error:Error:Code:#include <iostream> int main() { // ask for two numbers // assign the numbers to BigNumber and SmallNumber // If BigNumber is bigger then SmallNumber // see if they are evenly devisible // if they are, see if they are the same number using namespace std; int FirstNumber, SecondNumber; cout << "Enter two numbers.\n First: "; cin >> FirstNumber; cout << "\nSecond: "; cin >> SecondNumber; cout << "\n\n"; if (FirstNumber >= SecondNumber) { if (FirstNumber % SecondNumber) == 0) { if (FirstNumber == SecondNumer) cout << "They are the same!"; else cout << "They are evenly divisable."; } else cout << "They are not evenly devisable."; } cout << " Hey! The second one is larger."; return 0; }
error: expected primary-expression before '==' token
error: expected ';' before ')' token
|
https://cboard.cprogramming.com/cplusplus-programming/126975-debug-error.html
|
CC-MAIN-2017-22
|
refinedweb
| 158
| 56.05
|
Reporting Services: Using XML and Web Service Data Sources
SQL.
Contents
About This Document
Introduction
XML Data Provider
Examples
Limitations and Common Pitfalls
Conclusion
About This Document.
Other Sources of Information
This white paper is not intended to be an exhaustive source of information about Reporting Services. For detailed information, see the Reporting Services Web site.
Product Versions
This white paper is written for SQL Server 2005 Reporting Services; many features addressed are not relevant to earlier versions of Reporting Services.
Introduction.
XML Data Sources.
XML Data Provider Query Language:
Specific values can be specified at each node by enclosing them in braces. This will define the columns returned from the query. Notice that XML attributes can be accessed by specifying the "@" symbol plus the name. For example:
Similarly, to reference the value of the node directly, specify the "@" symbol without a name.
Namespaces
If the query requires use of specific XML namespaces, they can be specified within the element path. The following example shows how a specific XML namespace can be specified::
The following types are supported:
- String
- Integer
- Boolean
- Float, Decimal
- Date
- XML:
Fields that contain complete encoded XML documents are also supported. When decoded, they will be treated as a set of nested elements.
Auto-Detection of XML.
Examples.
Querying a Web Service
- In Report Designer, create a new Report Server Project.
- In the new project, create a new blank report.
- In the Data tab, on the Dataset menu, select New Dataset.
This will bring up the Data Source window, to create a new data source.
- Name your data source, and select XML in the Type drop-down list.
- Enter the following string in the Connection String box:
http://<Server Name>/ReportServer/ReportService2005.asmx
- In the Credentials tab, select Use Windows Authentication (Integrated Security).
- Determine the Web service namespace and method name..
- Determine Web service method parameters..
- Construct the query.
Enter the following query into the Query Designer and execute the query by selecting the exclamation (!) button on the toolbar.
- Construct the Element Path.
Notice that the auto-derived element path may not contain the data we want. We must construct the element path accordingly. To do this, we need an understanding of the XML schema. You can do this in one of the following ways:
- Look in the Web service documentation.
- Review the WSDL file directly for the structure.
- Run the following query against the WSDL file. This will use the XML data provider to parse the WSDL file, return information directly through the data set, and expose it in the designer..Note We used IgnoreNamespaces=true; if you require an explicit namespace, you must specify it directly in the query. For more information, see the XML Data Provider Query Language section, earlier in this white paper.
- Construct your report.
Now that you have your data source created, build your report as usual. By executing the query in the Data tab, the designer will auto-generate the fields for use in the report layout.
Specifying XML Data Using Report Parameters.
Add a report parameter with the name of the parameter(s) in the Web service call.
To add a report parameter
- Make sure the Layout tab is selected in Report Designer.
- On the Report menu, click Report Parameters.
- Click Add.
- Enter a name for the parameter.
- Select the Data Type, Prompt, and Report properties.
- For this example, leave Non-queried selected.
- Select Non-queried for Default Values.
- In the Non-Queried field, enter /Data Sources for the value.Note /Data Sources can be replaced with a valid, existing folder name in Report Manager, if the Data Sources folder does not exist for you.
- Click OK.
Add a parameter to your dataset that will pull in the value from the report parameter.
To add a dataset parameter
- On the Data tab of your report, select the dataset to which you want to add the parameter.
- Click the ellipsis (...) icon next to the drop-down list.
- Click the Parameters tab.
- In the Name column, enter the name of the parameter that the Web service accepts. In this case, it will be Item.
- In the Value column, enter "=Parameters!ReportParm1.Value" (replace ReportParm1 with the name you specified in step 4 of the previous procedure).
- Click OK.
- Execute the dataset by clicking the exclamation (!) button, or preview your report passing in the value for your report parameter.
Querying XML Data from SQL Server
- In the same project you created in the previous example, create a new blank report.
- In the Data tab, from the Dataset menu, select New Dataset.
- In the Data Source dialog box, create a new SQL data source and set the connection to the local instance of SQL Server. Under Query String, enter the following query string, substituting your local server name for <Server Name>:
- Click OK.
- Enter the following query in the Data tab.
- To add a subreport, on the Layout tab, drag the subreport item from the toolbox to the Layout pane. Right-click the subreport and select Properties.
- In the Subreport dialog box, on the Subreport menu, select the report you created in the previous example.
- To add parameter to subreport, select the Parameters tab, and then set the subreport XMLData parameter equal to =First(Fields!Product.Value). Notice that we must wrap the field reference in an aggregation expression, because it does not occur within the repeating pattern of a data region..
Limitations and Common Pitfalls
Provided the previous information and examples, new report authors might still have difficulties when querying XML data sources. Some of the most common misunderstandings include the following:
- Query syntax—The XML data-provider query syntax is incompatible with XPATH. For more information, see the XML Data Provider Query Language section, earlier in this white paper.
- Multiple parent-child or master-detail relationships at the same level—XML supports this construct. However, when flattening to a two-dimensional data set, the provider cannot support this in one query. For example, if a customer has multiple returns and multiple orders, the provider can return only one set: orders or returns. However, this can be combined in one report by using two data sets. Multiple datasets let you display the data within the same report, but in separate data regions.
- XML schema of Web service response—The structure of Web service responses is typically not well-documented; it can be unclear how to construct the query against a Web service. For examples about how to determine the structure, see the Querying a Web Service example, earlier in this white paper.
- Web service encoding—Frequently, Web services will use HTML or Base64 encoding in their responses. The XML Data Provider supports both decoding mechanisms through the query syntax. For more information, see the XML Data Provider Query Language section, earlier in this white paper.
- SOAP Action auto-derivation—The XML Data Provider will auto-generate SOAP Action by appending Method Name and Namespace. For non-.NET Framework Web services, the SOAP Action may differ and will have to be set explicitly in the query.
- XML namespaces—Frequently, consumers of Web services will have to address namespaces in the source XML. Setting IgnoreNamespaces=true eases the problem. However, if there are specific requirements that require the use of namespaces, see the XML Data Provider Query Language section, earlier in this white paper.
- Type casting—Unless specified in the query, data types will be returned as strings. The data provider will not automatically detect the type information. This problem usually occurs when authors try to use data in aggregation expressions. However, if the types of the fields can be explicitly specified, see the XML Data Provider Query Language section, earlier in this white paper.
Conclusion
|
https://msdn.microsoft.com/en-us/library/aa964129(SQL.90).aspx
|
CC-MAIN-2018-51
|
refinedweb
| 1,283
| 57.77
|
By Beyang Liu on May 15, 2017
Pick your favorite Java repository and a revision and file at random (or try this one). Visit that file in Sourcegraph and within seconds, you can jump to definition (Ctrl/⌘-click), find all references (right click), search for symbols (Ctrl/⌘-p), and view usage examples drawn from other projects.
How does the magic work? A big part of it is a new open standard called the Language Server Protocol (LSP). We think LSP will benefit almost every code editor and plugin, and we’d like to explain why with examples of how Sourcegraph has used it to scale to millions of repositories across many different languages.
Instant Code Intelligence on Sourcegraph
Jump-to-definition, find references, and symbol search are crucial tools for the everyday tasks of understanding and working with code. Their importance is obvious to users of IDEs like the Eclipse IDE, and there’s a constant effort to build plugins that provide these features for more and more languages.
The Language Server Protocol, originally released by Microsoft, is an open standard that makes it much easier to write editor plugins that work across many languages. And beyond the code in your editor, it has enabled Sourcegraph to bring such features to all the other places programmers view code, including your web browser, code review tool, and code search.
An example of the protocol in use, from the README.
Sourcegraph is designed to be a quick, frictionless way to make sense of code. It’s faster than OpenGrok and as smart as your IDE when it comes to things like finding all references to a symbol. Underneath the hood is a complex system that parses and analyzes source code on the fly to provide underlying capabilities that we call Code Intelligence. “Code Intelligence” is just shorthand for language-aware productivity boosters like:
But such features have existed in tools like the Eclipse platform for decades. Why the need now for a new open standard? The reason has to do with tractability.
IDEs like the Eclipse IDE are complex systems that often support Code Intelligence on a certain set of languages. Sourcegraph aims to support every language. LSP makes both these undertakings far more tractable.
Historically, the problem of supporting multiple languages in multiple editors has been O(M·N). You have M editors (Eclipse IDE, Visual Studio Code, Sublime, Atom, Emacs, Vim, etc.) and N languages (Java, JavaScript, Go, TypeScript, Python, etc.). Historically, you need a separate Code Intelligence plugin for each combination of editor and language. Such plugins are expensive to write — you have to understand compiler internals and integrate with different build systems and figure out UI subtleties. As a result, you end up in a world in which there are far fewer than M·N plugins — a world in which your choice of language severely constrains your choice of editor and vice versa. In the perfect world, you should be able to stick with your editor of choice no matter what language you work in.
O(M·N) problem
Defining a clear protocol between the language analyzer and the code viewer/editor is crucial..
LSP defines such a protocol that sits between editor plugins and the underlying analysis libraries. You build one language server for each language and one plugin for each editor. Each editor plugin that speaks LSP will now have support for every single language server. You’ve reduced a O(M·N) problem to a O(M+N) problem.
O(M + N)
The theory translates well into practice. Currently, there is a LSP implementation for almost every major programming language. And that means if your editor plugin speaks LSP, you have access to Code Intelligence across many languages all without having to write a single line of parsing or type-checking code.
Another key feature of LSP is the lack of a strict model for code structure. The protocol has no notion of namespaces, class hierarchies, definitions, or references. How does one represent “jump to definition” with no notion of a definition? In the case of LSP, the input is merely the location of the reference (a filename, line number, and column) and the output is the location of the definition (also a filename, line number, and column).
LSP does not attempt to model the semantic relationships in code at all. But if we are trying to build Code Intelligence, shouldn’t our protocol be aware of at least the basic semantic relationships in code? Surprisingly, the answer is “no” for two reasons:
None of this precludes building a semantic data model on top of LSP. In fact, at Sourcegraph, we’ve done exactly that for more advanced features. But all of that is possible because we build on top of a layer that does not make premature oversimplifications about the code.
The last feature of LSP that I’ll mention in this post is extensibility. The creators of LSP foresaw that in the future, people would desire new functionality. It’s easy to add new functionality to LSP. Indeed, there is a vibrant, open-source community that continues to contribute changes to the protocol while maintaining backwards compatibility with existing LSP plugins.
I’d love to live in a world where it’s as easy to use the Eclipse IDE to write Python or JavaScript as it is to write Java. I’d also love a world where exploring code in any language with IDE-like superpowers was as easy as sharing this hyperlink.
We think the Language Server Protocol will enable both these dreams to become reality. Code Intelligence is what makes the experience of using your IDE magical, and LSP makes that magic far more tractable to implement. We’ve used it to great success so far at Sourcegraph and we’d highly encourage you to check it out for your IDE and editor plugins.
Questions, comments, or feedback about Sourcegraph or LSP? Let us know!
|
https://about.sourcegraph.com/blog/sourcegraph-code-intelligence-and-the-language-server-protocol/
|
CC-MAIN-2018-47
|
refinedweb
| 994
| 61.87
|
This machine mirrors various open-source projects.
2 Gbit/s uplink. Will be upgraded soon...
If there are any issues or you want another project mirrored, please contact mirror-service -=AT=- netcologne DOT de !
A class which provides facilities for dumping details about type nodes. More...
#include "AstDumper.h"
#include "comma/ast/TypeVisitor.h"
#include "llvm/Support/raw_ostream.h"
Go to the source code of this file.
A class which provides facilities for dumping details about type nodes.
The facilities provided by this class are useful for debugging purposes and are used by the implementation of Ast::dump().
Definition in file TypeDumper.h.
|
https://mirror.netcologne.de/savannah/comma/doxygen/TypeDumper_8h.html
|
CC-MAIN-2021-49
|
refinedweb
| 103
| 54.59
|
OK, this one is a bit more complex, so start here, then go there.
WHY C# events
An EVENT in C# is simply a means to create a CHAIN of functions that will execute when something “happens” to an object.
EVENTS in C# follow the observer design pattern. The object that CONTAINS the “event” is the “PUBLISHER”, while all the objects that “attach a function” to the event are “subscribers” to that event.
Understanding C# custom events
As a prerequisite to understanding this, you must have already worked with normal events in C#, and built a couple of simple windowed applications using .NET. If not, go read up on them, also try this.
In fact, let me summarize the prereqs to understanding this article here:
- Worked with events in C# normally before (windows forms applications)
- Understands delegates
If you don’t have those prereqs, RUN AWAY!! This will not make any sense to you, especially if you don’t understand delegates at all.
Custom events are great!
The point of defining custom events in C# is to provide an EASY MECHANISM to have a chain of functions that will execute in rapid succession on your command.
The idea is this. You have an object, say a BUTTON. WHEN THAT BUTTON IS CLICKED by the user, you want some function to run. But wait, not just ONE function. You want SEVERAL functions to run. In rapid succession, one after the other. AND YOU WANT THEM TO RUN WHEN THE BUTTON IS CLICKED!
So here’s what you do. You define an EVENT
using System; public class Button { // Define the EVENT here. public event Action Pushed ; // NOTICE how we specify the ACTION delegate // in this declaration. // The ACTION delegate use means that // the "Pushed" event accepts a chain of // functions to be attached to it that all have // NO arguments, and return type VOID. // You can use ANY DELEGATE TYPE YOU WANT for // an event in C#. You can define your own // delegate type if you want, but you will really // have to study and understand delegates if you // want to do that (not covered here!) // This is the function that triggers the event. public void PushButton() { // Print out a message before actually firing the // Pushed event. Console.WriteLine("Oh, you pushed me."); // !! VERY IMPORTANT LINE!! Pushed(); // "FIRE" EVENT: CAUSES ALL FUNCTIONS THAT WERE ATTACHED // TO THE "Pushed" EVENT PREVIOUSLY TO EXECUTE IN // RAPID SUCCESSION, ONE AFTER THE OTHER! // The funny thing about Events is the WEIRD, WEIRD, WEIRD // syntax is uses. At one moment, you're +='ing to it, // the next moment, you're calling it as if it were a function. // Strictly speaking, the Pushed event ISN'T a function. // Its a series of functions.. internally it must be some // kind of object with some kind of linked list inside. But // in any case, this notation takes some getting used to, // but once you're used to it, it makes a whole lotta sense. // ALSO, take note that YOU MUST "FIRE" THIS EVENT FROM // WITHIN THE Button CLASS! // YOU __CANNOT__ "FIRE" AN EVENT OUTSIDE THE CLASS IN WHICH // THAT EVENT IS DECLARED. I explain this in more detail // below. // Finally, print out another message after firing all // event functions. Console.WriteLine("Great, now my paint is all dented"); } } public class Program { // one function that will be attached // to the Button's Pushed event. Notice // it can be attached because it has // no arguments and return type void. public static void ButtonPusher() { Console.WriteLine("HI THERE!!"); } // another function that will be attached // to the button's Pushed event public static void func2() { Console.WriteLine("HELLO!!"); } // notice because of our use of the ACTION delegate // type in the Pushed event declaratino, we CANNOT // attach THIS functino to the Pushed event. THe // signature of functions you attach to the Pushed event // MUST MATCH the signature of the delegate type you used // in the declaration of the event. In this case the Pushed // event uses the Action delegate type, which is defined // in the .NET framework to be a delegate of return type void, // and accepts no arguments. public static void sayHi( int howMany ) { Console.WriteLine( howMany + " hi's to yoU!" ) ; } static void Main( string[] args ) { Button b = new Button(); // Attach 3 functions to execute // when the Pushed event fires // from within the button b.Pushed += new Action( ButtonPusher ); b.Pushed += new Action( func2 ); b.Pushed += new Action( ButtonPusher ); // Illegal: sayHi does not match the Action delegate type, // and the Pushed event requires that the functions chained on // match the Action delegate type. ////////b.Pushed += new Action( sayHi ) ; // now push the button, (which in turn, // FIRES THE EVENT) b.PushButton(); // Finally, notice this is illegal /////b.Pushed() ; // The error is: // Error 1 The event 'Button.Pushed' can only appear on the // left hand side of += or -= (except when used from // within the type 'Button') // Reason: basically the EVENT member itself // is kind of private to the class. You're not // allowed to "invoke it" from outside the Button class. // But you can, as we did here, define a function // within the Button class that in turn, invokes/fires // the event. } }
I think events are rooted in the observer pattern, but you don’t have to know the observer pattern to apply what we’re working on here.
Ah, so, declaring a custom event in C# is fun. To summarize, here’s what you need:
1. A public delegate, which effectively specifies the type of function (argument list, return type) that can be chained onto the event. In this example, we just used the .NET defined Action delegate, which has return type void and no arguments passed to it.
2. Declaration of the event itself, inside the class that the event can “happen to”
3. Lastly, you TRIGGER the event from within the class in which the event is declared. You MAY NOT trigger the event from outside the class in which it is declared (you may NOT type eventName() OUTSIDE THE CLASS, EVER.)
|
https://bobobobo.wordpress.com/tag/events/
|
CC-MAIN-2018-22
|
refinedweb
| 999
| 73.78
|
I am studying the source code contained in session.rb in an effort to
understand how it works. I am encountering various instances of syntax
that I don’t understand. I’m sure Google would be my friend if I knew
what terms to use as search criteria. I’m hoping that I can post a few
of them here for clarification without being overly burdensome.
The first strange syntax that I encountered was what was apparently a
class definition in the Session class: Here’s the syntax:
def Session::create_new_id
In this case the separator between the identity of the class and the
name of the method is a double colon rather than the usual period.
What is the significance of using a double-colon as a separator?
Thanks for any input.
... doug
|
https://www.ruby-forum.com/t/class-method-definition-unrecognized-syntax/221874
|
CC-MAIN-2021-31
|
refinedweb
| 134
| 63.8
|
The Web Service binding (binding.ws) can be applied to SCA services and references. It does the following: *For service bindings, publishes "Plain Old Java Object" (POJO) "services" as Web Services. *Parses the binding.ws element and generates a WSDL of the service to be published or the reference to be invoked. (This includes policy references.) *Publishes the service as a JAX-WS Web Service. *Accepts request for the published services and performs reference invocations to the Web Services. Specifies a reference to the security policy to use. The following security mechanisms are supported: *Username token with message protection (WS-Security 1.1) *X509 certificate authentication with message protection (WS-Security 1.1) *Anonymous with message protection (WS-Security 1.1) *ID Propagation using SAML token (sender-vouches) with message protection (WS-Security 1.1) *Username token over SSL *SAML token (Sender Vouches) over SSL Valid properties are: a) weblogic.sca.binding.ws.sdoSchemaFile - property to specify the location of the schema file for SDO bindings. Used (and required) only if using databinding=toplink.sdo in binding.ws. The path must be relative to the application root, and the schema file must be bundled with the app b) weblogic.sca.binding.ws.externalCustomizationFile - property to specify an external databinding customization XML file. This can be used to provide additional information on the web service binding One example scenario of the use of the customization file is when your contract class for a SCA service contains overloaded methods that you want to expose as web service operations. In this case, the customization file can be used to disambiguate operation names for the web service. The path must be relative to the application root, and the customization file must be bundled with the app. c) weblogic.sca.binding.ws.referenceWsdlCacheTimeoutMins - property to set a timeout (in minutes) for wsdl caching when invoking references. References to wsdls are cached by default to provide better performance for high volume applications. If this property is unspecified, the timeout (i.e. refresh interval) for cached wsdls is assumed to be 60 minutes. This property can be set to zero to disable caching d) weblogic.sca.binding.ws.usingOwsmPolicies - property to indicate whether the PolicyReference supplied in binding.ws is an OWSM policy or not. This property is optional and defaults to false. For sca:service, indicate the port name to use for the service endpoint. For sca:reference, specifies the WSDL port that this reference points to in the external Web Service. This should be of the form namespace uri#wsdl.endpoint(servicename/portname) Required for sca:reference bindings only. Specifies the location (that is, URL) where the external reference can be found. The WSDL must be made available by appending ?wsdl to this location. The soapVersion of the web service - valid values are 1.1 and 1.2. Defaults to 1.1. The type of databinding to use - defaults to "toplink.jaxb", other options are "glassfish.jaxb" and "toplink.sdo" (Note that the schema required for SDO databinding will be supplied as a property in the binding) The EJB session bean binding can be applied to both SCA services and SCA references. Binding to Services:. Binding to References:. No longer in use. All EJB bindings are now considered remote and the implementation completely disregards the "remote" attribute. Optional. Specifies the name of the binding. For Web Service bindings, if supplied, it will be used as the service name for the web service in the WSDL". For Web Service bindings, it is required for sca:service bindings only. Specifies the location, relative to the context-root of the SCA application, where the Web Service must be published for this SCA service.
|
http://www.oracle.com/webfolder/technetwork/weblogic/weblogic-sca-binding/1.0/weblogic-sca-binding.xsd
|
CC-MAIN-2017-22
|
refinedweb
| 615
| 51.95
|
Will do, but I first need to grab a compiler. Don't have one on this computer.
Printable View
Will do, but I first need to grab a compiler. Don't have one on this computer.
Check the return values - cin is put into a fail state after the first getline, so until you clear it all subsequent reads will fail. See what happens when you change the first getline to:Code:
if (!cin.getline(ch, 10))
cin.clear();
Yes, it solves the problem. I never really knew what cin.clear() did before this.
Why is cin put in fail safe mode? I can't find any information on getline() that describes that behavior?Why is cin put in fail safe mode? I can't find any information on getline() that describes that behavior?Quote:
Originally Posted by Daved
MSDN::
The second.
Thanks.
After playing around a bit with those two successive calls to getline(), this is what I came up with to make the program work in a predictable way:
Code:
#include <iostream>
using namespace std;
int main()
{
char ch[3];
char left[3];
cout<<"Enter characters."<<endl;
cin.getline(ch,3);
if(cin.fail()) //then there are more characters to read
cin.clear();
else //the buffer is empty
cout<<"Enter some more characters:\n";
cin.getline(left, 3);
cout<<ch<<endl;
cout<<left<<endl;
return 0;
}
|
https://cboard.cprogramming.com/cplusplus-programming/61556-tell-me-if-im-right-2-print.html
|
CC-MAIN-2017-22
|
refinedweb
| 228
| 77.74
|
Metaprogramming is the process of using code to write code. In Elixir this gives us the ability to extend the language to fit our needs and dynamically change the code. We’ll start by looking at how Elixir is represented under the hood, then how to modify it, and finally we can use this knowledge to extend it.
A word of caution: Metaprogramming is tricky and should only be used when necessary. Overuse will almost certainly lead to complex code that is difficult to understand and debug.
The first step to metaprogramming is understanding how expressions are represented. In Elixir the abstract syntax tree (AST), the internal representation of our code, is composed of tuples. These tuples contain three parts: function name, metadata, and function arguments.
In order to see these internal structures, Elixir supplies us with the
quote/2 function. Using
quote/2 we can convert Elixir code into its underlying representation:
iex>"]]}
Notice the first three don’t return tuples? There are five literals that return themselves when quoted:
iex> :atom :atom iex> "string" "string" iex> 1 # All numbers 1 iex> [1, 2] # Lists [1, 2] iex> {"hello", :world} # 2 element tuples {"hello", :world}
Now that we can retrieve the internal structure of our code, how do we modify it? To inject new code or values we use
unquote/1. When we unquote an expression it will be evaluated and injected into the AST. To demonstrate
unquote/1 let’s look at some examples:
iex> denominator = 2 2 iex> quote do: divide(42, denominator) {:divide, [], [42, {:denominator, [], Elixir}]} iex> quote do: divide(42, unquote(denominator)) {:divide, [], [42, 2]}
In the first example our variable
denominator is quoted so the resulting AST includes a tuple for accessing the variable. In the
unquote/1 example the resulting code includes the value of
denominator instead.
Once we understand
quote/2 and
unquote/1 we’re ready to dive into macros. It is important to remember that macros, like all metaprogramming, should be used sparingly.
In the simplest of terms macros are special functions designed to return a quoted expression that will be inserted into our application code. Imagine the macro being replaced with the quoted expression rather than called like a function. With macros we have everything necessary to extend Elixir and dynamically add code to our applications.
We begin by defining a macro using
defmacro/2 which, like much of Elixir, is itself a macro (let that sink in). As an example we’ll implement
unless as a macro. Remember that our macro needs to return a quoted expression:
defmodule OurMacro do defmacro unless(expr, do: block) do quote do if !unquote(expr), do: unquote(block) end end end
Let’s require our module and give our macro a whirl:
iex> require OurMacro nil iex> OurMacro.unless true, do: "Hi" nil iex> OurMacro.unless false, do: "Hi" "Hi"
Because macros replace code in our application, we can control when and what is compiled. An example of this can be found in the
Logger module. When logging is disabled no code is injected and the resulting application contains no references or function calls to logging. This is different from other languages where there is still the overhead of a function call even when the implementation is NOP.
To demonstrate this we’ll make a simple logger that can either be enabled or disabled:
defmodule Logger do defmacro log(msg) do if Application.get_env(:logger, :enabled) do quote do IO.puts("Logged message: #{unquote(msg)}") end end end end defmodule Example do require Logger def test do Logger.log("This is a log message") end end
With logging enabled our
test function would result in code looking something like this:
def test do IO.puts("Logged message: #{"This is a log message"}") end
If we disable logging the resulting code would be:
def test do end
Okay, right now we know how to use
quote/2,
unquote/1 and write macros. But what if you have a huge chunk of quoted code and want to understand it? In this case, you can use
Macro.to_string/2. Take a look at this example:
iex> Macro.to_string(quote(do: foo.bar(1, 2, 3))) "foo.bar(1, 2, 3)"
And when you want to look at the code generated by macros you can combine them with
Macro.expand/2 and
Macro.expand_once/2, these functions expand macros into their given quoted code. The first may expand it several times, while the former - only once. For example, let’s modify
unless example from the previous section:
defmodule OurMacro do defmacro unless(expr, do: block) do quote do if !unquote(expr), do: unquote(block) end end end require OurMacro quoted = quote do OurMacro.unless true, do: "Hi" end
iex> quoted |> Macro.expand_once(__ENV__) |> Macro.to_string |> IO.puts if(!true) do "Hi" end
If we run the same code with
Macro.expand/2, it’s intriguing:
iex> quoted |> Macro.expand(__ENV__) |> Macro.to_string |> IO.puts case(!true) do x when x in [false, nil] -> nil _ -> "Hi" end
You may recall that we’ve mentioned
if is a macro in Elixir, here we see it expanded into the underlying
case statement.
Though not as common, Elixir does support private macros. A private macro is defined with
defmacrop and can only be called from the module in which it was defined. Private macros must be defined before the code that invokes them.
How macros interact with the caller’s context when expanded is known as macro hygiene. By default macros in Elixir are hygienic and will not conflict with our context:
defmodule Example do defmacro hygienic do quote do: val = -1 end end iex> require Example nil iex> val = 42 42 iex> Example.hygienic -1 iex> val 42
What if we wanted to manipulate the value of
val? To mark a variable as being unhygienic we can use
var!/2. Let’s update our example to include another macro utilizing
var!/2:
defmodule Example do defmacro hygienic do quote do: val = -1 end defmacro unhygienic do quote do: var!(val) = -1 end end
Let’s compare how they interact with our context:
iex> require Example nil iex> val = 42 42 iex> Example.hygienic -1 iex> val 42 iex> Example.unhygienic -1 iex> val -1
By including
var!/2 in our macro we manipulated the value of
val without passing it into our macro. The use of non-hygienic macros should be kept to a minimum. By including
var!/2 we increase the risk of a variable resolution conflict.
We already covered the usefulness of
unquote/1, but there’s another way to inject values into our code: binding. With variable binding we are able to include multiple variables in our macro and ensure they’re only unquoted once, avoiding accidental revaluations. To use bound variables we need to pass a keyword list to the
bind_quoted option in
quote/2.
To see the benefit of
bind_quote and to demonstrate the revaluation issue let’s use an example. We can start by creating a macro that simply outputs the expression twice:
defmodule Example do defmacro double_puts(expr) do quote do IO.puts unquote(expr) IO.puts unquote(expr) end end end
We’ll try out our new macro by passing it the current system time. We should expect to see it output twice:
iex> Example.double_puts(:os.system_time) 1450475941851668000 1450475941851733000
The times are different! What happened? Using
unquote/1 on the same expression multiple times results in revaluation and that can have unintended consequences. Let’s update the example to use
bind_quoted and see what we get:
With
bind_quoted we get our expected outcome: the same time printed twice.
Now that we’ve covered
quote/2,
unquote/1, and
defmacro/2 we have all the tools necessary to extend Elixir to suit our needs.
|
https://elixirschool.com/lessons/advanced/metaprogramming/
|
CC-MAIN-2016-50
|
refinedweb
| 1,304
| 63.8
|
Results 1 to 3 of 3
Thread: HELP REquired -urgent
- Join Date
- Jun 2005
- 15
- Thanks
- 0
- Thanked 0 Times in 0 Posts
HELP REquired -urgent
Hi Friends,
I have this requirement .Can Any one help me
I have to write a javascript which checks for the VPN connectivety If the connectivity exists it must take the user to google .co.in. Else it must take the user to a error page.
It must also work when the user is having the connectivity and suddenly the connectivity is removed.Then upon refreshing the page the script must take the user to the error page.
plz help me out with this.
- Join Date
- Jun 2002
- Location
- London, England
- 19,377
- Thanks
- 217
- Thanked 2,696 Times in 2,672 Posts
Suggest you have a look at the posting guidelines, especially regarding the title.
As far as I know JavaScript is not able to do what you are wanting.
public string ConjunctionJunction(string words, string phrases, string clauses)
- Join Date
- Apr 2005
- 1,051
- Thanks
- 0
- Thanked 0 Times in 0 Posts
{
return (String)(words + phrases + clauses);
}
<--- Was I Helpfull? Let me know ---<
|
http://www.codingforums.com/javascript-programming/68537-help-required-urgent.html
|
CC-MAIN-2017-26
|
refinedweb
| 191
| 78.28
|
i have been trying to incorporate various element into this mortgage calculation program. it is supposed to present the three options from the array or prompt you to enter your own rates. my structure with the public and private sections are out of place. i need help streamlining this and resolving its massive errors from my faulty logic.
#include <iostream.h> double MonthlyPayment (double amount, double rate, int months); int GetChoice(void); int main( ); //struct Choice static const Choice menu[] = ( 7, 5.35, 15, 5.5, 30, 5.75 ); //if i put the colon before menu= lots of errors { int term; double rate; void Show() { std::cout << term << " years @ " << rate << '%' << std::endl; } }; int main(); { size_t selection; do { for ( size_t i = 0; i < sizeof menu / sizeof *menu; ++i ) { std::cout << '(' << i << ") "; menu[i].Show(); } std::cout << "Selection ? "; std::cin >> selection; } while ( selection >= sizeof menu / sizeof *menu ); std::cout << "Your selection:\n"; menu[selection].Show(); return 0; } { double months, amount, rate; int option; //create a loop while((option = GetChoice()) == 1) { //option = GetChoice(); cout << "Enter the loan amount: "; cin >> amount; cout << "Enter the interest rate (X.Y): "; cin >> rate; cout << "Enter the length of the loan in months : "; cin >> months; //this line will generate a loss of data warning cout << "\tYour monthly payment is $ "<<MonthlyPayment(amount, rate, months)<<endl; } return 0; } int GetChoice(void) { int num; cout << endl; cout << "1. Calculate your monthly payment on the loan." << endl << "You will enter the loan amount, Interest rate, and Length of the loan" << endl; cout << "0. Exit the program" << endl; cout << "Press 1 to procede : "; cin >> num; return num; } double MonthlyPayment (double amount, double rate, int months) { //declare a local variable to be used for calc's and to hold return value, not function name! double monthPayment; // do the calc's //amount, months and rates values declared in prototype parameters, no need to define local variables monthPayment = (amount * months) / rate /1200; return monthPayment; //return the double }
|
https://www.daniweb.com/programming/software-development/threads/6121/program-help
|
CC-MAIN-2018-05
|
refinedweb
| 321
| 61.06
|
Spring Batch 2.2.0.RELEASE is now available
We are pleased to announce that Spring Batch 2.2.0.RELEASE is now available via Maven Central, Github and the SpringSource download repository.
Spring Batch Home | Source on GitHub | Reference Documentation
Support for Spring Data
Spring implementations for Neo4J and MongoDB as well as
ItemWriter impelementaions for Neo4J, MongoDB and Gemfire. We also have created a
RepositoryItemReader and
RepositoryItemWriter. Each of these implementations wrap any custom implementation of
PagingAndSortingRepository and
CrudRepository respsectively.
Java Configuration
Joining most of the other major Spring projects, with Spring Batch 2.2.0.RELEASE, you will be able to configure your batch jobs via Java config. The
@EnableBatchProcessing annotation.
@Configuration @EnableBatchProcessing @Import(DataSourceCnfiguration.class) public class AppConfig { @Autowired private JobBuilderFactory jobs; @Bean public Job job() { return jobs.get("myJob").start(step1()).next(step2()).build(); } @Bean protected Step step1() { ... } @Bean protected Step step2() { ... } }
The above java config is equivelant to the below XML configuration.
<batch> <job-repository /> <job id="myJob"> <step id="step1" .../> <step id="step2" .../> </job> <beans:bean <beans:property </beans:bean> </batch>
Non-identifying Job Parameters
Running.
AMQP support
Utilizing the Spring AMQP project, Spring 2.2.0.RELEASE offers support for both reading and writing to AMQP endpoints.
SQLFire support
Previous versions of Spring Batch provided a number of options for what database to use within the job repository. With the release of Spring Batch 2.2.0.RELEASE, we add support for SQLFire as yet another option for you to store job repository data.
Dependency upgrade
As part of the ongoing work to keep the dependencies of Spring Batch up to date, we updated batch to support Spring 3.2.x (minimum level of support is now 3.1.2) as well as Hibernate 4 (within the Hibernate based ItemReaders and ItemWriters).
Other updates and fixes
Beyond all of the new features, we also address many bugs and provided numerous other improvements. The complete list of what has changed between Spring Batch 2.2.0.RELEASE and your current version of Spring Batch can be found here in the changelog.
Links
Spring Batch Home | Source on GitHub | Reference Documentation
|
http://spring.io/blog/2013/06/06/spring-batch-2-2-0-release-is-now-available
|
CC-MAIN-2017-43
|
refinedweb
| 357
| 51.44
|
Linear.
Simple linear regression
The most basic kind of regression problem has a single predictor (the
input) and a single outcome. Given a list of input values
and corresponding output values
, we have to find
parameters m and b such that the linear function:
Is "as close as possible" to the observed outcome y. More concretely, suppose we get this data [1]:
We have to find a slope m and intercept b for a line that approximates this data as well as possible. We evaluate how well some pair of m and b approximates the data by defining a "cost function". For linear regression, a good cost function to use is the Mean Square Error (MSE) [2]:
Expanding
, we get:
Let's turn this into Python code (link to the full code sample):
def compute_cost(x, y, m, b): """Compute the MSE cost of a prediction based on m, b. x: inputs vector y: observed outputs vector m, b: regression parameters Returns: a scalar cost. """ yhat = m * x + b diff = yhat - y # Vectorized computation using a dot product to compute sum of squares. cost = np.dot(diff.T, diff) / float(x.shape[0]) # Cost is a 1x1 matrix, we need a scalar. return cost.flat[0]
Now we're faced with a classical optimization problem: we have some parameters
(m and b) we can tweak, and some cost function
we want to
minimize. The topic of mathematical optimization is vast, but what ends up
working very well for machine learning is a fairly simple algorithm called
gradient descent.
Imagine plotting
as a 3-dimensional surface, and picking some
random point on it. Our goal is to find the lowest point on the surface, but we
have no idea where that is. A reasonable guess is to move a bit "downwards" from
our current location, and then repeat.
"Downwards" is exactly what "gradient descent" means. We make a small change to
our location (defined by m and b) in the direction in which
decreases most - the gradient [3]. We then repeat this process until we reach
a minimum, hopefully global. In fact, since the linear regression cost function
is convex we will find the global minimum this way. But in the general case
this is not guaranteed, and many sophisticated extensions of gradient descent
exist that try to avoid local minima and maximize the chance of finding a global
one.
Back to our function,
. The gradient is defined
as the vector:
To find it, we have to compute the partial derivatives of MSE w.r.t. the learning parameters m and b:
And then update m and b in each step of the learning with:
Where
is a customizable "learning rate", a hyperparameter. Here is
the gradient descent loop in Python. Note that we examine the whole data set in
every step; for much larger data sets, SGD (Stochastic Gradient Descent) with
some reasonable mini-batch would make more sense, but for simple linear
regression problems the data size is rarely very big.
def gradient_descent(x, y, nsteps, learning_rate=0.1): """Runs gradient descent optimization to fit a line y^ = x * m + b. x, y: input data and observed outputs. nsteps: how many steps to run the optimization for. learning_rate: learning rate of gradient descent. Yields 'nsteps + 1' triplets of (m, b, cost) where m, b are the fit parameters for the given step, and cost is their cost vs the real y. """ n = x.shape[0] # Start with m and b initialized to 0s for the first try. m, b = 0, 0 yield m, b, compute_cost(x, y, m, b) for step in range(nsteps): yhat = m * x + b diff = yhat - y dm = learning_rate * (diff * x).sum() * 2 / n db = learning_rate * diff.sum() * 2 / n m -= dm b -= db yield m, b, compute_cost(x, y, m, b)
After running this for 30 steps, the gradient converges and the parameters barely change. Here's a 3D plot of the cost as a function of the regression parameters, along with a contour plot of the same function. It's easy to see this function is convex, as expected. This makes finding the global minimum simple, since no matter where we start, the gradient will lead us directly to it.
To help visualize this, I marked the cost for each successive training step on the contour plot - you can see how the algorithm relentlessly converges to the minimum
The final parameters learned by the regression are 2.2775 for m and 6.0028 for b, which is very close to the actual parameters I used to generate this fake data with.
Here's a visualization that shows how the regression line improves progressively during learning:
Evaluating how good the fit is
In statistics, there are many ways to evaluate how good a "fit" some model is on the given data. One of the most popular ones is the r-squared test ("coefficient of determination"). It measures the proportion of the total variance in the output (y) that can be explained by the variation in x:
This is trivial to translate to code:
def compute_rsquared(x, y, m, b): yhat = m * x + b diff = yhat - y SE_line = np.dot(diff.T, diff) SE_y = len(y) * y.var() return 1 - SE_line / SE_y
For our regression results, I get r-squared of 0.76, which isn't too bad. Note that the data is very jittery, so it's natural the regression cannot explain all the variance. As an interesting exercise, try to modify the code that generates the data with different standard deviations for the random noise and see the effect on r-squared.
An analytical solution to simple linear regression
Using the equations for the partial derivatives of MSE (shown above) it's possible to find the minimum analytically, without having to resort to a computational procedure (gradient descent). We compare the derivatives to zero:
And solve for m and b. To make the equations easier to follow, let's
introduce a bit of notation.
is the mean value of x across
all samples. Similarly
is the mean value of y. So the sum
is actually
. Now let's take the second
equation from above and see how to simplify it:
Similarly, for the partial derivative by m we can reach:
In these equations, all quantities except m and b are constant. Solving them for the unknowns m and b, we get [4]:
If we plug the data values we have for x and y in these equations, we get 2.2777 for m and 6.0103 for b - almost exactly the values we obtained with regression [5].
Remember that by comparing the partial derivatives to zero we find a critical point, which is not necessarily a minimum. We can use the second derivative test to find what kind of critical point that is, by computing the Hessian of the cost:
Plugging the numbers and running the test, we can indeed verify that the critical point is a minimum.
Multiple linear regression
The good thing about simple regression is that it's easy to visualize. The model is trained using just two parameters, and visualizing the cost as a function of these two parameters is possible since we get a 3D plot. Anything beyond that becomes increasingly more difficult to visualize.
In simple linear regression, every x is just a number; so is every y. In
multiple linear regression this is no longer so, and each data point x is a
vector. The model parameters can also be represented by the vector
. To avoid confusion of indices and subscripts, let's agree that
we use subscripts to denote components of vectors, while parenthesized
superscripts are used to denote different samples. So
is the
second component of sample 6.
Our goal is to find the vector
such that the linear function:
Is as close as possible to the actual y across all samples. Since working with
vectors is easier for this problem, we define
to always be equal to
1, so that the first term in the equation above denotes the intercept.
Expressing the regression coefficients as a vector:
We can now rewrite
as:
Where both
and x are column vectors with n+1 elements, as
shown above. The mean square error (over k samples) now becomes:
Now we have to find the partial derivative of this cost by each
.
Using the chain rule, it's easy to see that:
And use this to update the parameters in every training step. The code is
actually not much different from the simple regression case; here is a well
documented, completely worked out example.
The code takes a realistic dataset from the UCI machine learning repository with 4 predictors and a single outcome and
builds a regression model. 4 predictors plus one intercept give us a
5-dimensional
, which is utterly impossible to visualize, so we
have to stick to math in order to analyze it.
An analytical solution to multiple linear regression
Multiple linear regression also has an analytical solution. If we compute the
derivative of the cost by each
, we'll end up with n+1 equations
with the same number of variables, which we can solve analytically.
An elegant matrix formula that computes
from X and y is
called the Normal Equation:
I've written about deriving the normal equation
previously, so I won't spend more time on it. The accompanying code computes
using the normal equation and compares the result with the
obtained from gradient descent.
As an excercise, you can double check that the analytical solution for simple linear regression (formulae for m and b) is just a special case of applying the normal equation in two dimensions.
You may wonder: when should be use the analytical solution, and when is gradient descent better? In general, whenever we can use the analytical solution - we should. But it's not always feasible, computationally.
Consider a data set with k samples and n features. Then X is a k x n
matrix, and hence
is a n x n matrix. Inverting a matrix is a
operation, so for large n, finding
can take
quite a bit of time. Moreover, keeping
in memory can be
computationally infeasible if
is huge and sparse, but
is
dense. In all these cases, iterative gradient descent is a more feasible
approach.
In addition, the moment we deviate from the linear regression a bit, such as adding nonlinear terms, regularization, or some other model enhancement, the analytical solutions no longer apply. Gradient descent keeps working just the same, however, as long as we know how to compute the gradient of the new cost function.
|
http://eli.thegreenplace.net/2016/linear-regression/
|
CC-MAIN-2017-09
|
refinedweb
| 1,775
| 60.75
|
Toggle navigation
Gallery
Solution
Become Agents
Delivery
FAQS
Services
Products
WPC Decking
Outdoor Wall Panel
PVC Fence
CO-Extrusion Decking
PVC Synthetic Boat Deck
WPC Fence
Outdoor Furniture
DIY Decking
Free Samples
Project Case
decorative indoor non slip stair treads
decorative indoor non slip stair treads
Decorative Indoor Stair Treads | Stair Treads, Corner ...
The decorative indoor stair treads are not just there to be decorative. ... indoor stair treads are made to be slip ... decorative indoor stair treads that ...
Non Slip Stair Treads - Sears
"non slip stair treads" ... Dark Gray Ribbed 30" x 8" Indoor/Outdoor Non-Skid Slip ... Crystal Emotion Decorative Piano Music Key Living Room Doormat Kitchen ...
Decorative Indoor Stair Treads, Decorative ... - Alibaba
Alibaba offers 2,785 decorative indoor stair treads products. such as free samples, paid samples.
Stair Treads Carpet Non Slip - Foter
Ensure a significant boost of safety for your interior with these indoor non-slip stair treads. ... are gray stair treads carpet non-slip ... and decorative value ...
Decorative Indoor Stair Treads | Wayfair
Quickview. These beautiful machine made Stair Treads feature durable low profile nylon pile with a modern color palette. Non-slip rubber backing enhances safety and ...
Decorative Indoor Stair Treads | Wayfair
Shop Wayfair for the best decorative indoor stair treads. ... indoor carpet stair treads indoor non slip stair treads decorative indoor stair treads indoor stair ...
15 Best Decorative Indoor Stair Treads | Stair Tread Rugs ...
Using decorative indoor stair treads in your home can help you to manage to create a better look for the family room or other room that you are currently putting them in.
Top Lovely Decorative Indoor Stair Treads - Broxtern ...
Lovely Decorative Indoor Stair Treads – Thank’s for visiting my site, Decorative Indoor Stair Treads gallery is one of the many images galleries contained in this ...
Decorative Non Slip Stair Treads | Bizrate
Explore discounts on Decorative non slip stair treads. Compare Prices, & Save Money on brands such as Bungalow Flooring, Dean Flooring Company and Colonial Mills at ...
Amazon: decorative indoor stair treads
EdenTapes(15-PACK)Pre Cut Transparent 24"x4" Anti Slip Clear Tape , Family Safety For Kids, Elders And Pets, Adhesive Stair Treads, Indoor, Outdoor, Prevents Slipping ...
The 5 Best Stair Treads [Ranked] | Product Reviews and Ratings
All of the stair treads we looked at are for indoor use save for the Rubber-Cal “Coin Grip” Non slip rubber tread stair mats 6 pack and the Puchan-LM Outdoor ...
Amazon: decorative stair treads
KEYAMA Acrylic Set of 15 indoor Floral/Flowers carpet stair treads free tape Non-slip stair carpet Treads carpet staircase decorative area rugs 9"W x 30"L Red 059
Indoor/Outdoor non slip stair treads at Brookstone—Buy Now!
Buy indoor/outdoor non slip stair treads at Brookstone. Shop now!
Decorative Indoor Stair Treads ‹ Decor Love
Feel free to look through my collection of decorative indoor stair treads. ... anti-slip underside and a beautiful decorative ... Non Slip Indoor Stair Treads ...
Outdoor WOOD LOOK DECORATIVE RUBBER STAIR TREADS NEW | eBay
Find best value and selection for your Outdoor WOOD LOOK DECORATIVE RUBBER STAIR TREADS NEW ... Outdoor Rubber Stair Treads Cover Protector Indoor Non-slip Step ...
Decorative Stair Treads | Beso
Decorative Stair Treads ... your step in these indoor/outdoor stair treads. perfect for ... Tread to give your stairs a decorative, non-slip surface ...
Popular Decorative Stair Treads-Buy Cheap Decorative Stair ...
Buy Decorative Stair Treads from Reliable China Decorative Stair Treads suppliers.Find Quality Decorative Stair Treads Home & Garden,Carpet,Mat,Furniture, and more on ...
Non-Slip Stair Treads - Rubber-Cal
Non-slip stair treads are the perfect solution ... Non-Slip Decorative Rubber Stair Treads Ideal for ... Some indoor and outdoor stair treads are designed ...
Decorative Stair Treads ‹ Decor Love
Have a look at my collection of decorative stair treads ... They are non-slip. ... Large Decorative Wall Mirrors;
Outdoor Non Slip Stair Treads | Amstep Products
Stair Treads For Outdoor Use Stairs ... budget and ease of maintenance on both indoor and outdoor stairs, exterior stair treads exposed to the ... Non-slip paint is ...
Stair Treads | Improvements
Shop our huge selection of beautiful and durable stair treads. ... Baskets & Decorative Boxes; ... 14 Piece Kimberly Solid Slip-Resistant Stair Treads & Rug Set.
decorative stair treads | eBay
Find great deals on eBay for decorative stair treads. ... Stair Tread Mats 2-piece Non-slip Decorative ... 13pcs Stair Treads Rectangle Non-slip Carpet Mats Indoor ...
Decorative Non Slip Stair Treads - Bizgoco
Decorative Indoor Stair Treads. ... In addition to Decorative Non Slip Stair Treads, we also provide you with Non Slip Shoe Cover, Non Slip Floor Tile, ...
Related Posts:
non skid deck bass boat
trinidad and tobago teak lumber exporters
outdoor vinyl provacy screens
import wpc decking
indoor outdoor decorative panels
resurface decking with composite decking
marlite panels home depot
wood plastic composites building
kit wood plastic composite pergola material
discount click patio blocks
paint for plywood boats
6 ft wood fence cost per foot
Random Posts:
plastic lumber orange county
composite timber floors wholesale
kitchen cabinets design lowes
vinyl fence northern ireland
what is the cost per linear foot for a wood composite fence
composite deck stairs non slip
einwood floor manufacturers
rice hull composite decking in china
pvc board cladding exterior wall
hardwood supplier in johor
Wood Plastic Posts:
simple floor designs
is there a market in aus for flooring and walling
composite panel manufacturers india
hdpe plastic panel
wood plastic sheets 4x8 home depot
truck bed decking
Add On Puppy Panel Picket
trinidad wood plastic lattice panel buy
pergola off deck
vinyl wood flooring in baton rouge
composite shingles look like wood
average cost of wood mezzanine floor canada
white composite picket fence
Wood Composite Product:
plastic wood wholesale
where to buy decking tiles in portland oregon
how to make a wooden bench seat Europe and the Middle East
wood grain fence by maintenance
south africa pvc panel manufacture
garden retaining wall ideas
wood plastic fencing egypt
outdoor fence cost calculator Norway
how tio build a round above ground pool deck North...
chinese government issues or problems plastic composites
cost of veranda roof designs
acrylic impregnated wood flooring for home reviews
|
http://sunriseplast.in/co-extruded/5474-decorative-indoor-non-slip-stair-treads.html
|
CC-MAIN-2018-34
|
refinedweb
| 1,007
| 54.22
|
<p>Told ya I would do it!!
<a href=3D"..."></p>
<p><img src=3D"
?apprenticeship"> </a></p>
<br>
<br>
<br>I got more.. if you are daring :)
<br>
<br>
<br>
<a href=3D"">beam me off scotty</a>=
</font></td>
bhatzzt ntqusevnlfdjs d mg
At 22
On Wed, 2003-05-28 at 15:20, Magnus Lyck=E5 wrote:
> At 12:39 2003-05-28 -0500, Ian Bicking wrote:
> >I was thinking of changing the magic method I use to __sqlrepr__, whic=
h
> >seems like a good name to me. Just having a single convention would b=
e
> >a start.
>=20
> Ok with me. It would be good if there was at least a name
> given as an option in the DB-API spec. This function obviously
> exist in a number of implementations, with different names.
>=20
> >Right now I think quoting would probably best be done like:
> >
> >* Integers, floats, strings are all automatically quoted. Maybe
> >mxDateTime and datetime objects too. No hooks for these -- the
> >underlying C driver may want to handle these data structures on its ow=
n
> >anyway.
>=20
> Right.
>=20
> >* Anything with a __sqlrepr__ method has that called, with no
> >arguments. The result is expected to be fully quoted.
>=20
> This is what I thought first, but there were some oppsition to
> the idea on the db-sig mailing list. Let's return to the date
> and Access. Let's say that you have your own date class, and you
> deliver the string "'1984-06-04'". This won't work on Access.
> If __sqlrepr__() had returned '1984-06-04' and another method
> __sqltype__ had returned 'DATE', then the driver could have
> known that it would do "'%s'" % __sqlrepr__() on sane platforms
> and "#%s#" % __sqlrepr__() on that warped MS platform.
Yes, I started thinking about this when I was partway through writing
down my thoughts. Generally the place I am using this kind of
functionality is with various explicit literals, and SQLBuilder in
particular (e.g. SQLBuilder.func.NOW()). In that case it wouldn't cause
too much of a problem that the constructed SQL was not
backend-specific. I know I've this hook elsewhere, but I'm at a loss to
remember when.
If it's not considered the end-all of SQL construction and backend
abstraction, then I think it's still a useful hook.
> If the interface doesn't build the full SQL statement in the
> interface, but actually sends the parameters separately to
> the backend, you might end up with things like
>=20
> INSERT INTO T1 (C1) VALUES ('''that''''s''')
>=20
> That would be a bit sad... :(
>=20
> But still, it's a start. It's certainly reasonable that the
> result from __sqlrepr__ is passed in as is if there is no
> __sqltype__ attribute in the object. I think that __sqltype__
> is also a good idea though.
I think __sqltype__ seems a little awkward. You have to agree on the
types (and type names) that the backend accepts, and that gets into a
whole discussion that seems rather endless ;)
But maybe it should be done in the default quote function, then it can
be overridden for weird databases.
> >* If both those fail, then there's a function which has one last chanc=
e
> >to return a SQL representation on the object. This would be for quoti=
ng
> >types that you couldn't add a __sqlrepr__ method to -- for instance, i=
f
> >mxDateTime objects weren't automatically handled, you might handle the=
m
> >here. Usage something like:
> >
> >import dbdriver
> >old_quote =3D dbdriver.quote
> >def quote(val):
> > if type(val) is DateTimeType:
> > return val.strftime("'%c'")
> > else:
> > return old_quote(val)
>=20
> And then "dbdriver.quote =3D quote" or what?=20
Yes, I forgot to finish it with that.
> Do you register
> this? Why not just supply something like date.Format('%Y-%m-%d')
> instead of your plain date?
Date is a contrived example, since most drivers handle dates natively.=20
Maybe an arbitrary precision number would be a better example.
> But finally: "In case of doubt, refuse the temptation to guess."
> At least some drivers fall back on repr() in an else-statement.
> I only want a "raise TypeError" in the default case.
Yes, I definitely agree. If you really want repr, you'd write something
like:
def quote(val):
try:
return old_quote(val)
except TypeError:
return repr(val)
dbdriver.quote =3D quote
But I definitely repr is bad by default.
> >Maybe there's a better way to phrase this hook, but this might be
> >sufficient. The last quoting technique would probably be the only way
> >to add your own quoting that was database-specific (as would be
> >necessary with Access and mxDateTime objects). So maybe __sqlrepr__
> >should actually just be part of the standard quote function.
>=20
> But drivers that can talk to Access, such as mxODBC and adodbapi have
> no problem with this, since they just pass the unquoted date string to
> the backend and let the ODBC driver handle that. Remember? That's where
> we started. Generally, it's always possible to wrap object in a small
> class that just implements __init__(self, value) and __sqlrepr__(self),
> so I don't quite see the need for this quote function.
The quote function is potentially database specific. After thinking
about it, this function should have the chance to get at the raw value
before __sqlrepr__ is called..
Actually, maybe psycopg doesn't do this, but rather just calls
str()/__str__ (where we use __sqlrepr__) -- certainly a special method
is better, though.
> >Maybe create a DBAPI module again (didn't DBAPI 1 have a common module=
?)
> >-- put this function in there, the quote function, some common
> >exceptions for everyone to use. It'd be DBAPI 3.0, or 2.1... anyway,
> >that's a lot of the biggest problems people seem to have.
>=20
> Agreed. I think some drivers might be implemented entirely in
> C, and others want to be completely Python to be as portable as
> possible, so it might not be trivial to write a module that all
> will agree with...
>=20
> Well, if it's written as a .pyd/.so and becomes a Python standard
> module it should work... :)
Parts of it really need to be in C, I think, so if it's all in C then
probably everyone could be made happy. Who has an all-Python driver?=20
Gadfly I imagine, maybe COM-based drivers...=20
Anyway, people talked serious about including Gadfly in the standard
distribution, so there's interest in supporting database stuff. The
only weird part about the module is that it would be useless on its own.
> With standardized and uniform SQL access and the new datetime class
> I only think we need a fixed point / money data type, and Python
> will be ready to become the COBOL of the 21st century! :)
> (It does sound awful, doesn't it. I guess that's why I like it.)
w00t!
Ian Bicking wrote:
> I think views don't jive well with SQLObject -- they create an opaque
> structure.
Why not have views result in read-only objects? Viz:
class roObject(SQLObject):
_view = 'my_view'
...
...
> But yes, normalization can lead to a whole bunch of tables.
> I'm interested extending the power of joins so that some of these can be
> handled more easily, without having to have too many classes involved.
And this is where every ORM falls down right now. When you're starting
from scratch, every ORM is more or less OK. But if you have to use it
with a pre-existing schema, oop...
> But you don't have to use complicated queries anyway. There's nothing
> intrinsically Wrong about doing the logic in Python. List comprehension
> even makes set operations look nicer, and caching can provide
> performance improvements.
But this means writing an algorithm instead of describing what you want
(declaratively, with SQL).
I haven't done any benchmarking, but given all the indexing that can go
on in an RDBMS, it seems to me that the iterative Python version of:
from table_one
where col_one in (
select col_two
from table_two
where blah)
Is going to be slower since there isn't going to be the benefit of
indexing. Caching won't make anything faster since the RDBMS is caching too.
OTOH, the overhead of the RDBMS parsing, planning, etc. might be quite
high. Hmmm... anybody care to speculate on this? I must benchmark this
one day...
>.
I don't know if I agree with you about this... I'll have to think about
it more. The point about using SQL is that you aren't thinking about
optimization or algorithms at all. You're thinking of the data and
relationships embodied therein--or at least you should be.
In a perfect world, you figure out what data you're looking for, then
describe what you want. It is the RDBMS that does the optimization to
give you what you describe. It is only when it isn't performing well
that one would even think of optimizing your SQL, adding more indices, etc.
...Edmund.
At 19:45 2003-05-28 -0400, Edmund Lian wrote:
>To be honest, I'd rather see synthetic primary keys banished. But, while
>PostgreSQL allows changes in primary keys to cascade automatically to
>foreign keys in other tables, Oracle and a few other databases do not. So,
>the need to be portable might well necessitate synthetic keys.
Does *any* database but PostgreSQL support cascaded key updates
like that?
Anyway, this is *not* the big problem with "natural" primary keys.
The main problem is that the business rules change, and making big
changes in large, actively used databases is very disruptive and
expensive. We want to isolate each needed change as much as possible.
It's far from unique that the set of columns that was the ideal key
yesterday isn't that any longer. Yesterday it was a solid business
rule that only one row in this table could be created per person
each day, so personId + registryDate seemed to be the ideal combo.
The business experts are so sure that they would bet their arm on it.
Today things changed, and in a few cases, it might actually happen
that there have to be two rows for one person on certain dates.
With synthetic keys, this means that we drop a unique index. With
natural keys, our primary key breaks, and with that maybe a whole
tree of keys for detail and sub-detail tables that use these
fields as parts of their primary keys. Yuk! Been there, done that...
I solved it ugly, and cheated with the date in those rare cases,
using the next day, if the current was used, but I'd rather do
things cleanly.
Using the primary key of one table as part of the primary key for
another table just because there is a parent-child relationship
between those tables mean that we have a much tighter coupling
between the tables than we have with synthetic keys. While this
evil, tight coupling can sometimes be avoided in the *primary*
keys of dependent tables, we can't avoid having the entire
primary key (which contains business information for another table)
as foreign key fields in the dependent table.
Not only the data model is hampered by this. The classes in the
application logic, whether it's implemented in Python, Java or
C++ will carry along attributes that really belong to another
class! This also means that the cost of implementing a business
rule change is multiplied.
By using a uniform primary key type, we will also always have a
uniform foreign key type, and it will be much easier to change
the table structure. After all we sometimes realize the the X
objects aren't really atttibutes of the Y object, but rather of
the Z objects. Natural keys create some kind of software structure
cement, and makes changes in business rules very hard. Often,
these structures get cemented long before the product is even
launched. It's one thing that it's difficult to migrate loads of
important business data, but it *should* at least be swift to
change the system if it isn't running yet.
For a different problem that brought me to the same conclusion, see
--
Magnus Lycka (It's really Lyckå), magnus@...
Thinkware AB, Sweden,
I code Python ~ The shortest path from thought to working program
On Wed, 2003-05-28 at 18:53, Edmund Lian wrote:
> Apologies for the delay in replying...
No problem, we all have other lives too...
> > What I suspect Edmund's problem is, is that his tables don't map well to
> > classes. Or maybe more accurately, his *usage* doesn't map well to
> > instances and attribute access. I'm imagining that his applications are
> > phrased with rows being relations, not so much structured data. Or at
> > least some of the data.
>
> Not to mention that in a fully normalized database, there can be a ton
> of joins to get what you want (or else views are used, but it's the same
> thing).
I think views don't jive well with SQLObject -- they create an opaque
structure. But yes, normalization can lead to a whole bunch of tables.
I'm interested extending the power of joins so that some of these can be
handled more easily, without having to have too many classes involved.
> My usage is certainly very traditional in that I use fully normalized
> data models. Getting what I want does require the use of subselects,
> multiway joins and outer joins, transactions and rollbacks, etc. I still
> can't see how to do these, or else change the data model to avoid these
> so that I can use SQLObject. But, I'll try and report back what I find.
Any ORM involves moving logic into Python (or whatever programming
language). That's a compromise you'll have to deal with.
But you don't have to use complicated queries anyway. There's nothing
intrinsically Wrong about doing the logic in Python. List comprehension
even makes set operations look nicer, and caching can provide
performance improvements..
Ian
|
https://sourceforge.net/p/sqlobject/mailman/sqlobject-discuss/?viewmonth=200305&viewday=29&style=flat
|
CC-MAIN-2018-22
|
refinedweb
| 2,355
| 72.56
|
topics covered:
Hurricane Isabelle has introduced itself with a drizzle of rain and wind. I've so far staved off the desire to put So Central Rain on repeat. In grade school, fourth I think, we learned that hurricanes are no longer named exclusively after women, because feminists were bothered by the characterization as tempestuous and destructive. The girls in the class were all unanimous that they liked the idea of girl hurricanes, because they're strong and assertive. [They alternate boy and girl names now, in case ya didn't know, and annually alternate between two lists, one with boy name first and one with girl name first.]
I hope I'm keeping the proper blog tone here... From Nerve.com's list of fifty most unsexy things: ``9. Livejournal. How I'm feeling: bored. Song stuck in my head: "Raspberry Beret." Air of mystery that once surrounded me: gone.''
I was really into Carl Steadman, a sort of internet pioneer and the guy who runs Plastic. I really felt for him after reading his autobiography in this Wired article, and could relate to the leitmotiv `Carl is tired.' Kid A in Alphabetland is everything a work of art should be. [I've found conflicting sources on whether Radiohead stole the title from Carl or not.] But then I read his blog, which is exceptionally histrionic. Air of mystery surrounding Carl: gone.
Our motivations for blogging are twofold. First, there's the pleasant ego boost of having random 14-yr olds who found you on Google write to you to tell you that they read what you wrote and now they like you. Also, I have a chance to shill books and try to leech a bit more of an Amazon commission out of people. Got a book/DVD/toy you want? I'll give you a dollar if you write me with the item name and then buy it from my link.
Re: comments. The blog form mandates that there be a mechanism by which readers can contact the author. Well, dear reader, I'm not gonna invest time in putting together Php forms and such for comments until I feel this is useful; instead you just have the cute little animated gif to the left. If you write interesting things about the content here, I'll post your comments (whether you like it or not).
[link][no comments]
Television is a medium whereby data is sent from a few central points to a multitude of receiving machines. The reader may judge for him/her/itself, but people on the receiving side are often characterized as passive, mindless consumers.
The internet is a set of computers which use a standardized communication method to exchange data. Any computer on the network can address every other computer, and serve or receive data with its peers. There are some standards as to how that data gets shunted around, but the flow of data is basically arbitrary.
Now, the reader's experience with the internet is probably more like the definition of television than the definition of internet. You go to a website like nytimes.com or salon.com or hornywetmidgets.com and information is beamed in to your house, and you consume that information. Oh, you can use the Net like the mail to send one-to-one emails, and many web sites do have interactive details such as the `add to cart' button, but the flow of information is basically one way.
There are many forces out there trying to keep it as much like TV as possible. The majority of digital-protection schemes which protect the members of the RIAA and the MPAA will have the side-effect of making the Net more like TV. For example, the peer-to-peer networks that we read about in the news every day exactly fit the internet definition above. A site such as itunes.com, where you can download music that they put out for you, is a closer fit to the above definition of television.
But I digress. In Internetland, everybody can be a content provider to everybody else. Those who think this is how it should be can all have a blog.
Within the grand scheme of human history, this is new.
Nice, democratic people that we are, we like to think that everybody should have a voice, all the time. But that one isn't entirely obvious. It's like libertarianism: hoardes of free marketeers insist that the world would be a better place with zero regulation, but such a state has never, ever existed. [As a reply, a few thousand libertarians are trying to make one.] Equal access to public media has also never existed.
And the truth is, that if you give everybody a chance to talk, most of them will, indeed, talk about the completely banal, idiotic, or vaguely offensive. [I'd give examples, but how to cull it down?] So you get people who complain about the bloggers, saying that the Net is filled with blog noise from self-appointed experts such as this arse.
But people are really good at filtering dumb content. Yeah, they still think Fox News is Fair and Balanced (tm), but I expect that even that facade has been cracked, as they keep suing other content providers who parody them, such as Fox Broadcasting. [Ex post note: this lawsuit was just a joke by Matt Groening. But I'm leaving the darn links.] Or to give an example on the other end of the production spectrum, most people, when happening upon a Chick publication lying around, will successfully gather the clues and work out that this is the work of a crackpot.
Despite the innovative features, online readily follows traditional media this way. I have full faith in the abilities of those who stumble upon this to realize that even though I'm a world authority on the application of Bayesian updating to models of simultaneous conviviality, that doesn't give me the slightest license to blather endlessly on why Jack Snow is annoying.
More meta: With that in mind, I've submitted the site to Google, which I count as the blog going live, as complete strangers will now stumble upon this work and be forced to work out whether it's worth reading or not. We'll see where it goes. [By its own purchases, Google seems OK with blogs, by the way.]
I have to admit that most of what I look for in web sites myself is the TV-like sort of thing, wherein I watch words come up and look at them while I'm eating. Y'know, sentences that you don't have to read all the way through because you have something to click on in the middle of each of them. I guess that's what I'm providing, and that's OK.
Despite my lack of authority, you're hopefully finding some entertainment value in these pontifications. One reader suggested that I shoot for something more personal and less beat-you-about-the-head-and-neck witty, but it's sorta hard to put personal content here. A simple `I still think about `Lissa Tom a lot' would probably deeply disturb some subset of the world's population. I certainly don't want to end up like these characters.
Oh, and while we're on the subject of this document, the reader will note that I'm only updating on even-numbered days, thus saving the reader the endless torment of hitting over and over again on at least the odd-numbered days. See, I really do care.
[link][no comments]
Comment!
Yes, the comment box is tiny; write in a real text editor then just cut and paste here. If you are a human, type the letter h in the first box.
h for human:
Name:
Remember personal information?
This is actually the third time I've tried writing this `why I write didactic essays' essay. I think I'm afraid of inspecting my actual motivations too closely. On the one hand, a didactic essay places the author above the reader, in a `look what I know and you don't' kind of way. On the other hand, if the essay is effective, the author and reader are on an even footing at the end of the essay, since both now have equal ownership of the content. A hard call there.
Being useful has always been a concern of mine. The world has put a whole heap of effort and NSF funds in to me, and I don't really feel that I ever really repaid it, in an amorphous, collective sense. By the usual measure of being useful, i.e., getting paid, I'm a good negative $960/month right now.
I've sent a book proposal to (name of publisher). They should get back to me this week, maybe. I'm gonna be heartbroken if it's not accepted.
Anyway, when people go to a movie, I always ask them to take notes and act it out for me when they get back. This is not a dumb joke: I would be f.ing delighted if anybody did this. E.g., Miss JAM of Alexandria, VA gave me a detailed play-by-play of the musical `Wicked', including brief musical figures, and I was delighted. Not only did I get the content of the story, which I wouldn't have had the attention span to sit through, I also got to enjoy the affective fun of having a pal tell the story instead of watching attractive strangers from New York acting the thing out. Similarly with seminars: I'd always try to get the executive summary from pals who'd gone, and would always volunteer to give the executive summary for those seminars I'd attended.
In other regards, this has always been sort of my ideal manner of transferring information: struggling with primary sources or textbooks, and then telling pals all about it. It's efficient and fun, when everybody is willing to play along; it also either appeases my desperate desire not to be beneath others (like my professors) or my desperate desire for an egalitarian society (among my peers).
Conversely, my brain is filled with heaps upon heaps of useless information, and something about explaining it to a pal makes it feel less useless when they agree that it's interesting and useful. For those few moments when we sit in mutual admiration of a fact about the world, my life of collecting dumb information doesn't feel like a complete waste.
I attempted to explain one of my favorite facts, the Central Limit Theorem, to Miss STA of Prague, Czech Republic, and she was actively not interested. I almost cried.
public This guy makes a brilliant point about magazine articles: "I had begun to notice that people refer to a magazine article by mentioning the magazine, not the author, but with a book they typically don't remember the publisher, but only the author[...]." In this context (but another post) the guy explains why RSS saves us: it lets us pick authors that we like and design a nameless, virtual newspaper/magazine which is entirely by the people we are most interested in. Our virtual magazine can even have lots of comics (see the links page) and Dave Barry. It gives me that 90's optimism that yes, the Web really can revolutionize publishing and information dissemination.
Remember the `zine revolution, where a collection of a few people printed stuff up and made their pals read it and also left it at the bookstore hoping that a few strangers would also read a few pages? There's blogging with RSS for ya.
private So I myself have now been using an RSS reader for a little over a week. The results? My apartment is much cleaner, and I have no dishes lingering in the sink. I think I'm like a lot of people in that I guide my life based on the item on my `to do' list that is the least onerous at the moment. This had meant hitting <F5> on Paul's blog and seeing if he's said anything in the last five minutes, but now that's entirely obsolete, since the RSS reader does that automatically. As much as I love chycks in eyeliner, even that site from a few days ago has become onerous.
In fact, generally, looking for new content is among the most onerous things I can think of. As much as I may give the impression otherwise, I hate clicking on things and hoping they'll turn up something good; I really do think 90% of the content online is crap; and buying stuff online is so painful at this point that I'd rather go without than suffer the requisite half an hour of aimless clicking that goes into buying anything with plastic or silicon parts.
And so, having barred the joy of <F5>-ing the sites I really do like, I'm down to sweeping my floor and doing dishes. I guess it's sort of a geek thing to do, to automate and make efficient your downtime (here's a great example).
Oh, and I also read the NYT and the Economist more, since they now push themselves to me rather than requiring that I click on a link. I am thus notified within half an hour any time a U.S. serviceman dies in Iraq.
virtual I bought a big pile of records the other day. I'm increasingly feeling what the luddites of old said about CDs: they're just not fun compared to records. There's no tactile joy, nothing to do with your hands or your eyes. The little CD booklet really doesn't compare to the big square sleeve that hipsters have lately taken to framing and hanging on the wall. There's no ritual to putting a CD in the little motorized tray. As previously noted, if you have to get up every twenty minutes to flip the darn record, you're more likely to listen compared to just putting on a playlist in the background.
To go even further, walking through Chinatown in Manhattan a month or two ago, I happened upon a pile of 78 RPM records, from circa 1915-1925. They do indeed put the records of the 80s to shame: these things don't wobble or bend, and they weigh something substantial. They feel good to hold. These 78s are vaguely Jewish in nature, like Cohen calls his tailor on the 'Phone (comedy monologue, it says) and the Yiddisher klezmer orchestra. I wish I coud hear them.
I was raised more on CDs, though, so the step from CDs to MP3s on a hard drive was a trivial one, since pushing little plastic buttons and clicking on the picture of a button are about the same experience. Now I've got an efficient, streamlined system for playing music that involves absolutely no tactile involvement at all. Perhaps this is why I'm so into good computer keyboards---but compare the keys on your keyboard with the keys on a piano (not to be confused with a MIDI keyboard). In the end, convenience and cheapness will always win out over tactile fun. That's why CDs made records basically disappear, and why MP3s threaten to make the entire concept of music purchased with a tangible physical medium obsolote.
For me, this brings up two questions: first, how far will the virtualization of things go? Will all our media be on screens and speakers; our cars, tools, and other assorted things with buttons replaced with little touch-screens and voice commands; the soft parts replaced by pictures of soft parts; and once-heavy things like glass jars, wood furniture, and telephones replaced with cheap, light, and fully functional plastic counterparts? What'll be left? Which brings us to the central question:
The visitors from the future are always drawn as having gigantic heads and tiny hands. I wonder if the future really is in not touching things. I guess it can go one of two ways. We may not care at all, since our heads are getting bigger, or we may start to care much more about the things that are basically impossible to replace with non-tactile substitutes: clothing, food, people.
Which is how my RSS feed has made my life better: by streamlining the way I waste time online, I'm forced to read physical books, put my hands under running water, play records, and live more in the tactile world.!)
OK, so the content management system keeps track, and this is the hundredth entry.
What I'd had here: I had written up an appropriately self-absorbed analysis of the situation to date: me, the audience, our interaction. I'd posted the winners among this month's oddest search terms: persuasive essay about gallstone i hate my students young teen girls liking another girls boobies crusades pictoral gays are rapping by pictures optimal griping position [That was the end of November. This month: ecuadorian dwarves.]
I'd talked about the effect that writing on a regular basis has had on my thought process and my writing ability. The big winner among ways my writing has improved by writing sort-of-essays on a sort-of-regular basis is that I cut more. I used to think that every frigging thing I'd written was golden. I mean, I'd put effort into constructing the sentence just right, and now it's so delightfully clever---the reader would be so much worse off if such beauty weren't brought to light.
So yeah, I cut more. There are paragraphs and sections in the dustbin, and even entire half-entries which just never went anywhere, or never said anything that others haven't already said better, or that just didn't feel good---like the entry that used to be here before I deleted it all.
Small scale: The medium one writes with needs a method of turing an undesirable paragraph into an invisible comment. It is much easier to say `oh, I'll just set aside this paragraph for now' than `I'll just irrevocably delete what I'd jut written'. That is, if my writing tool allows commenting, my output will be of higher quality.
[The tech details: Word and OpenOffice users: don't send out DOC or SXW files. If you save as a PDF, then your bitchy asides and bad writing are safe. [How to save a DOC as a PDF: download OpenOffice.org, open your Word document with it, click file|export.] HTML is half-OK, since people never read the comments unless they're really bored. If that describes you, then let me confess that I myself have some nontrivial comments in many entries. TeX users, put \long\def\comment#1{} somewhere, and then \comment{stuff} will work (but be careful about spacing).]
Large scale: I've been posting less frequently lately, partly because I have so many things I've already said, but partly because my quality control is higher. It gets back to the root question of what a blog is supposed to be, exactly. Unlike (daily or weekly) TV or (weekly or monthly) magazines or any other medium that I can think of, the blog does not need to be updated regularly.
I'm reasonably confident that in the near future, I will be able to produce interesting content; however, I have absolutely no faith that in any given seven-day period I will produce anything of interest at all. And this is where RSS saves me: I don't have to make sure that I have something every day or week to keep you interested, `cause when I have something, the RSS feed will tell you. And so, RSS makes me a better writer.
[Tech: So if you don't have an RSS reader, get thee to Bloglines and set yourself up. There are probably at least a half dozen other irregularly-updated sites which you read, so a centralized site-checker will pay off quickly.]
The moral is that although our modern technological world has given us the ability to cheaply produce reams of cheap content, in a few ways it's also given us the ability to filter and throw away content. On balance, I think I'm a better writer for it.
My faves Since this is the navel-gazing entry, I wanted to give those of you who weren't here from day one a brief list of favorites from the archive, since I've written well over a novel's worth of text and you're probably not going to read it all. So here are the entries that score high in importance, utility, or reader popularity. Rereading, I think a few sentences could be cut from all of them.
10/14/2004: Does Economics make people evil? 09/16/2004: Cohen calls his tailor on the `phone 09/09/2004: Neoclassicism watch 08/10/2004: Comparative advantage and capital07/08/2004: Debate suggestions 06/02/2004: Yet another entry about drug access restrictions. 05/18/2004: Accounting for humans 05/12/2004: Measuring attractiveness 04/06/2004: Instrumental music measures 03/30/2004: Floating in midair 01/14/2004: The legacy of the French 12/18/2003: Israel I 11/28/2003: The perception of causation
Next time I'll get back to the usual alienating overtechnical detail.
[link][a comment]
on Saturday, December 4th, zoe said
I also liked "I just wasn't made for these times" and "The CLT again"
[PDF version]
The editorial page of your favorite newspaper or magazine is primarily
(but not 100%) push-driven. Editors don't solicit editorials; editorials
solicit editors.
Here's the timeline: I wrote a 700-word op-ed on Tuesday, and sent
it to the think tank's Communications department, where we have a few
people who work full-time on placing op-ed pieces in the newspapers.
Ms AM wrote up a polite cover, and emailed it to the editors of a paper
or two (I don't know how many). The editor of the Wall Street Journal
wrote back on Friday, saying that he'll run the thing as a letter. He
cut a few hundred words, sent it back to me and Ms AM for approval,
I made two tweaks, the editor prepended a sensational headline that I
did not approve, and it ran in today's paper.
Among the columns pushed upon him or her, what will an editor pick? No
surprises: the work will have to be apropos to current news, and
will have to be sensational. Simmering-but-not-boiling issues will
not run. Moderate opinions will not run. Or at
least, as in the case of my editorial, relatively moderate opinions will
be revised to sound as sensational as possible.
The trouble with patents has been building for a decade, but it hasn't
been in the mainstream press until the whole thing about the Blackberry
hit. Now, it's easy for me to get op-eds printed, because disaster is
already starting to strike. But wouldn't it be great if people could
have gotten press five years ago about how trouble like the Blackberry
case is on its way? But punchiness really does force the press to be
reactive instead of proactive.
The guys on Capitol Hill want desperately to be proactive. They're smart
folks, and many of them care about good policy. That means that the press,
to the extent that it goes after what happened yesterday, is of limited
relevance to policymakers. Conversely, to the extent that rulemaking
is about obscure details of legal code, policymakers are assured that
general media will not molest them.
TV and radio are only worse. They have a hard-and-fast time constraint,
meaning that they have no choice but to be on the low-detail end of
the spectrum. A five-minute piece can not have much more content than
a one-page op-ed, which is not much. I've done a few interviews for the
nice people at NPR. One went for half an hour, and my final on-air time
in the three-minute piece was a single sentence--I didn't even get a
semicolon. Last week, I got a call where I was explaining the situation
to a radio reporter, and she said, exasperated, “We've been talking for
thirteen minutes now and I still don't have a good ten-second clip.” I
wound up getting cut from that one entirely.
You don't need me to tell you this, but details are anathemic to
punchiness, and so are going to be lost. If your idea is too complex
for a single sentence, it's evidently not worth the listener's time.
I'm mostly whining because before I started dealing with media folk on a
regular basis, I didn't think that it would all be so true. Every
time I deal with generalist media people, I feel pressure (often explicit)
to round off details and say caustic and sensationalist things. When I
get off the telephone or hit the send button,
I fret about how the journalist at the other end is going to spin and
simplify me until I disagree with myself.
So, am I going to stop talking to media folks and stop submitting
oversimplified op-eds? Of course not. If I want Congress to do
anything, or if I want to get grants or continue writing, I need media
appearances. It's how we keep score. For many people, the mental shortcut
to answer the question is this person worth talking
to? is to reduce it to has this person been
published in/by something I've heard of? The first question is
about whether the person knows the topic in depth, while the second
is about whether the person can convince an editor that he or she can
summarize information for a general audience. But it is an ingrained
heuristic, rooted in observation biases that one could characterize as
basic human nature, and I can't imagine a future where such tendencies
magically disappear.
So it's not going to go away. There will always be a need for generalist
media, and generalist media will always be better-recognized and more
widely read than specialized media, and to maximize audiences they
will chase ambulances and oversimplify. Further, people like me have
a strong incentive to play along even though we really hate to, because
so many people equate widely-read with authoritative.
This is part three of three.
It will make the most sense if you maybe look over part I,
Anatomy of an
op-ed
and part II, Anti-intellectual.
When I ask people what they do, the most interesting answers are verbs.
I don't care that you're an assistant executive manager for BungleCo.
What have you been doing for the last eight hours? Have you
been talking to people? Organizing papers? What conflicts do you need
to resolve?
Conversely, when I tell people that I work at a think tank, many of
them are entirely unconcerned with what I actually do during the day,
because they already have the correct image of me staring at a computer
screen until my eyeballs hurt. The real mystery: where does the money
come from? How does somebody make money at a place where people just
sit around and, um, think?
Writing doesn't pay the bills. If you get a few hundred bucks for an
op-ed, you should be delighted. If you put out a magazine article a
month, you can make a living, but then you're a full-time journalist
and don't have time for anything else. The book? I've made more on
Amazon referral commissions than royalties for writing the thing. From
a business perspective, the press placements are all just advertising.
Not everybody thinks they know all there is to know about knowing
things. There are people who appreciate an expert. They realize that
the most efficient means of doing things is a division of labor where
they produce widgets and when they need a policy expert, they hire one,
rather than thinking they can study up on the subject in their spare time.
So when does somebody need an expert in a given policy? When they have
a deeply-held opinion, and need somebody to espouse it. By finding an
expert who happens to agree with them, the expert gets funded and the
interested party gets support on its beliefs. And that is where all those
studies funded by the most obvious donor come from. Since I know the
software patent debate well, I can point to a pro-software patent study
or two that says “We are grateful to Microsoft for their support” on
the cover. Some read this and presume that MSFT found somebody to speak
for them, and then purchased their opinion. But the flow probably went
the other way: the expert formed his opinion (I have in mind two guys,
one of whom I know), and then approached Microsoft about maybe providing
funding for the research.
This is how the funding for many a study happens: first, the expert
does research until he knows the subject well. He has formed his
honest best opinion about the subject. He starts writing up a few
pages. Then, he shops it around.
Dear philanthropic
organization/corporation/wealthy individual: I have an opinion, and can
state it eloquently and with authority. Further, that opinion happens
to match yours perfectly! What a wonderful coincidence. If you'd like me
to continue fleshing out this idea which I personally hold, then please
send cash.
The expert is independently deriving his opinion, but the funding
certainly has great potential to corrupt the expert's research. First,
there are the details to be negotiated, wherein funder and researcher
agree on the broad concept, but there may be details on which they
differ. Second, there is the problem of the non-unitary actor. You know
that guy that MSFT funded because they agree with him? We're coworkers,
to the extent that you'd call this work. When I plug in my laptop to
write articles opposing MSFT's IP position, MSFT chips in for the juice.
There are a few approaches to the conflict. I'm happy to say that in
my case, the administrators at my think tank are well aware that my
writing disagrees with the position of one of its funders, and at no
point have they asked me to tone down my bitching. They care more about
doing independent research than any one donor, and know that the only
way to please all the donors all the time is to never say anything.
Another approach is to take such a firm opinion that there's no way to
budge. Are there orthodox economic motivations for government regulation?
Absolutely. Will you hear about any of them from the Cato Institute?
Funders know the answer to that one, and know not to bother asking.
The final approach, of course, is to fold to pressure. I could only guess
at how often this happens. To keep a parallel essay form, I should give
an example here, but that would be rude.
The other way that the 'formulate hypothesis, then find funding' approach
can create bias is in the suppression of certain ideas. This is no
conspiracy theory suppression, but the simple fact that publicizing an
idea needs both an expert to formulate it and a funder to pay for it.
You can find an expert somewhere that espouses any given idea,
but the business side has a whole lot more money than the rest of
us, so why doesn't the policy world turn into a gigantic pro-business
alliance? First, the funding for the pure social benefit is surprisingly
large. There are general funds like MacArthur, Ford, Soros, Hewlett,
and while we're talking MSFT, the Gates Foundation, that have little
or no interest in supporting moneyed interests. Any one of these funds
could keep several think tanks running for a long time to come.
Second, there's two sides to every issue. Say Company A has a
labor-intensive process to produce pollutants, while Company B has a
giant machine that was built in Japan to produce the same pollutants.
Company A will be happy to support bills that espouse anti-business
import tariffs because they would hurt Company B more; Company B will be
happy to support higher minimum wage laws, because doing so is handing
a charge to its competitor. As for the overall corporate tax rate,
you won't see much disagreement.
Thus, the problem of getting funding for policy research (and the problem
of policy design in general) is finding the mega-rich interests that
happen to agree with your belief. For any sufficiently detailed question,
there will be some balance between the funders.
Others are interested in access for the sake of keeping engaged.
People want to be surrounded by folks who are beautiful and smart; the
think tank ain't doing much for the beautiful part, but has its share of
smart folks who can say an interesting thing or two. There are people
who will contribute to be a part of that. The administrators describe
these folks as individuals who “get it”, where “it” is the value of good
research, regardless of the bias of that research. If this were Broadway,
I suppose we'd call these guys angels.
There's also the funding from the pure research supporters, such as the
National Institute of Assorted, which is not nearly as exciting. Though,
it's a chance to mention an interesting paradox that applies to academic
work in general: nobody will fund a study that doesn't have a good idea
of the expected conclusion. You can't do the research until you've
got the funding; you can't write a good proposal until you've done the
research. The academics who can unravel that knot live in big houses.
on Monday, May 1st, Greg Harris said
Ben,I found your blog log through Katie's. Thanks for moving her going away party to a new level of memorable. Later,Greg
You all know
good ol'
Wikipedia, but there are also
Wikibooks.
As you browse through the books at that site, you'll notice two things:
they aren't very complete (most are half an essay at best), and they aren't
very good.
I'm not going to talk about the reliability and authority issue which
seems to dominate most discussion of wikimedia. Personally, if I'm
reading to get a lite intro to a subject of which I'm ignorant, I'll
take Wikipedia as gospel, because it doesn't matter; if I'm working on
an academic topic, then I'm not going to cite an encyclopædia
of any sort, but will have my own external sources providing detail.
You no doubt have your own sense of what is or is not reliable.
Instead, I'm going to talk here about why the deck is stacked against
wikibooks and other attempts to apply the open source idea to every
field of endeavor.
The average entry on Wikipedia is between a single line and a few
pages long. They have limited narrative depth at best, and generally
just cover a simple list of facts. Although wikipedia would be
thousands of pages if printed out in its entirety,
nobody is expected to have edited anything beyond a sliver, and
nobody expects it to have any structure beyond alphabetical order.
Figure one: Wikiart from the
surrealists.
[Photo credit]
Computer code is much like this: a person working on one subpart of
a program doesn't have to know anything about how the other subparts
work. To write a translator, Jane can work on text parsing, Joe can work
on a set of dictionaries, and Jess can work on the clicky interface,
and all can work with little regard to what the other parties are doing.
Narrative works don't have such wonderful compartmentalization. Sure,
there are chapters, but if the chapters don't tightly come together, we
won't like the darn story much.
You ever play the Exquisite Corpse? You fold a paper in thirds, and draw
a head, and then refold so the head isn't visible and hand the paper to
a pal who draws the torso, and then your pal hides the torso and another
pal draws the waist and the legs. Then you unfold it all and laugh about
how delightful such a disjointed figure could be. If you were lucky
enough to be one of the founders of the Surrealist movement, then your
drawing will wind up on the wall of the Art Institute of
Chicago (see figure). But for the rest of us,
the game is a fun brainstorm but ain't a final work.
Anthologies are common enough, but we often call them edited
volumes and put the editor's name on the cover to remind the reader
that somebody sat down and made sure that the elements somehow cohered.
We're used to other aggregate works directed by one individual: pop
songs that have a single producer and movies with one director. I leave
to the reader the debate over the quality of songs written via jamming
with the band versus songs written by a single composer.
OK, there's your survey of media. Painting, sculpture, movies, music,
novels, all involve one or a small number of people directing a
final product, which may have been touched by dozens of hands. This is
not surprising, and I don't think anybody seriously expects wikipainting
to truly surpass the old method.
But textbooks. There seems to be a serious belief that a textbook can be
collaboratively written by a committee. This is not a new wikiconcept.
In elementary school, we all had many a textbook with no author or editor on
the cover, and a list of committee members on the title page.
Those textbooks sucked.
We often refer to a subject like math or biology as a field. Picture a
big expanse of plain, in which you could take any direction. When we go
to school, we take courses--carefully guided paths through an
open expanse. In other words, a good textbook goes somewhere. It is a
narrative.
Conversely, some textbooks attempt to survey the entire field at once.
Such books are frankly no longer textbooks, but are rightly called
references. They have their place, but it ain't teaching. I can see the
appeal for the textbook writers, who want to maximize their market share.
They provide as much material as possible in the hopes that the teacher
will select a course through the material; some teachers do, covering
only chapters 1.3, 3.8, 8.1, and 16.4, while others wind up ploughing
through the entire field, column by column. [If you are reading this
in book form, I've put effort in to cohering the essays into something
of a few narrative threads. Really.]
The wikimethod is good for writing references but bad for writing
narratives, so the deck is stacked against wikitextbooks.
Again, like the encyclopædic texts, they have a valid and valuable
place on the e-bookshelf, but they can't replace narrative works, just
as (conversely) we wouldn't read a single narrative and claim that we
understand the entire field.
Of course, it's not so simple. The real success stories in open
source come from a single good idea, some good coding, and lots of good advertising
and self-promotion. Of course, it also helps if your program is about
porn.
Out of a thousand readers, over 990 won't fix so much as a typo, and a
handful will make little ten-second fixes on a single equation or
such. If you're lucky, maybe a single reader out of every few thousand
will contribute the significant time investment to contribute a narrative.
Open source provides a new alternative to finding and coordinating coauthors,
but it's not particularly a revolution over existing coauthoring
tools (diff, revision control, those cute little change tracking features
in word processors). The fact remains that a narrative is best written
by a small number of people in close communication.
And if you're a publisher, take this as a prospectus. Quirky
books by economists are hot these days.
Given that I only have about two friends, this is a bit
mystifying. So, ¿who are you people? and ¿what do you people
want from me? Please, take twenty seconds and answer those questions in
the ornery comment box below. Feel free to omit your email address, use
just your initials, or otherwise not tell me who you actually are. But
if I have a better idea of who's reading and why, I'll be able to write
better stuff in the future.
on Tuesday, November 28th, techne said
hello. I read your blog.
on Wednesday, November 29th, Cocoa said
Like Techne, I have been known to read your blog. Here are some things I'd like to know:1) How to get a person on the phone (instead of voice-activated-commanding-computer-lady).2) Where and/or how to 'build' my own computer.3) Will there be peace in Israel?4) How I can retain more of what I read and/or deciding what is important from all of the crap out there. I understand that you may not be able to answer these questions (based on their somewhat rhetorical nature). But you asked, so I answered.
Also, I'd like to know how to turn the center-align default off my comment. Thanks
on Thursday, November 30th, Derrick said
Hi. Guess what? I'm reading. By the way -- Cocoa may be interested to know that you can often bail out of Voice User Interfaces (a.k.a. "voice-activated-commanding-computer-lady") by screaming your head off into the receiver. These things have models built in to detect user frustration, and route really pissed customers to humans. Pressing buttons randomly works pretty well too, but screaming is a lot more fun.
on Thursday, November 30th, DH said
I still read!!! I loved the last one :)
on Thursday, November 30th, Miss ALS of San Diego said
i found you during a drunk googling episode. somehow you ended up in my bookmarks.alcohol is great for making pals.
on Saturday, December 2nd, SueDoc said
I want more of your favorite non-legume recipes, because I am allergic to soy and peanuts but I would still like to cut down on my dead animal consumption. But I like just about everything else you post, too. I am not picky.
on Monday, December 4th, h for hi said
I merely want to protest the use of the bracketing question marks while using italics, as well. What a waste. It defeats the entire purpose of double q-marks. You know Spanish, but, you don't.Best,h(human)
on Friday, December 8th, Andy said
I think you should retitle this series "omphaloskeptical entry" part x, y, z...
|
http://fluff.info/blog/arch/cat-blogs.html
|
crawl-001
|
refinedweb
| 7,271
| 69.72
|
Seemingly unused qualified import affects method visibility
Here is a simple test case:
module MyLib where class MyClass a where myMethod :: a -> a
module MyModule where import MyLib (MyClass) --import qualified MyLib as L data Foo = Foo instance MyClass Foo where -- error: ‘myMethod’ is not a (visible) method of class ‘MyClass’ myMethod Foo = Foo
Since I have only imported
MyClass and not its methods (that would be
import MyLib (MyClass(..))), the error is correct,
myMethod is not visible. But if I uncomment the
import qualified MyLib as L line, the error disappears even though I do not use
L anywhere. Writing
L.myMethod Foo = Foo is not even legal!
I filed this under "confusing error message", so let me show you the conditions under which the above behaviour was confusing. We were using classy-prelude instead of
Prelude, but we were not familiar with all the differences between the two preludes. We started with code like this, which did not compile:
{-# LANGUAGE NoImplicitPrelude #-} module MyModule import ClassyPrelude data Foo a = Foo instance Foldable Foo where -- 'foldMap' is not a (visible) method of class 'Foldable' foldMap = undefined
So we clarified that we meant
Prelude.Foldable, in case
ClassyFoldable.Foldable meant something different.
{-# LANGUAGE NoImplicitPrelude #-} module MyModule import ClassyPrelude import qualified Prelude data Foo a = Foo instance Prelude.Foldable Foo where foldMap = undefined
This compiled, so we first thought that
Prelude.Foldable and
ClassyPrelude.Foldable were two different type classes, but we later discovered that
ClassyPrelude.Foldable is a re-export of
Prelude.Foldable. So the following means the same thing and also compiles:
{-# LANGUAGE NoImplicitPrelude #-} module MyModule import ClassyPrelude import qualified Prelude data Foo a = Foo instance ClassyPrelude.Foldable Foo where foldMap = undefined
At this point, the qualified
Prelude import doesn't seem used anywhere, so we thought it was safe to remove it:
{-# LANGUAGE NoImplicitPrelude #-} import ClassyPrelude data Foo a = Foo instance ClassyPrelude.Foldable Foo where -- 'foldMap' is not a (visible) method of class 'Foldable' foldMap = undefined
But
ClassyPrelude.foldMap is not the same as
Prelude.foldMap, so this did not compile and it wasn't clear why.
One way to make this less confusing would be to allow qualified method names; this way, we would have tried both
Prelude.foldMap = undefined and
ClassyPrelude.foldMap = undefined, and we would have discovered the source of the problem.
|
https://gitlab.haskell.org/ghc/ghc/-/issues/14629
|
CC-MAIN-2021-17
|
refinedweb
| 386
| 54.52
|
I get a file name from a user & upload the file for him/her, My problem is that due to my code, User should enter the file name to upload it, But I want to search more carefully & upload all files that their name is like the name user entered, How I can write it instead of this code?
Example : When user type Biology, The programm should upload files that are like Campbell Biology, My Biology Or ...
I need something LIKE Statement in SQL ...
try:
requested_file = open(str(args[0]) + '.pdf', 'rb')
It seems you want to get all files which contain the particular search string the user enters.
There are two options, the second one being more thorough than the first.
Option 1:
glob.glob.
You can use the
glob.glob function, passing wildcards:
import glob search = ... # your term here for files in glob.glob('*%s*.pdf' % search): ... # do something with file
Option 2:
re.search with
os.listdir:
You can traverse your present directory and filter with regex.
import os import re pattern = re.compile('.*%s.*\.pdf' %search, re.I) for files in filter(pattern.search, os.listdir('.')): ... # do something with files
The second option offers you a little more flexibility.
glob is limited by the wildcard syntax.
|
https://codedump.io/share/QfOwDLNw3qTw/1/how-to-search-more-carefully-in-files-with-python
|
CC-MAIN-2020-40
|
refinedweb
| 210
| 77.53
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.